id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_1611_3 | /* t1disasm
*
* This program `disassembles' Adobe Type-1 font programs in either PFB or PFA
* format. It produces a human readable/editable pseudo-PostScript file by
* performing eexec and charstring decryption as specified in the `Adobe Type 1
* Font Format' version 1.1 (the `black book'). There is a companion program,
* t1asm, which `assembles' such a pseudo-PostScript file into either PFB or
* PFA format.
*
* Copyright (c) 1992 by I. Lee Hetherington, all rights reserved.
* Copyright (c) 1998-2013 Eddie Kohler
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, subject to the
* conditions listed in the Click LICENSE file, which is available in full at
* http://github.com/kohler/click/blob/master/LICENSE. The conditions
* include: you must preserve this copyright notice, and you cannot mention
* the copyright holders in advertising related to the Software without
* their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS
* OR IMPLIED. This notice is a summary of the Click LICENSE file; the
* license in that file is binding.
*
* New change log in `NEWS'. Old change log:
*
* Revision 1.4 92/07/10 10:55:08 ilh
* Added support for additional PostScript after the closefile command
* (ie., some fonts have {restore}if' after the cleartomark). Also,
* removed hardwired charstring start command (-| or RD) in favor of
* automatically determining it.
*
* Revision 1.3 92/06/23 10:57:53 ilh
* MSDOS porting by Kai-Uwe Herbing (herbing@netmbx.netmbx.de)
* incoporated.
*
* Revision 1.2 92/05/22 12:05:33 ilh
* Fixed bug where we were counting on sprintf to return its first
* argument---not true in ANSI C. This bug was detected by Piet
* Tutelaers (rcpt@urc.tue.nl). Also, fixed (signed) integer overflow
* error when testing high-order bit of integer for possible
* sign-extension by making comparison between unsigned integers.
*
* Revision 1.1 92/05/22 12:04:07 ilh
* initial version
*
* Ported to Microsoft C/C++ Compiler and MS-DOS operating system by
* Kai-Uwe Herbing (herbing@netmbx.netmbx.de) on June 12, 1992. Code
* specific to the MS-DOS version is encapsulated with #ifdef _MSDOS
* ... #endif, where _MSDOS is an identifier, which is automatically
* defined, if you compile with the Microsoft C/C++ Compiler.
*
*/
/* Note: this is ANSI C. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#if defined(_MSDOS) || defined(_WIN32)
# include <fcntl.h>
# include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <errno.h>
#include <assert.h>
#include <lcdf/clp.h>
#include "t1lib.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char byte;
static FILE *ofp;
static int lenIV = 4;
static char cs_start[10];
static int unknown = 0;
/* decryption stuff */
static uint16_t c1 = 52845, c2 = 22719;
static uint16_t cr_default = 4330;
static uint16_t er_default = 55665;
static int error_count = 0;
/* If the line contains an entry of the form `/lenIV <num>' then set the global
lenIV to <num>. This indicates the number of random bytes at the beginning
of each charstring. */
static void
set_lenIV(char *line)
{
char *p = strstr(line, "/lenIV ");
/* Allow lenIV to be negative. Thanks to Tom Kacvinsky <tjk@ams.org> */
if (p && (isdigit(p[7]) || p[7] == '+' || p[7] == '-')) {
lenIV = atoi(p + 7);
}
}
static void
set_cs_start(char *line)
{
char *p, *q, *r;
if ((p = strstr(line, "string currentfile"))) {
/* enforce presence of `readstring' -- 5/29/99 */
if (!strstr(line, "readstring"))
return;
/* locate the name of the charstring start command */
*p = '\0'; /* damage line[] */
q = strrchr(line, '/');
if (q) {
r = cs_start;
++q;
while (!isspace(*q) && *q != '{')
*r++ = *q++;
*r = '\0';
}
*p = 's'; /* repair line[] */
}
}
/* Subroutine to output strings. */
static void
output(const char *string)
{
fprintf(ofp, "%s", string);
}
/* Subroutine to neatly format output of charstring tokens. If token = "\n",
then a newline is output. If at start of line (start == 1), prefix token
with tab, otherwise a space. */
static void
output_token(const char *token)
{
static int start = 1;
if (strcmp(token, "\n") == 0) {
fprintf(ofp, "\n");
start = 1;
} else {
fprintf(ofp, "%s%s", start ? "\t" : " ", token);
start = 0;
}
}
/* Subroutine to decrypt and ASCII-ify tokens in charstring data. The
charstring decryption machinery is fired up, skipping the first lenIV
bytes, and the decrypted tokens are expanded into human-readable form. */
static void
decrypt_charstring(unsigned char *line, int len)
{
int i;
int32_t val;
char buf[20];
/* decrypt charstring */
if (lenIV >= 0) {
/* only decrypt if lenIV >= 0 -- negative lenIV means unencrypted
charstring. Thanks to Tom Kacvinsky <tjk@ams.org> */
uint16_t cr = cr_default;
byte plain;
for (i = 0; i < len; i++) {
byte cipher = line[i];
plain = (byte)(cipher ^ (cr >> 8));
cr = (uint16_t)((cipher + cr) * c1 + c2);
line[i] = plain;
}
line += lenIV;
len -= lenIV;
}
/* handle each charstring command */
for (i = 0; i < len; i++) {
byte b = line[i];
if (b >= 32) {
if (b >= 32 && b <= 246)
val = b - 139;
else if (b >= 247 && b <= 250) {
i++;
val = (b - 247)*256 + 108 + line[i];
} else if (b >= 251 && b <= 254) {
i++;
val = -(b - 251)*256 - 108 - line[i];
} else {
val = (line[i+1] & 0xff) << 24;
val |= (line[i+2] & 0xff) << 16;
val |= (line[i+3] & 0xff) << 8;
val |= (line[i+4] & 0xff) << 0;
/* in case an int32 is larger than four bytes---sign extend */
#if INT_MAX > 0x7FFFFFFFUL
if (val & 0x80000000)
val |= ~0x7FFFFFFF;
#endif
i += 4;
}
sprintf(buf, "%d", val);
output_token(buf);
} else {
switch (b) {
case 0: output_token("error"); break; /* special */
case 1: output_token("hstem"); break;
case 3: output_token("vstem"); break;
case 4: output_token("vmoveto"); break;
case 5: output_token("rlineto"); break;
case 6: output_token("hlineto"); break;
case 7: output_token("vlineto"); break;
case 8: output_token("rrcurveto"); break;
case 9: output_token("closepath"); break; /* Type 1 ONLY */
case 10: output_token("callsubr"); break;
case 11: output_token("return"); break;
case 13: output_token("hsbw"); break; /* Type 1 ONLY */
case 14: output_token("endchar"); break;
case 16: output_token("blend"); break; /* Type 2 */
case 18: output_token("hstemhm"); break; /* Type 2 */
case 19: output_token("hintmask"); break; /* Type 2 */
case 20: output_token("cntrmask"); break; /* Type 2 */
case 21: output_token("rmoveto"); break;
case 22: output_token("hmoveto"); break;
case 23: output_token("vstemhm"); break; /* Type 2 */
case 24: output_token("rcurveline"); break; /* Type 2 */
case 25: output_token("rlinecurve"); break; /* Type 2 */
case 26: output_token("vvcurveto"); break; /* Type 2 */
case 27: output_token("hhcurveto"); break; /* Type 2 */
case 28: { /* Type 2 */
/* short integer */
val = (line[i+1] & 0xff) << 8;
val |= (line[i+2] & 0xff);
i += 2;
if (val & 0x8000)
val |= ~0x7FFF;
sprintf(buf, "%d", val);
output_token(buf);
}
case 29: output_token("callgsubr"); break; /* Type 2 */
case 30: output_token("vhcurveto"); break;
case 31: output_token("hvcurveto"); break;
case 12:
i++;
b = line[i];
switch (b) {
case 0: output_token("dotsection"); break; /* Type 1 ONLY */
case 1: output_token("vstem3"); break; /* Type 1 ONLY */
case 2: output_token("hstem3"); break; /* Type 1 ONLY */
case 3: output_token("and"); break; /* Type 2 */
case 4: output_token("or"); break; /* Type 2 */
case 5: output_token("not"); break; /* Type 2 */
case 6: output_token("seac"); break; /* Type 1 ONLY */
case 7: output_token("sbw"); break; /* Type 1 ONLY */
case 8: output_token("store"); break; /* Type 2 */
case 9: output_token("abs"); break; /* Type 2 */
case 10: output_token("add"); break; /* Type 2 */
case 11: output_token("sub"); break; /* Type 2 */
case 12: output_token("div"); break;
case 13: output_token("load"); break; /* Type 2 */
case 14: output_token("neg"); break; /* Type 2 */
case 15: output_token("eq"); break; /* Type 2 */
case 16: output_token("callothersubr"); break; /* Type 1 ONLY */
case 17: output_token("pop"); break; /* Type 1 ONLY */
case 18: output_token("drop"); break; /* Type 2 */
case 20: output_token("put"); break; /* Type 2 */
case 21: output_token("get"); break; /* Type 2 */
case 22: output_token("ifelse"); break; /* Type 2 */
case 23: output_token("random"); break; /* Type 2 */
case 24: output_token("mul"); break; /* Type 2 */
case 26: output_token("sqrt"); break; /* Type 2 */
case 27: output_token("dup"); break; /* Type 2 */
case 28: output_token("exch"); break; /* Type 2 */
case 29: output_token("index"); break; /* Type 2 */
case 30: output_token("roll"); break; /* Type 2 */
case 33: output_token("setcurrentpoint"); break;/* Type 1 ONLY */
case 34: output_token("hflex"); break; /* Type 2 */
case 35: output_token("flex"); break; /* Type 2 */
case 36: output_token("hflex1"); break; /* Type 2 */
case 37: output_token("flex1"); break; /* Type 2 */
default:
sprintf(buf, "escape_%d", b);
unknown++;
output_token(buf);
break;
}
break;
default:
sprintf(buf, "UNKNOWN_%d", b);
unknown++;
output_token(buf);
break;
}
output_token("\n");
}
}
if (i > len) {
output("\terror\n");
error("disassembly error: charstring too short");
}
}
/* Disassembly font_reader functions */
static int in_eexec = 0;
static unsigned char *save = 0;
static int save_len = 0;
static int save_cap = 0;
static void
append_save(const unsigned char *line, int len)
{
if (line == save) {
assert(len <= save_cap);
save_len = len;
return;
}
if (save_len + len >= save_cap) {
unsigned char *new_save;
if (!save_cap) save_cap = 1024;
while (save_len + len >= save_cap) save_cap *= 2;
new_save = (unsigned char *)malloc(save_cap);
if (!new_save)
fatal_error("out of memory");
memcpy(new_save, save, save_len);
free(save);
save = new_save;
}
memcpy(save + save_len, line, len);
save_len += len;
}
/* 23.Feb.2004 - use 'memstr', not strstr, because the strings input to
eexec_line aren't null terminated! Reported by Werner Lemberg. */
static const unsigned char *
oog_memstr(const unsigned char *line, int line_len, const char *pattern, int pattern_len)
{
const unsigned char *try;
const unsigned char *last = line + line_len - pattern_len + 1;
while (line < last
&& (try = memchr(line, (unsigned char)*pattern, last - line))) {
if (memcmp(try, pattern, pattern_len) == 0)
return try;
else
line = try + 1;
}
return 0;
}
/* returns 1 if next \n should be deleted */
static int
eexec_line(unsigned char *line, int line_len)
{
int cs_start_len = strlen(cs_start);
int pos;
int first_space;
int digits;
int cut_newline = 0;
/* append this data to the end of `save' if necessary */
if (save_len) {
append_save(line, line_len);
line = save;
line_len = save_len;
save_len = 0;
}
if (!line_len)
return 0;
/* Look for charstring start */
/* skip first word */
for (pos = 0; pos < line_len && isspace(line[pos]); pos++)
;
while (pos < line_len && !isspace(line[pos]))
pos++;
if (pos >= line_len)
goto not_charstring;
/* skip spaces */
first_space = pos;
while (pos < line_len && isspace(line[pos]))
pos++;
if (pos >= line_len || !isdigit(line[pos]))
goto not_charstring;
/* skip number */
digits = pos;
while (pos < line_len && isdigit(line[pos]))
pos++;
/* check for subr (another number) */
if (pos < line_len - 1 && isspace(line[pos]) && isdigit(line[pos+1])) {
first_space = pos;
digits = pos + 1;
for (pos = digits; pos < line_len && isdigit(line[pos]); pos++)
;
}
/* check for charstring start */
if (pos + 2 + cs_start_len < line_len
&& pos > digits
&& line[pos] == ' '
&& strncmp((const char *)(line + pos + 1), cs_start, cs_start_len) == 0
&& line[pos + 1 + cs_start_len] == ' ') {
/* check if charstring is long enough */
int cs_len = atoi((const char *)(line + digits));
if (pos + 2 + cs_start_len + cs_len < line_len) {
/* long enough! */
if (line[line_len - 1] == '\r') {
line[line_len - 1] = '\n';
cut_newline = 1;
}
fprintf(ofp, "%.*s {\n", first_space, line);
decrypt_charstring(line + pos + 2 + cs_start_len, cs_len);
pos += 2 + cs_start_len + cs_len;
fprintf(ofp, "\t}%.*s", line_len - pos, line + pos);
return cut_newline;
} else {
/* not long enough! */
append_save(line, line_len);
return 0;
}
}
/* otherwise, just output the line */
not_charstring:
/* 6.Oct.2003 - Werner Lemberg reports a stupid Omega font that behaves
badly: a charstring definition follows "/Charstrings ... begin", ON THE
SAME LINE. */
{
const char *CharStrings = (const char *)
oog_memstr(line, line_len, "/CharStrings ", 13);
int crap, n;
char should_be_slash = 0;
if (CharStrings
&& sscanf(CharStrings + 12, " %d dict dup begin %c%n", &crap, &should_be_slash, &n) >= 2
&& should_be_slash == '/') {
int len = (CharStrings + 12 + n - 1) - (char *) line;
fprintf(ofp, "%.*s\n", len, line);
return eexec_line((unsigned char *) (CharStrings + 12 + n - 1), line_len - len);
}
}
if (line[line_len - 1] == '\r') {
line[line_len - 1] = '\n';
cut_newline = 1;
}
set_lenIV((char *)line);
set_cs_start((char *)line);
fprintf(ofp, "%.*s", line_len, line);
/* look for `currentfile closefile' to see if we should stop decrypting */
if (oog_memstr(line, line_len, "currentfile closefile", 21) != 0)
in_eexec = -1;
return cut_newline;
}
static int
all_zeroes(const char *string)
{
if (*string != '0')
return 0;
while (*string == '0')
string++;
return *string == '\0' || *string == '\n';
}
static void
disasm_output_ascii(char *line, int len)
{
int was_in_eexec = in_eexec;
(void) len; /* avoid warning */
in_eexec = 0;
/* if we came from a binary section, we need to process that too */
if (was_in_eexec > 0) {
unsigned char zero = 0;
eexec_line(&zero, 0);
}
/* if we just came from the "ASCII part" of an eexec section, we need to
process the saved lines */
if (was_in_eexec < 0) {
int i = 0;
int save_char = 0; /* note: save[] is unsigned char * */
while (i < save_len) {
/* grab a line */
int start = i;
while (i < save_len && save[i] != '\r' && save[i] != '\n')
i++;
if (i < save_len) {
if (i < save_len - 1 && save[i] == '\r' && save[i+1] == '\n')
save_char = -1;
else
save_char = save[i+1];
save[i] = '\n';
save[i+1] = 0;
} else
save[i] = 0;
/* output it */
disasm_output_ascii((char *)(save + start), -1);
/* repair damage */
if (i < save_len) {
if (save_char >= 0) {
save[i+1] = save_char;
i++;
} else
i += 2;
}
}
save_len = 0;
}
if (!all_zeroes(line))
output(line);
}
/* collect until '\n' or end of binary section */
static void
disasm_output_binary(unsigned char *data, int len)
{
static int ignore_newline;
static uint16_t er;
byte plain;
int i;
/* in the ASCII portion of a binary section, just save this data */
if (in_eexec < 0) {
append_save(data, len);
return;
}
/* eexec initialization */
if (in_eexec == 0) {
er = er_default;
ignore_newline = 0;
in_eexec = 0;
}
if (in_eexec < 4) {
for (i = 0; i < len && in_eexec < 4; i++, in_eexec++) {
byte cipher = data[i];
plain = (byte)(cipher ^ (er >> 8));
er = (uint16_t)((cipher + er) * c1 + c2);
data[i] = plain;
}
data += i;
len -= i;
}
/* now make lines: collect until '\n' or '\r' and pass them off to
eexec_line. */
i = 0;
while (in_eexec > 0) {
int start = i;
for (; i < len; i++) {
byte cipher = data[i];
plain = (byte)(cipher ^ (er >> 8));
er = (uint16_t)((cipher + er) * c1 + c2);
data[i] = plain;
if (plain == '\r' || plain == '\n')
break;
}
if (ignore_newline && start < i && data[start] == '\n') {
ignore_newline = 0;
continue;
}
if (i >= len) {
if (start < len)
append_save(data + start, i - start);
break;
}
i++;
ignore_newline = eexec_line(data + start, i - start);
}
/* if in_eexec < 0, we have some plaintext lines sitting around in a binary
section of the PFB. save them for later */
if (in_eexec < 0 && i < len)
append_save(data + i, len - i);
}
static void
disasm_output_end(void)
{
/* take care of leftover saved data */
static char crap[1] = "";
disasm_output_ascii(crap, 0);
}
/*****
* Command line
**/
#define OUTPUT_OPT 301
#define VERSION_OPT 302
#define HELP_OPT 303
static Clp_Option options[] = {
{ "help", 0, HELP_OPT, 0, 0 },
{ "output", 'o', OUTPUT_OPT, Clp_ValString, 0 },
{ "version", 0, VERSION_OPT, 0, 0 },
};
static const char *program_name;
void
fatal_error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
fputc('\n', stderr);
va_end(val);
exit(1);
}
void
error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
fputc('\n', stderr);
error_count++;
va_end(val);
}
static void
short_usage(void)
{
fprintf(stderr, "Usage: %s [INPUT [OUTPUT]]\n\
Try `%s --help' for more information.\n",
program_name, program_name);
}
static void
usage(void)
{
printf("\
`T1disasm' translates a PostScript Type 1 font in PFB or PFA format into a\n\
human-readable, human-editable form. The result is written to the standard\n\
output unless an OUTPUT file is given.\n\
\n\
Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\
\n\
Options:\n\
-o, --output=FILE Write output to FILE.\n\
-h, --help Print this message and exit.\n\
--version Print version number and warranty and exit.\n\
\n\
Report bugs to <ekohler@gmail.com>.\n", program_name);
}
#ifdef __cplusplus
}
#endif
int
main(int argc, char *argv[])
{
struct font_reader fr;
int c;
FILE *ifp = 0;
const char *ifp_filename = "<stdin>";
Clp_Parser *clp =
Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
program_name = Clp_ProgramName(clp);
/* interpret command line arguments using CLP */
while (1) {
int opt = Clp_Next(clp);
switch (opt) {
output_file:
case OUTPUT_OPT:
if (ofp)
fatal_error("output file already specified");
if (strcmp(clp->vstr, "-") == 0)
ofp = stdout;
else {
ofp = fopen(clp->vstr, "w");
if (!ofp) fatal_error("%s: %s", clp->vstr, strerror(errno));
}
break;
case HELP_OPT:
usage();
exit(0);
break;
case VERSION_OPT:
printf("t1disasm (LCDF t1utils) %s\n", VERSION);
printf("Copyright (C) 1992-2010 I. Lee Hetherington, Eddie Kohler et al.\n\
This is free software; see the source for copying conditions.\n\
There is NO warranty, not even for merchantability or fitness for a\n\
particular purpose.\n");
exit(0);
break;
case Clp_NotOption:
if (ifp && ofp)
fatal_error("too many arguments");
else if (ifp)
goto output_file;
if (strcmp(clp->vstr, "-") == 0)
ifp = stdin;
else {
ifp_filename = clp->vstr;
ifp = fopen(clp->vstr, "rb");
if (!ifp) fatal_error("%s: %s", clp->vstr, strerror(errno));
}
break;
case Clp_Done:
goto done;
case Clp_BadOption:
short_usage();
exit(1);
break;
}
}
done:
if (!ifp) ifp = stdin;
if (!ofp) ofp = stdout;
#if defined(_MSDOS) || defined(_WIN32)
/* As we might be processing a PFB (binary) input file, we must set its file
mode to binary. */
_setmode(_fileno(ifp), _O_BINARY);
#endif
/* prepare font reader */
fr.output_ascii = disasm_output_ascii;
fr.output_binary = disasm_output_binary;
fr.output_end = disasm_output_end;
/* peek at first byte to see if it is the PFB marker 0x80 */
c = getc(ifp);
ungetc(c, ifp);
/* do the file */
if (c == PFB_MARKER)
process_pfb(ifp, ifp_filename, &fr);
else if (c == '%')
process_pfa(ifp, ifp_filename, &fr);
else
fatal_error("%s does not start with font marker (`%%' or 0x80)", ifp_filename);
fclose(ifp);
fclose(ofp);
if (unknown)
error((unknown > 1
? "encountered %d unknown charstring commands"
: "encountered %d unknown charstring command"),
unknown);
return (error_count ? 1 : 0);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1611_3 |
crossvul-cpp_data_good_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, sizeof(obuf));
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/good_252_0 |
crossvul-cpp_data_good_5824_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) {
int chroma_planes, chroma_h_shift, chroma_v_shift, transparency, colorspace, bits_per_raw_sample;
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];
}
colorspace = get_symbol(c, state, 0); //YUV cs type
bits_per_raw_sample = f->version > 0 ? get_symbol(c, state, 0) : f->avctx->bits_per_raw_sample;
chroma_planes = get_rac(c, state);
chroma_h_shift = get_symbol(c, state, 0);
chroma_v_shift = get_symbol(c, state, 0);
transparency = get_rac(c, state);
if (f->plane_count) {
if ( colorspace != f->colorspace
|| bits_per_raw_sample != f->avctx->bits_per_raw_sample
|| chroma_planes != f->chroma_planes
|| chroma_h_shift!= f->chroma_h_shift
|| chroma_v_shift!= f->chroma_v_shift
|| transparency != f->transparency) {
av_log(f->avctx, AV_LOG_ERROR, "Invalid change of global parameters\n");
return AVERROR_INVALIDDATA;
}
}
f->colorspace = colorspace;
f->avctx->bits_per_raw_sample = bits_per_raw_sample;
f->chroma_planes = chroma_planes;
f->chroma_h_shift = chroma_h_shift;
f->chroma_v_shift = chroma_v_shift;
f->transparency = transparency;
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/good_5824_0 |
crossvul-cpp_data_good_4734_0 | /*
* helper functions for vmalloc video4linux capture buffers
*
* The functions expect the hardware being able to scatter gatter
* (i.e. the buffers are not linear in physical memory, but fragmented
* into PAGE_SIZE chunks). They also assume the driver does not need
* to touch the video data.
*
* (c) 2007 Mauro Carvalho Chehab, <mchehab@infradead.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <media/videobuf-vmalloc.h>
#define MAGIC_DMABUF 0x17760309
#define MAGIC_VMAL_MEM 0x18221223
#define MAGIC_CHECK(is,should) if (unlikely((is) != (should))) \
{ printk(KERN_ERR "magic mismatch: %x (expected %x)\n",is,should); BUG(); }
static int debug = 0;
module_param(debug, int, 0644);
MODULE_DESCRIPTION("helper module to manage video4linux vmalloc buffers");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@infradead.org>");
MODULE_LICENSE("GPL");
#define dprintk(level, fmt, arg...) if (debug >= level) \
printk(KERN_DEBUG "vbuf-sg: " fmt , ## arg)
/***************************************************************************/
static void
videobuf_vm_open(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
dprintk(2,"vm_open %p [count=%u,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count++;
}
static void
videobuf_vm_close(struct vm_area_struct *vma)
{
struct videobuf_mapping *map = vma->vm_private_data;
struct videobuf_queue *q = map->q;
int i;
dprintk(2,"vm_close %p [count=%u,vma=%08lx-%08lx]\n",map,
map->count,vma->vm_start,vma->vm_end);
map->count--;
if (0 == map->count) {
dprintk(1,"munmap %p q=%p\n",map,q);
mutex_lock(&q->lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == q->bufs[i])
continue;
if (q->bufs[i]->map != map)
continue;
q->ops->buf_release(q,q->bufs[i]);
q->bufs[i]->map = NULL;
q->bufs[i]->baddr = 0;
}
mutex_unlock(&q->lock);
kfree(map);
}
return;
}
static struct vm_operations_struct videobuf_vm_ops =
{
.open = videobuf_vm_open,
.close = videobuf_vm_close,
};
/* ---------------------------------------------------------------------
* vmalloc handlers for the generic methods
*/
/* Allocated area consists on 3 parts:
struct video_buffer
struct <driver>_buffer (cx88_buffer, saa7134_buf, ...)
struct videobuf_pci_sg_memory
*/
static void *__videobuf_alloc(size_t size)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_buffer *vb;
vb = kzalloc(size+sizeof(*mem),GFP_KERNEL);
mem = vb->priv = ((char *)vb)+size;
mem->magic=MAGIC_VMAL_MEM;
dprintk(1,"%s: allocated at %p(%ld+%ld) & %p(%ld)\n",
__FUNCTION__,vb,(long)sizeof(*vb),(long)size-sizeof(*vb),
mem,(long)sizeof(*mem));
return vb;
}
static int __videobuf_iolock (struct videobuf_queue* q,
struct videobuf_buffer *vb,
struct v4l2_framebuffer *fbuf)
{
int pages;
struct videbuf_vmalloc_memory *mem=vb->priv;
BUG_ON(!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
pages = PAGE_ALIGN(vb->size) >> PAGE_SHIFT;
/* Currently, doesn't support V4L2_MEMORY_OVERLAY */
if ((vb->memory != V4L2_MEMORY_MMAP) &&
(vb->memory != V4L2_MEMORY_USERPTR) ) {
printk(KERN_ERR "Method currently unsupported.\n");
return -EINVAL;
}
/* FIXME: should be tested with kernel mmap mem */
mem->vmalloc=vmalloc_user (PAGE_ALIGN(vb->size));
if (NULL == mem->vmalloc) {
printk(KERN_ERR "vmalloc (%d pages) failed\n",pages);
return -ENOMEM;
}
dprintk(1,"vmalloc is at addr 0x%08lx, size=%d\n",
(unsigned long)mem->vmalloc,
pages << PAGE_SHIFT);
/* It seems that some kernel versions need to do remap *after*
the mmap() call
*/
if (mem->vma) {
int retval=remap_vmalloc_range(mem->vma, mem->vmalloc,0);
kfree(mem->vma);
mem->vma=NULL;
if (retval<0) {
dprintk(1,"mmap app bug: remap_vmalloc_range area %p error %d\n",
mem->vmalloc,retval);
return retval;
}
}
return 0;
}
static int __videobuf_sync(struct videobuf_queue *q,
struct videobuf_buffer *buf)
{
return 0;
}
static int __videobuf_mmap_free(struct videobuf_queue *q)
{
unsigned int i;
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (q->bufs[i]) {
if (q->bufs[i]->map)
return -EBUSY;
}
}
return 0;
}
static int __videobuf_mmap_mapper(struct videobuf_queue *q,
struct vm_area_struct *vma)
{
struct videbuf_vmalloc_memory *mem;
struct videobuf_mapping *map;
unsigned int first;
int retval;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED))
return -EINVAL;
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == q->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != q->bufs[first]->memory)
continue;
if (q->bufs[first]->boff == offset)
break;
}
if (VIDEO_MAX_FRAME == first) {
dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n",
(vma->vm_pgoff << PAGE_SHIFT));
return -EINVAL;
}
/* create mapping + update buffer list */
map = q->bufs[first]->map = kzalloc(sizeof(struct videobuf_mapping),GFP_KERNEL);
if (NULL == map)
return -ENOMEM;
map->start = vma->vm_start;
map->end = vma->vm_end;
map->q = q;
q->bufs[first]->baddr = vma->vm_start;
vma->vm_ops = &videobuf_vm_ops;
vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED;
vma->vm_private_data = map;
mem=q->bufs[first]->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
/* Try to remap memory */
retval=remap_vmalloc_range(vma, mem->vmalloc,0);
if (retval<0) {
dprintk(1,"mmap: postponing remap_vmalloc_range\n");
mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL);
if (!mem->vma) {
kfree(map);
q->bufs[first]->map=NULL;
return -ENOMEM;
}
memcpy(mem->vma,vma,sizeof(*vma));
}
dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n",
map,q,vma->vm_start,vma->vm_end,
(long int) q->bufs[first]->bsize,
vma->vm_pgoff,first);
videobuf_vm_open(vma);
return (0);
}
static int __videobuf_copy_to_user ( struct videobuf_queue *q,
char __user *data, size_t count,
int nonblocking )
{
struct videbuf_vmalloc_memory *mem=q->read_buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
BUG_ON (!mem->vmalloc);
/* copy to userspace */
if (count > q->read_buf->size - q->read_off)
count = q->read_buf->size - q->read_off;
if (copy_to_user(data, mem->vmalloc+q->read_off, count))
return -EFAULT;
return count;
}
static int __videobuf_copy_stream ( struct videobuf_queue *q,
char __user *data, size_t count, size_t pos,
int vbihack, int nonblocking )
{
unsigned int *fc;
struct videbuf_vmalloc_memory *mem=q->read_buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
if (vbihack) {
/* dirty, undocumented hack -- pass the frame counter
* within the last four bytes of each vbi data block.
* We need that one to maintain backward compatibility
* to all vbi decoding software out there ... */
fc = (unsigned int*)mem->vmalloc;
fc += (q->read_buf->size>>2) -1;
*fc = q->read_buf->field_count >> 1;
dprintk(1,"vbihack: %d\n",*fc);
}
/* copy stuff using the common method */
count = __videobuf_copy_to_user (q,data,count,nonblocking);
if ( (count==-EFAULT) && (0 == pos) )
return -EFAULT;
return count;
}
static struct videobuf_qtype_ops qops = {
.magic = MAGIC_QTYPE_OPS,
.alloc = __videobuf_alloc,
.iolock = __videobuf_iolock,
.sync = __videobuf_sync,
.mmap_free = __videobuf_mmap_free,
.mmap_mapper = __videobuf_mmap_mapper,
.video_copy_to_user = __videobuf_copy_to_user,
.copy_stream = __videobuf_copy_stream,
};
void videobuf_queue_vmalloc_init(struct videobuf_queue* q,
struct videobuf_queue_ops *ops,
void *dev,
spinlock_t *irqlock,
enum v4l2_buf_type type,
enum v4l2_field field,
unsigned int msize,
void *priv)
{
videobuf_queue_core_init(q, ops, dev, irqlock, type, field, msize,
priv, &qops);
}
EXPORT_SYMBOL_GPL(videobuf_queue_vmalloc_init);
void *videobuf_to_vmalloc (struct videobuf_buffer *buf)
{
struct videbuf_vmalloc_memory *mem=buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
return mem->vmalloc;
}
EXPORT_SYMBOL_GPL(videobuf_to_vmalloc);
void videobuf_vmalloc_free (struct videobuf_buffer *buf)
{
struct videbuf_vmalloc_memory *mem=buf->priv;
BUG_ON (!mem);
MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM);
vfree(mem->vmalloc);
mem->vmalloc=NULL;
return;
}
EXPORT_SYMBOL_GPL(videobuf_vmalloc_free);
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4734_0 |
crossvul-cpp_data_good_3277_0 | /*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, 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.
*/
/* Toplevel file. Relies on dhd_linux.c to send commands to the dongle. */
#include <linux/kernel.h>
#include <linux/etherdevice.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <net/cfg80211.h>
#include <net/netlink.h>
#include <brcmu_utils.h>
#include <defs.h>
#include <brcmu_wifi.h>
#include "core.h"
#include "debug.h"
#include "tracepoint.h"
#include "fwil_types.h"
#include "p2p.h"
#include "btcoex.h"
#include "pno.h"
#include "cfg80211.h"
#include "feature.h"
#include "fwil.h"
#include "proto.h"
#include "vendor.h"
#include "bus.h"
#include "common.h"
#define BRCMF_SCAN_IE_LEN_MAX 2048
#define WPA_OUI "\x00\x50\xF2" /* WPA OUI */
#define WPA_OUI_TYPE 1
#define RSN_OUI "\x00\x0F\xAC" /* RSN OUI */
#define WME_OUI_TYPE 2
#define WPS_OUI_TYPE 4
#define VS_IE_FIXED_HDR_LEN 6
#define WPA_IE_VERSION_LEN 2
#define WPA_IE_MIN_OUI_LEN 4
#define WPA_IE_SUITE_COUNT_LEN 2
#define WPA_CIPHER_NONE 0 /* None */
#define WPA_CIPHER_WEP_40 1 /* WEP (40-bit) */
#define WPA_CIPHER_TKIP 2 /* TKIP: default for WPA */
#define WPA_CIPHER_AES_CCM 4 /* AES (CCM) */
#define WPA_CIPHER_WEP_104 5 /* WEP (104-bit) */
#define RSN_AKM_NONE 0 /* None (IBSS) */
#define RSN_AKM_UNSPECIFIED 1 /* Over 802.1x */
#define RSN_AKM_PSK 2 /* Pre-shared Key */
#define RSN_AKM_SHA256_1X 5 /* SHA256, 802.1X */
#define RSN_AKM_SHA256_PSK 6 /* SHA256, Pre-shared Key */
#define RSN_CAP_LEN 2 /* Length of RSN capabilities */
#define RSN_CAP_PTK_REPLAY_CNTR_MASK (BIT(2) | BIT(3))
#define RSN_CAP_MFPR_MASK BIT(6)
#define RSN_CAP_MFPC_MASK BIT(7)
#define RSN_PMKID_COUNT_LEN 2
#define VNDR_IE_CMD_LEN 4 /* length of the set command
* string :"add", "del" (+ NUL)
*/
#define VNDR_IE_COUNT_OFFSET 4
#define VNDR_IE_PKTFLAG_OFFSET 8
#define VNDR_IE_VSIE_OFFSET 12
#define VNDR_IE_HDR_SIZE 12
#define VNDR_IE_PARSE_LIMIT 5
#define DOT11_MGMT_HDR_LEN 24 /* d11 management header len */
#define DOT11_BCN_PRB_FIXED_LEN 12 /* beacon/probe fixed length */
#define BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS 320
#define BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS 400
#define BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS 20
#define BRCMF_SCAN_CHANNEL_TIME 40
#define BRCMF_SCAN_UNASSOC_TIME 40
#define BRCMF_SCAN_PASSIVE_TIME 120
#define BRCMF_ND_INFO_TIMEOUT msecs_to_jiffies(2000)
#define BRCMF_ASSOC_PARAMS_FIXED_SIZE \
(sizeof(struct brcmf_assoc_params_le) - sizeof(u16))
static bool check_vif_up(struct brcmf_cfg80211_vif *vif)
{
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state)) {
brcmf_dbg(INFO, "device is not ready : status (%lu)\n",
vif->sme_state);
return false;
}
return true;
}
#define RATE_TO_BASE100KBPS(rate) (((rate) * 10) / 2)
#define RATETAB_ENT(_rateid, _flags) \
{ \
.bitrate = RATE_TO_BASE100KBPS(_rateid), \
.hw_value = (_rateid), \
.flags = (_flags), \
}
static struct ieee80211_rate __wl_rates[] = {
RATETAB_ENT(BRCM_RATE_1M, 0),
RATETAB_ENT(BRCM_RATE_2M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_5M5, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_11M, IEEE80211_RATE_SHORT_PREAMBLE),
RATETAB_ENT(BRCM_RATE_6M, 0),
RATETAB_ENT(BRCM_RATE_9M, 0),
RATETAB_ENT(BRCM_RATE_12M, 0),
RATETAB_ENT(BRCM_RATE_18M, 0),
RATETAB_ENT(BRCM_RATE_24M, 0),
RATETAB_ENT(BRCM_RATE_36M, 0),
RATETAB_ENT(BRCM_RATE_48M, 0),
RATETAB_ENT(BRCM_RATE_54M, 0),
};
#define wl_g_rates (__wl_rates + 0)
#define wl_g_rates_size ARRAY_SIZE(__wl_rates)
#define wl_a_rates (__wl_rates + 4)
#define wl_a_rates_size (wl_g_rates_size - 4)
#define CHAN2G(_channel, _freq) { \
.band = NL80211_BAND_2GHZ, \
.center_freq = (_freq), \
.hw_value = (_channel), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
#define CHAN5G(_channel) { \
.band = NL80211_BAND_5GHZ, \
.center_freq = 5000 + (5 * (_channel)), \
.hw_value = (_channel), \
.max_antenna_gain = 0, \
.max_power = 30, \
}
static struct ieee80211_channel __wl_2ghz_channels[] = {
CHAN2G(1, 2412), CHAN2G(2, 2417), CHAN2G(3, 2422), CHAN2G(4, 2427),
CHAN2G(5, 2432), CHAN2G(6, 2437), CHAN2G(7, 2442), CHAN2G(8, 2447),
CHAN2G(9, 2452), CHAN2G(10, 2457), CHAN2G(11, 2462), CHAN2G(12, 2467),
CHAN2G(13, 2472), CHAN2G(14, 2484)
};
static struct ieee80211_channel __wl_5ghz_channels[] = {
CHAN5G(34), CHAN5G(36), CHAN5G(38), CHAN5G(40), CHAN5G(42),
CHAN5G(44), CHAN5G(46), CHAN5G(48), CHAN5G(52), CHAN5G(56),
CHAN5G(60), CHAN5G(64), CHAN5G(100), CHAN5G(104), CHAN5G(108),
CHAN5G(112), CHAN5G(116), CHAN5G(120), CHAN5G(124), CHAN5G(128),
CHAN5G(132), CHAN5G(136), CHAN5G(140), CHAN5G(144), CHAN5G(149),
CHAN5G(153), CHAN5G(157), CHAN5G(161), CHAN5G(165)
};
/* Band templates duplicated per wiphy. The channel info
* above is added to the band during setup.
*/
static const struct ieee80211_supported_band __wl_band_2ghz = {
.band = NL80211_BAND_2GHZ,
.bitrates = wl_g_rates,
.n_bitrates = wl_g_rates_size,
};
static const struct ieee80211_supported_band __wl_band_5ghz = {
.band = NL80211_BAND_5GHZ,
.bitrates = wl_a_rates,
.n_bitrates = wl_a_rates_size,
};
/* This is to override regulatory domains defined in cfg80211 module (reg.c)
* By default world regulatory domain defined in reg.c puts the flags
* NL80211_RRF_NO_IR for 5GHz channels (for * 36..48 and 149..165).
* With respect to these flags, wpa_supplicant doesn't * start p2p
* operations on 5GHz channels. All the changes in world regulatory
* domain are to be done here.
*/
static const struct ieee80211_regdomain brcmf_regdom = {
.n_reg_rules = 4,
.alpha2 = "99",
.reg_rules = {
/* IEEE 802.11b/g, channels 1..11 */
REG_RULE(2412-10, 2472+10, 40, 6, 20, 0),
/* If any */
/* IEEE 802.11 channel 14 - Only JP enables
* this and for 802.11b only
*/
REG_RULE(2484-10, 2484+10, 20, 6, 20, 0),
/* IEEE 802.11a, channel 36..64 */
REG_RULE(5150-10, 5350+10, 80, 6, 20, 0),
/* IEEE 802.11a, channel 100..165 */
REG_RULE(5470-10, 5850+10, 80, 6, 20, 0), }
};
/* Note: brcmf_cipher_suites is an array of int defining which cipher suites
* are supported. A pointer to this array and the number of entries is passed
* on to upper layers. AES_CMAC defines whether or not the driver supports MFP.
* So the cipher suite AES_CMAC has to be the last one in the array, and when
* device does not support MFP then the number of suites will be decreased by 1
*/
static const u32 brcmf_cipher_suites[] = {
WLAN_CIPHER_SUITE_WEP40,
WLAN_CIPHER_SUITE_WEP104,
WLAN_CIPHER_SUITE_TKIP,
WLAN_CIPHER_SUITE_CCMP,
/* Keep as last entry: */
WLAN_CIPHER_SUITE_AES_CMAC
};
/* Vendor specific ie. id = 221, oui and type defines exact ie */
struct brcmf_vs_tlv {
u8 id;
u8 len;
u8 oui[3];
u8 oui_type;
};
struct parsed_vndr_ie_info {
u8 *ie_ptr;
u32 ie_len; /* total length including id & length field */
struct brcmf_vs_tlv vndrie;
};
struct parsed_vndr_ies {
u32 count;
struct parsed_vndr_ie_info ie_info[VNDR_IE_PARSE_LIMIT];
};
static u8 nl80211_band_to_fwil(enum nl80211_band band)
{
switch (band) {
case NL80211_BAND_2GHZ:
return WLC_BAND_2G;
case NL80211_BAND_5GHZ:
return WLC_BAND_5G;
default:
WARN_ON(1);
break;
}
return 0;
}
static u16 chandef_to_chanspec(struct brcmu_d11inf *d11inf,
struct cfg80211_chan_def *ch)
{
struct brcmu_chan ch_inf;
s32 primary_offset;
brcmf_dbg(TRACE, "chandef: control %d center %d width %d\n",
ch->chan->center_freq, ch->center_freq1, ch->width);
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq1);
primary_offset = ch->chan->center_freq - ch->center_freq1;
switch (ch->width) {
case NL80211_CHAN_WIDTH_20:
case NL80211_CHAN_WIDTH_20_NOHT:
ch_inf.bw = BRCMU_CHAN_BW_20;
WARN_ON(primary_offset != 0);
break;
case NL80211_CHAN_WIDTH_40:
ch_inf.bw = BRCMU_CHAN_BW_40;
if (primary_offset > 0)
ch_inf.sb = BRCMU_CHAN_SB_U;
else
ch_inf.sb = BRCMU_CHAN_SB_L;
break;
case NL80211_CHAN_WIDTH_80:
ch_inf.bw = BRCMU_CHAN_BW_80;
if (primary_offset == -30)
ch_inf.sb = BRCMU_CHAN_SB_LL;
else if (primary_offset == -10)
ch_inf.sb = BRCMU_CHAN_SB_LU;
else if (primary_offset == 10)
ch_inf.sb = BRCMU_CHAN_SB_UL;
else
ch_inf.sb = BRCMU_CHAN_SB_UU;
break;
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
default:
WARN_ON_ONCE(1);
}
switch (ch->chan->band) {
case NL80211_BAND_2GHZ:
ch_inf.band = BRCMU_CHAN_BAND_2G;
break;
case NL80211_BAND_5GHZ:
ch_inf.band = BRCMU_CHAN_BAND_5G;
break;
case NL80211_BAND_60GHZ:
default:
WARN_ON_ONCE(1);
}
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
u16 channel_to_chanspec(struct brcmu_d11inf *d11inf,
struct ieee80211_channel *ch)
{
struct brcmu_chan ch_inf;
ch_inf.chnum = ieee80211_frequency_to_channel(ch->center_freq);
ch_inf.bw = BRCMU_CHAN_BW_20;
d11inf->encchspec(&ch_inf);
return ch_inf.chspec;
}
/* Traverse a string of 1-byte tag/1-byte length/variable-length value
* triples, returning a pointer to the substring whose first element
* matches tag
*/
static const struct brcmf_tlv *
brcmf_parse_tlvs(const void *buf, int buflen, uint key)
{
const struct brcmf_tlv *elt = buf;
int totlen = buflen;
/* find tagged parameter */
while (totlen >= TLV_HDR_LEN) {
int len = elt->len;
/* validate remaining totlen */
if ((elt->id == key) && (totlen >= (len + TLV_HDR_LEN)))
return elt;
elt = (struct brcmf_tlv *)((u8 *)elt + (len + TLV_HDR_LEN));
totlen -= (len + TLV_HDR_LEN);
}
return NULL;
}
/* Is any of the tlvs the expected entry? If
* not update the tlvs buffer pointer/length.
*/
static bool
brcmf_tlv_has_ie(const u8 *ie, const u8 **tlvs, u32 *tlvs_len,
const u8 *oui, u32 oui_len, u8 type)
{
/* If the contents match the OUI and the type */
if (ie[TLV_LEN_OFF] >= oui_len + 1 &&
!memcmp(&ie[TLV_BODY_OFF], oui, oui_len) &&
type == ie[TLV_BODY_OFF + oui_len]) {
return true;
}
if (tlvs == NULL)
return false;
/* point to the next ie */
ie += ie[TLV_LEN_OFF] + TLV_HDR_LEN;
/* calculate the length of the rest of the buffer */
*tlvs_len -= (int)(ie - *tlvs);
/* update the pointer to the start of the buffer */
*tlvs = ie;
return false;
}
static struct brcmf_vs_tlv *
brcmf_find_wpaie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((const u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPA_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static struct brcmf_vs_tlv *
brcmf_find_wpsie(const u8 *parse, u32 len)
{
const struct brcmf_tlv *ie;
while ((ie = brcmf_parse_tlvs(parse, len, WLAN_EID_VENDOR_SPECIFIC))) {
if (brcmf_tlv_has_ie((u8 *)ie, &parse, &len,
WPA_OUI, TLV_OUI_LEN, WPS_OUI_TYPE))
return (struct brcmf_vs_tlv *)ie;
}
return NULL;
}
static int brcmf_vif_change_validate(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif,
enum nl80211_iftype new_type)
{
struct brcmf_cfg80211_vif *pos;
bool check_combos = false;
int ret = 0;
struct iface_combination_params params = {
.num_different_channels = 1,
};
list_for_each_entry(pos, &cfg->vif_list, list)
if (pos == vif) {
params.iftype_num[new_type]++;
} else {
/* concurrent interfaces so need check combinations */
check_combos = true;
params.iftype_num[pos->wdev.iftype]++;
}
if (check_combos)
ret = cfg80211_check_combinations(cfg->wiphy, ¶ms);
return ret;
}
static int brcmf_vif_add_validate(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype new_type)
{
struct brcmf_cfg80211_vif *pos;
struct iface_combination_params params = {
.num_different_channels = 1,
};
list_for_each_entry(pos, &cfg->vif_list, list)
params.iftype_num[pos->wdev.iftype]++;
params.iftype_num[new_type]++;
return cfg80211_check_combinations(cfg->wiphy, ¶ms);
}
static void convert_key_from_CPU(struct brcmf_wsec_key *key,
struct brcmf_wsec_key_le *key_le)
{
key_le->index = cpu_to_le32(key->index);
key_le->len = cpu_to_le32(key->len);
key_le->algo = cpu_to_le32(key->algo);
key_le->flags = cpu_to_le32(key->flags);
key_le->rxiv.hi = cpu_to_le32(key->rxiv.hi);
key_le->rxiv.lo = cpu_to_le16(key->rxiv.lo);
key_le->iv_initialized = cpu_to_le32(key->iv_initialized);
memcpy(key_le->data, key->data, sizeof(key->data));
memcpy(key_le->ea, key->ea, sizeof(key->ea));
}
static int
send_key_to_dongle(struct brcmf_if *ifp, struct brcmf_wsec_key *key)
{
int err;
struct brcmf_wsec_key_le key_le;
convert_key_from_CPU(key, &key_le);
brcmf_netdev_wait_pend8021x(ifp);
err = brcmf_fil_bsscfg_data_set(ifp, "wsec_key", &key_le,
sizeof(key_le));
if (err)
brcmf_err("wsec_key error (%d)\n", err);
return err;
}
static s32
brcmf_configure_arp_nd_offload(struct brcmf_if *ifp, bool enable)
{
s32 err;
u32 mode;
if (enable)
mode = BRCMF_ARP_OL_AGENT | BRCMF_ARP_OL_PEER_AUTO_REPLY;
else
mode = 0;
/* Try to set and enable ARP offload feature, this may fail, then it */
/* is simply not supported and err 0 will be returned */
err = brcmf_fil_iovar_int_set(ifp, "arp_ol", mode);
if (err) {
brcmf_dbg(TRACE, "failed to set ARP offload mode to 0x%x, err = %d\n",
mode, err);
err = 0;
} else {
err = brcmf_fil_iovar_int_set(ifp, "arpoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ARP offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ARP offload to 0x%x\n",
enable, mode);
}
err = brcmf_fil_iovar_int_set(ifp, "ndoe", enable);
if (err) {
brcmf_dbg(TRACE, "failed to configure (%d) ND offload err = %d\n",
enable, err);
err = 0;
} else
brcmf_dbg(TRACE, "successfully configured (%d) ND offload to 0x%x\n",
enable, mode);
return err;
}
static void
brcmf_cfg80211_update_proto_addr_mode(struct wireless_dev *wdev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
ifp = vif->ifp;
if ((wdev->iftype == NL80211_IFTYPE_ADHOC) ||
(wdev->iftype == NL80211_IFTYPE_AP) ||
(wdev->iftype == NL80211_IFTYPE_P2P_GO))
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_DIRECT);
else
brcmf_proto_configure_addr_mode(ifp->drvr, ifp->ifidx,
ADDR_INDIRECT);
}
static int brcmf_get_first_free_bsscfgidx(struct brcmf_pub *drvr)
{
int bsscfgidx;
for (bsscfgidx = 0; bsscfgidx < BRCMF_MAX_IFS; bsscfgidx++) {
/* bsscfgidx 1 is reserved for legacy P2P */
if (bsscfgidx == 1)
continue;
if (!drvr->iflist[bsscfgidx])
return bsscfgidx;
}
return -ENOMEM;
}
static int brcmf_cfg80211_request_ap_if(struct brcmf_if *ifp)
{
struct brcmf_mbss_ssid_le mbss_ssid_le;
int bsscfgidx;
int err;
memset(&mbss_ssid_le, 0, sizeof(mbss_ssid_le));
bsscfgidx = brcmf_get_first_free_bsscfgidx(ifp->drvr);
if (bsscfgidx < 0)
return bsscfgidx;
mbss_ssid_le.bsscfgidx = cpu_to_le32(bsscfgidx);
mbss_ssid_le.SSID_len = cpu_to_le32(5);
sprintf(mbss_ssid_le.SSID, "ssid%d" , bsscfgidx);
err = brcmf_fil_bsscfg_data_set(ifp, "bsscfg:ssid", &mbss_ssid_le,
sizeof(mbss_ssid_le));
if (err < 0)
brcmf_err("setting ssid failed %d\n", err);
return err;
}
/**
* brcmf_ap_add_vif() - create a new AP virtual interface for multiple BSS
*
* @wiphy: wiphy device of new interface.
* @name: name of the new interface.
* @params: contains mac address for AP device.
*/
static
struct wireless_dev *brcmf_ap_add_vif(struct wiphy *wiphy, const char *name,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_cfg80211_vif *vif;
int err;
if (brcmf_cfg80211_vif_event_armed(cfg))
return ERR_PTR(-EBUSY);
brcmf_dbg(INFO, "Adding vif \"%s\"\n", name);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_AP);
if (IS_ERR(vif))
return (struct wireless_dev *)vif;
brcmf_cfg80211_arm_vif_event(cfg, vif);
err = brcmf_cfg80211_request_ap_if(ifp);
if (err) {
brcmf_cfg80211_arm_vif_event(cfg, NULL);
goto fail;
}
/* wait for firmware event */
err = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_ADD,
BRCMF_VIF_EVENT_TIMEOUT);
brcmf_cfg80211_arm_vif_event(cfg, NULL);
if (!err) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto fail;
}
/* interface created in firmware */
ifp = vif->ifp;
if (!ifp) {
brcmf_err("no if pointer provided\n");
err = -ENOENT;
goto fail;
}
strncpy(ifp->ndev->name, name, sizeof(ifp->ndev->name) - 1);
err = brcmf_net_attach(ifp, true);
if (err) {
brcmf_err("Registering netdevice failed\n");
free_netdev(ifp->ndev);
goto fail;
}
return &ifp->vif->wdev;
fail:
brcmf_free_vif(vif);
return ERR_PTR(err);
}
static bool brcmf_is_apmode(struct brcmf_cfg80211_vif *vif)
{
enum nl80211_iftype iftype;
iftype = vif->wdev.iftype;
return iftype == NL80211_IFTYPE_AP || iftype == NL80211_IFTYPE_P2P_GO;
}
static bool brcmf_is_ibssmode(struct brcmf_cfg80211_vif *vif)
{
return vif->wdev.iftype == NL80211_IFTYPE_ADHOC;
}
static struct wireless_dev *brcmf_cfg80211_add_iface(struct wiphy *wiphy,
const char *name,
unsigned char name_assign_type,
enum nl80211_iftype type,
struct vif_params *params)
{
struct wireless_dev *wdev;
int err;
brcmf_dbg(TRACE, "enter: %s type %d\n", name, type);
err = brcmf_vif_add_validate(wiphy_to_cfg(wiphy), type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return ERR_PTR(err);
}
switch (type) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return ERR_PTR(-EOPNOTSUPP);
case NL80211_IFTYPE_AP:
wdev = brcmf_ap_add_vif(wiphy, name, params);
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
wdev = brcmf_p2p_add_vif(wiphy, name, name_assign_type, type, params);
break;
case NL80211_IFTYPE_UNSPECIFIED:
default:
return ERR_PTR(-EINVAL);
}
if (IS_ERR(wdev))
brcmf_err("add iface %s type %d failed: err=%d\n",
name, type, (int)PTR_ERR(wdev));
else
brcmf_cfg80211_update_proto_addr_mode(wdev);
return wdev;
}
static void brcmf_scan_config_mpc(struct brcmf_if *ifp, int mpc)
{
if (brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_NEED_MPC))
brcmf_set_mpc(ifp, mpc);
}
void brcmf_set_mpc(struct brcmf_if *ifp, int mpc)
{
s32 err = 0;
if (check_vif_up(ifp->vif)) {
err = brcmf_fil_iovar_int_set(ifp, "mpc", mpc);
if (err) {
brcmf_err("fail to set mpc\n");
return;
}
brcmf_dbg(INFO, "MPC : %d\n", mpc);
}
}
s32 brcmf_notify_escan_complete(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp, bool aborted,
bool fw_abort)
{
struct brcmf_scan_params_le params_le;
struct cfg80211_scan_request *scan_request;
u64 reqid;
u32 bucket;
s32 err = 0;
brcmf_dbg(SCAN, "Enter\n");
/* clear scan request, because the FW abort can cause a second call */
/* to this functon and might cause a double cfg80211_scan_done */
scan_request = cfg->scan_request;
cfg->scan_request = NULL;
if (timer_pending(&cfg->escan_timeout))
del_timer_sync(&cfg->escan_timeout);
if (fw_abort) {
/* Do a scan abort to stop the driver's scan engine */
brcmf_dbg(SCAN, "ABORT scan in firmware\n");
memset(¶ms_le, 0, sizeof(params_le));
eth_broadcast_addr(params_le.bssid);
params_le.bss_type = DOT11_BSSTYPE_ANY;
params_le.scan_type = 0;
params_le.channel_num = cpu_to_le32(1);
params_le.nprobes = cpu_to_le32(1);
params_le.active_time = cpu_to_le32(-1);
params_le.passive_time = cpu_to_le32(-1);
params_le.home_time = cpu_to_le32(-1);
/* Scan is aborted by setting channel_list[0] to -1 */
params_le.channel_list[0] = cpu_to_le16(-1);
/* E-Scan (or anyother type) can be aborted by SCAN */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN,
¶ms_le, sizeof(params_le));
if (err)
brcmf_err("Scan abort failed\n");
}
brcmf_scan_config_mpc(ifp, 1);
/*
* e-scan can be initiated internally
* which takes precedence.
*/
if (cfg->int_escan_map) {
brcmf_dbg(SCAN, "scheduled scan completed (%x)\n",
cfg->int_escan_map);
while (cfg->int_escan_map) {
bucket = __ffs(cfg->int_escan_map);
cfg->int_escan_map &= ~BIT(bucket);
reqid = brcmf_pno_find_reqid_by_bucket(cfg->pno,
bucket);
if (!aborted) {
brcmf_dbg(SCAN, "report results: reqid=%llu\n",
reqid);
cfg80211_sched_scan_results(cfg_to_wiphy(cfg),
reqid);
}
}
} else if (scan_request) {
struct cfg80211_scan_info info = {
.aborted = aborted,
};
brcmf_dbg(SCAN, "ESCAN Completed scan: %s\n",
aborted ? "Aborted" : "Done");
cfg80211_scan_done(scan_request, &info);
}
if (!test_and_clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_dbg(SCAN, "Scan complete, probably P2P scan\n");
return err;
}
static int brcmf_cfg80211_del_ap_iface(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp = netdev_priv(ndev);
int ret;
int err;
brcmf_cfg80211_arm_vif_event(cfg, ifp->vif);
err = brcmf_fil_bsscfg_data_set(ifp, "interface_remove", NULL, 0);
if (err) {
brcmf_err("interface_remove failed %d\n", err);
goto err_unarm;
}
/* wait for firmware event */
ret = brcmf_cfg80211_wait_vif_event(cfg, BRCMF_E_IF_DEL,
BRCMF_VIF_EVENT_TIMEOUT);
if (!ret) {
brcmf_err("timeout occurred\n");
err = -EIO;
goto err_unarm;
}
brcmf_remove_interface(ifp, true);
err_unarm:
brcmf_cfg80211_arm_vif_event(cfg, NULL);
return err;
}
static
int brcmf_cfg80211_del_iface(struct wiphy *wiphy, struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct net_device *ndev = wdev->netdev;
if (ndev && ndev == cfg_to_ndev(cfg))
return -ENOTSUPP;
/* vif event pending in firmware */
if (brcmf_cfg80211_vif_event_armed(cfg))
return -EBUSY;
if (ndev) {
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status) &&
cfg->escan_info.ifp == netdev_priv(ndev))
brcmf_notify_escan_complete(cfg, netdev_priv(ndev),
true, true);
brcmf_fil_iovar_int_set(netdev_priv(ndev), "mpc", 1);
}
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_WDS:
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_MESH_POINT:
return -EOPNOTSUPP;
case NL80211_IFTYPE_AP:
return brcmf_cfg80211_del_ap_iface(wiphy, wdev);
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
return brcmf_p2p_del_vif(wiphy, wdev);
case NL80211_IFTYPE_UNSPECIFIED:
default:
return -EINVAL;
}
return -EOPNOTSUPP;
}
static s32
brcmf_cfg80211_change_iface(struct wiphy *wiphy, struct net_device *ndev,
enum nl80211_iftype type,
struct vif_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif = ifp->vif;
s32 infra = 0;
s32 ap = 0;
s32 err = 0;
brcmf_dbg(TRACE, "Enter, bsscfgidx=%d, type=%d\n", ifp->bsscfgidx,
type);
/* WAR: There are a number of p2p interface related problems which
* need to be handled initially (before doing the validate).
* wpa_supplicant tends to do iface changes on p2p device/client/go
* which are not always possible/allowed. However we need to return
* OK otherwise the wpa_supplicant wont start. The situation differs
* on configuration and setup (p2pon=1 module param). The first check
* is to see if the request is a change to station for p2p iface.
*/
if ((type == NL80211_IFTYPE_STATION) &&
((vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_GO) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_DEVICE))) {
brcmf_dbg(TRACE, "Ignoring cmd for p2p if\n");
/* Now depending on whether module param p2pon=1 was used the
* response needs to be either 0 or EOPNOTSUPP. The reason is
* that if p2pon=1 is used, but a newer supplicant is used then
* we should return an error, as this combination wont work.
* In other situations 0 is returned and supplicant will start
* normally. It will give a trace in cfg80211, but it is the
* only way to get it working. Unfortunately this will result
* in situation where we wont support new supplicant in
* combination with module param p2pon=1, but that is the way
* it is. If the user tries this then unloading of driver might
* fail/lock.
*/
if (cfg->p2p.p2pdev_dynamically)
return -EOPNOTSUPP;
else
return 0;
}
err = brcmf_vif_change_validate(wiphy_to_cfg(wiphy), vif, type);
if (err) {
brcmf_err("iface validation failed: err=%d\n", err);
return err;
}
switch (type) {
case NL80211_IFTYPE_MONITOR:
case NL80211_IFTYPE_WDS:
brcmf_err("type (%d) : currently we do not support this type\n",
type);
return -EOPNOTSUPP;
case NL80211_IFTYPE_ADHOC:
infra = 0;
break;
case NL80211_IFTYPE_STATION:
infra = 1;
break;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
ap = 1;
break;
default:
err = -EINVAL;
goto done;
}
if (ap) {
if (type == NL80211_IFTYPE_P2P_GO) {
brcmf_dbg(INFO, "IF Type = P2P GO\n");
err = brcmf_p2p_ifchange(cfg, BRCMF_FIL_P2P_IF_GO);
}
if (!err) {
brcmf_dbg(INFO, "IF Type = AP\n");
}
} else {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, infra);
if (err) {
brcmf_err("WLC_SET_INFRA error (%d)\n", err);
err = -EAGAIN;
goto done;
}
brcmf_dbg(INFO, "IF Type = %s\n", brcmf_is_ibssmode(vif) ?
"Adhoc" : "Infra");
}
ndev->ieee80211_ptr->iftype = type;
brcmf_cfg80211_update_proto_addr_mode(&vif->wdev);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_escan_prep(struct brcmf_cfg80211_info *cfg,
struct brcmf_scan_params_le *params_le,
struct cfg80211_scan_request *request)
{
u32 n_ssids;
u32 n_channels;
s32 i;
s32 offset;
u16 chanspec;
char *ptr;
struct brcmf_ssid_le ssid_le;
eth_broadcast_addr(params_le->bssid);
params_le->bss_type = DOT11_BSSTYPE_ANY;
params_le->scan_type = 0;
params_le->channel_num = 0;
params_le->nprobes = cpu_to_le32(-1);
params_le->active_time = cpu_to_le32(-1);
params_le->passive_time = cpu_to_le32(-1);
params_le->home_time = cpu_to_le32(-1);
memset(¶ms_le->ssid_le, 0, sizeof(params_le->ssid_le));
/* if request is null exit so it will be all channel broadcast scan */
if (!request)
return;
n_ssids = request->n_ssids;
n_channels = request->n_channels;
/* Copy channel array if applicable */
brcmf_dbg(SCAN, "### List of channelspecs to scan ### %d\n",
n_channels);
if (n_channels > 0) {
for (i = 0; i < n_channels; i++) {
chanspec = channel_to_chanspec(&cfg->d11inf,
request->channels[i]);
brcmf_dbg(SCAN, "Chan : %d, Channel spec: %x\n",
request->channels[i]->hw_value, chanspec);
params_le->channel_list[i] = cpu_to_le16(chanspec);
}
} else {
brcmf_dbg(SCAN, "Scanning all channels\n");
}
/* Copy ssid array if applicable */
brcmf_dbg(SCAN, "### List of SSIDs to scan ### %d\n", n_ssids);
if (n_ssids > 0) {
offset = offsetof(struct brcmf_scan_params_le, channel_list) +
n_channels * sizeof(u16);
offset = roundup(offset, sizeof(u32));
ptr = (char *)params_le + offset;
for (i = 0; i < n_ssids; i++) {
memset(&ssid_le, 0, sizeof(ssid_le));
ssid_le.SSID_len =
cpu_to_le32(request->ssids[i].ssid_len);
memcpy(ssid_le.SSID, request->ssids[i].ssid,
request->ssids[i].ssid_len);
if (!ssid_le.SSID_len)
brcmf_dbg(SCAN, "%d: Broadcast scan\n", i);
else
brcmf_dbg(SCAN, "%d: scan for %.32s size=%d\n",
i, ssid_le.SSID, ssid_le.SSID_len);
memcpy(ptr, &ssid_le, sizeof(ssid_le));
ptr += sizeof(ssid_le);
}
} else {
brcmf_dbg(SCAN, "Broadcast scan %p\n", request->ssids);
if ((request->ssids) && request->ssids->ssid_len) {
brcmf_dbg(SCAN, "SSID %s len=%d\n",
params_le->ssid_le.SSID,
request->ssids->ssid_len);
params_le->ssid_le.SSID_len =
cpu_to_le32(request->ssids->ssid_len);
memcpy(¶ms_le->ssid_le.SSID, request->ssids->ssid,
request->ssids->ssid_len);
}
}
/* Adding mask to channel numbers */
params_le->channel_num =
cpu_to_le32((n_ssids << BRCMF_SCAN_PARAMS_NSSID_SHIFT) |
(n_channels & BRCMF_SCAN_PARAMS_COUNT_MASK));
}
static s32
brcmf_run_escan(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp,
struct cfg80211_scan_request *request)
{
s32 params_size = BRCMF_SCAN_PARAMS_FIXED_SIZE +
offsetof(struct brcmf_escan_params_le, params_le);
struct brcmf_escan_params_le *params;
s32 err = 0;
brcmf_dbg(SCAN, "E-SCAN START\n");
if (request != NULL) {
/* Allocate space for populating ssids in struct */
params_size += sizeof(u32) * ((request->n_channels + 1) / 2);
/* Allocate space for populating ssids in struct */
params_size += sizeof(struct brcmf_ssid_le) * request->n_ssids;
}
params = kzalloc(params_size, GFP_KERNEL);
if (!params) {
err = -ENOMEM;
goto exit;
}
BUG_ON(params_size + sizeof("escan") >= BRCMF_DCMD_MEDLEN);
brcmf_escan_prep(cfg, ¶ms->params_le, request);
params->version = cpu_to_le32(BRCMF_ESCAN_REQ_VERSION);
params->action = cpu_to_le16(WL_ESCAN_ACTION_START);
params->sync_id = cpu_to_le16(0x1234);
err = brcmf_fil_iovar_data_set(ifp, "escan", params, params_size);
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "system busy : escan canceled\n");
else
brcmf_err("error (%d)\n", err);
}
kfree(params);
exit:
return err;
}
static s32
brcmf_do_escan(struct brcmf_if *ifp, struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err;
u32 passive_scan;
struct brcmf_scan_results *results;
struct escan_info *escan = &cfg->escan_info;
brcmf_dbg(SCAN, "Enter\n");
escan->ifp = ifp;
escan->wiphy = cfg->wiphy;
escan->escan_state = WL_ESCAN_STATE_SCANNING;
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
brcmf_scan_config_mpc(ifp, 0);
results = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
results->version = 0;
results->count = 0;
results->buflen = WL_ESCAN_RESULTS_FIXED_SIZE;
err = escan->run(cfg, ifp, request);
if (err)
brcmf_scan_config_mpc(ifp, 1);
return err;
}
static s32
brcmf_cfg80211_escan(struct wiphy *wiphy, struct brcmf_cfg80211_vif *vif,
struct cfg80211_scan_request *request,
struct cfg80211_ssid *this_ssid)
{
struct brcmf_if *ifp = vif->ifp;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct cfg80211_ssid *ssids;
u32 passive_scan;
bool escan_req;
bool spec_scan;
s32 err;
struct brcmf_ssid_le ssid_le;
u32 SSID_len;
brcmf_dbg(SCAN, "START ESCAN\n");
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("Scanning already: status (%lu)\n", cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status)) {
brcmf_err("Scanning being aborted: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status (%lu)\n",
cfg->scan_status);
return -EAGAIN;
}
if (test_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state)) {
brcmf_err("Connecting: status (%lu)\n", ifp->vif->sme_state);
return -EAGAIN;
}
/* If scan req comes for p2p0, send it over primary I/F */
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif;
escan_req = false;
if (request) {
/* scan bss */
ssids = request->ssids;
escan_req = true;
} else {
/* scan in ibss */
/* we don't do escan in ibss */
ssids = this_ssid;
}
cfg->scan_request = request;
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
if (escan_req) {
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_p2p_scan_prep(wiphy, request, vif);
if (err)
goto scan_out;
err = brcmf_do_escan(vif->ifp, request);
if (err)
goto scan_out;
} else {
brcmf_dbg(SCAN, "ssid \"%s\", ssid_len (%d)\n",
ssids->ssid, ssids->ssid_len);
memset(&ssid_le, 0, sizeof(ssid_le));
SSID_len = min_t(u8, sizeof(ssid_le.SSID), ssids->ssid_len);
ssid_le.SSID_len = cpu_to_le32(0);
spec_scan = false;
if (SSID_len) {
memcpy(ssid_le.SSID, ssids->ssid, SSID_len);
ssid_le.SSID_len = cpu_to_le32(SSID_len);
spec_scan = true;
} else
brcmf_dbg(SCAN, "Broadcast scan\n");
passive_scan = cfg->active_scan ? 0 : 1;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PASSIVE_SCAN,
passive_scan);
if (err) {
brcmf_err("WLC_SET_PASSIVE_SCAN error (%d)\n", err);
goto scan_out;
}
brcmf_scan_config_mpc(ifp, 0);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCAN, &ssid_le,
sizeof(ssid_le));
if (err) {
if (err == -EBUSY)
brcmf_dbg(INFO, "BUSY: scan for \"%s\" canceled\n",
ssid_le.SSID);
else
brcmf_err("WLC_SCAN error (%d)\n", err);
brcmf_scan_config_mpc(ifp, 1);
goto scan_out;
}
}
/* Arm scan timeout timer */
mod_timer(&cfg->escan_timeout, jiffies +
BRCMF_ESCAN_TIMER_INTERVAL_MS * HZ / 1000);
return 0;
scan_out:
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->scan_request = NULL;
return err;
}
static s32
brcmf_cfg80211_scan(struct wiphy *wiphy, struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
vif = container_of(request->wdev, struct brcmf_cfg80211_vif, wdev);
if (!check_vif_up(vif))
return -EIO;
err = brcmf_cfg80211_escan(wiphy, vif, request, NULL);
if (err)
brcmf_err("scan error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_set_rts(struct net_device *ndev, u32 rts_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "rtsthresh",
rts_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_frag(struct net_device *ndev, u32 frag_threshold)
{
s32 err = 0;
err = brcmf_fil_iovar_int_set(netdev_priv(ndev), "fragthresh",
frag_threshold);
if (err)
brcmf_err("Error (%d)\n", err);
return err;
}
static s32 brcmf_set_retry(struct net_device *ndev, u32 retry, bool l)
{
s32 err = 0;
u32 cmd = (l ? BRCMF_C_SET_LRL : BRCMF_C_SET_SRL);
err = brcmf_fil_cmd_int_set(netdev_priv(ndev), cmd, retry);
if (err) {
brcmf_err("cmd (%d) , error (%d)\n", cmd, err);
return err;
}
return err;
}
static s32 brcmf_cfg80211_set_wiphy_params(struct wiphy *wiphy, u32 changed)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (changed & WIPHY_PARAM_RTS_THRESHOLD &&
(cfg->conf->rts_threshold != wiphy->rts_threshold)) {
cfg->conf->rts_threshold = wiphy->rts_threshold;
err = brcmf_set_rts(ndev, cfg->conf->rts_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_FRAG_THRESHOLD &&
(cfg->conf->frag_threshold != wiphy->frag_threshold)) {
cfg->conf->frag_threshold = wiphy->frag_threshold;
err = brcmf_set_frag(ndev, cfg->conf->frag_threshold);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_LONG
&& (cfg->conf->retry_long != wiphy->retry_long)) {
cfg->conf->retry_long = wiphy->retry_long;
err = brcmf_set_retry(ndev, cfg->conf->retry_long, true);
if (!err)
goto done;
}
if (changed & WIPHY_PARAM_RETRY_SHORT
&& (cfg->conf->retry_short != wiphy->retry_short)) {
cfg->conf->retry_short = wiphy->retry_short;
err = brcmf_set_retry(ndev, cfg->conf->retry_short, false);
if (!err)
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static void brcmf_init_prof(struct brcmf_cfg80211_profile *prof)
{
memset(prof, 0, sizeof(*prof));
}
static u16 brcmf_map_fw_linkdown_reason(const struct brcmf_event_msg *e)
{
u16 reason;
switch (e->event_code) {
case BRCMF_E_DEAUTH:
case BRCMF_E_DEAUTH_IND:
case BRCMF_E_DISASSOC_IND:
reason = e->reason;
break;
case BRCMF_E_LINK:
default:
reason = 0;
break;
}
return reason;
}
static int brcmf_set_pmk(struct brcmf_if *ifp, const u8 *pmk_data, u16 pmk_len)
{
struct brcmf_wsec_pmk_le pmk;
int i, err;
/* convert to firmware key format */
pmk.key_len = cpu_to_le16(pmk_len << 1);
pmk.flags = cpu_to_le16(BRCMF_WSEC_PASSPHRASE);
for (i = 0; i < pmk_len; i++)
snprintf(&pmk.key[2 * i], 3, "%02x", pmk_data[i]);
/* store psk in firmware */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_WSEC_PMK,
&pmk, sizeof(pmk));
if (err < 0)
brcmf_err("failed to change PSK in firmware (len=%u)\n",
pmk_len);
return err;
}
static void brcmf_link_down(struct brcmf_cfg80211_vif *vif, u16 reason)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(vif->wdev.wiphy);
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTED, &vif->sme_state)) {
brcmf_dbg(INFO, "Call WLC_DISASSOC to stop excess roaming\n ");
err = brcmf_fil_cmd_data_set(vif->ifp,
BRCMF_C_DISASSOC, NULL, 0);
if (err) {
brcmf_err("WLC_DISASSOC failed (%d)\n", err);
}
if ((vif->wdev.iftype == NL80211_IFTYPE_STATION) ||
(vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT))
cfg80211_disconnected(vif->wdev.netdev, reason, NULL, 0,
true, GFP_KERNEL);
}
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &vif->sme_state);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
if (vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_NONE) {
brcmf_set_pmk(vif->ifp, NULL, 0);
vif->profile.use_fwsup = BRCMF_PROFILE_FWSUP_NONE;
}
brcmf_dbg(TRACE, "Exit\n");
}
static s32
brcmf_cfg80211_join_ibss(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ibss_params *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_join_params join_params;
size_t join_params_size = 0;
s32 err = 0;
s32 wsec = 0;
s32 bcnprd;
u16 chanspec;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (params->ssid)
brcmf_dbg(CONN, "SSID: %s\n", params->ssid);
else {
brcmf_dbg(CONN, "SSID: NULL, Not supported\n");
return -EOPNOTSUPP;
}
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (params->bssid)
brcmf_dbg(CONN, "BSSID: %pM\n", params->bssid);
else
brcmf_dbg(CONN, "No BSSID specified\n");
if (params->chandef.chan)
brcmf_dbg(CONN, "channel: %d\n",
params->chandef.chan->center_freq);
else
brcmf_dbg(CONN, "no channel specified\n");
if (params->channel_fixed)
brcmf_dbg(CONN, "fixed channel required\n");
else
brcmf_dbg(CONN, "no fixed channel required\n");
if (params->ie && params->ie_len)
brcmf_dbg(CONN, "ie len: %d\n", params->ie_len);
else
brcmf_dbg(CONN, "no ie specified\n");
if (params->beacon_interval)
brcmf_dbg(CONN, "beacon interval: %d\n",
params->beacon_interval);
else
brcmf_dbg(CONN, "no beacon interval specified\n");
if (params->basic_rates)
brcmf_dbg(CONN, "basic rates: %08X\n", params->basic_rates);
else
brcmf_dbg(CONN, "no basic rates specified\n");
if (params->privacy)
brcmf_dbg(CONN, "privacy required\n");
else
brcmf_dbg(CONN, "no privacy required\n");
/* Configure Privacy for starter */
if (params->privacy)
wsec |= WEP_ENABLED;
err = brcmf_fil_iovar_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("wsec failed (%d)\n", err);
goto done;
}
/* Configure Beacon Interval for starter */
if (params->beacon_interval)
bcnprd = params->beacon_interval;
else
bcnprd = 100;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD, bcnprd);
if (err) {
brcmf_err("WLC_SET_BCNPRD failed (%d)\n", err);
goto done;
}
/* Configure required join parameter */
memset(&join_params, 0, sizeof(struct brcmf_join_params));
/* SSID */
ssid_len = min_t(u32, params->ssid_len, IEEE80211_MAX_SSID_LEN);
memcpy(join_params.ssid_le.SSID, params->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
join_params_size = sizeof(join_params.ssid_le);
/* BSSID */
if (params->bssid) {
memcpy(join_params.params_le.bssid, params->bssid, ETH_ALEN);
join_params_size += BRCMF_ASSOC_PARAMS_FIXED_SIZE;
memcpy(profile->bssid, params->bssid, ETH_ALEN);
} else {
eth_broadcast_addr(join_params.params_le.bssid);
eth_zero_addr(profile->bssid);
}
/* Channel */
if (params->chandef.chan) {
u32 target_channel;
cfg->channel =
ieee80211_frequency_to_channel(
params->chandef.chan->center_freq);
if (params->channel_fixed) {
/* adding chanspec */
chanspec = chandef_to_chanspec(&cfg->d11inf,
¶ms->chandef);
join_params.params_le.chanspec_list[0] =
cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
/* set channel for starter */
target_channel = cfg->channel;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_CHANNEL,
target_channel);
if (err) {
brcmf_err("WLC_SET_CHANNEL failed (%d)\n", err);
goto done;
}
} else
cfg->channel = 0;
cfg->ibss_starter = false;
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err) {
brcmf_err("WLC_SET_SSID failed (%d)\n", err);
goto done;
}
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_leave_ibss(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif)) {
/* When driver is being unloaded, it can end up here. If an
* error is returned then later on a debug trace in the wireless
* core module will be printed. To avoid this 0 is returned.
*/
return 0;
}
brcmf_link_down(ifp->vif, WLAN_REASON_DEAUTH_LEAVING);
brcmf_net_setcarrier(ifp, false);
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32 brcmf_set_wpa_version(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_1)
val = WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED;
else if (sme->crypto.wpa_versions & NL80211_WPA_VERSION_2)
val = WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED;
else
val = WPA_AUTH_DISABLED;
brcmf_dbg(CONN, "setting wpa_auth to 0x%0x\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("set wpa_auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->wpa_versions = sme->crypto.wpa_versions;
return err;
}
static s32 brcmf_set_auth_type(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 val = 0;
s32 err = 0;
switch (sme->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
val = 0;
brcmf_dbg(CONN, "open system\n");
break;
case NL80211_AUTHTYPE_SHARED_KEY:
val = 1;
brcmf_dbg(CONN, "shared key\n");
break;
default:
val = 2;
brcmf_dbg(CONN, "automatic, auth type (%d)\n", sme->auth_type);
break;
}
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err) {
brcmf_err("set auth failed (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->auth_type = sme->auth_type;
return err;
}
static s32
brcmf_set_wsec_mode(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
s32 pval = 0;
s32 gval = 0;
s32 wsec;
s32 err = 0;
if (sme->crypto.n_ciphers_pairwise) {
switch (sme->crypto.ciphers_pairwise[0]) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
pval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
pval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
pval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
pval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher pairwise (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
}
if (sme->crypto.cipher_group) {
switch (sme->crypto.cipher_group) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
gval = WEP_ENABLED;
break;
case WLAN_CIPHER_SUITE_TKIP:
gval = TKIP_ENABLED;
break;
case WLAN_CIPHER_SUITE_CCMP:
gval = AES_ENABLED;
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
gval = AES_ENABLED;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
brcmf_dbg(CONN, "pval (%d) gval (%d)\n", pval, gval);
/* In case of privacy, but no security and WPS then simulate */
/* setting AES. WPS-2.0 allows no security */
if (brcmf_find_wpsie(sme->ie, sme->ie_len) && !pval && !gval &&
sme->privacy)
pval = AES_ENABLED;
wsec = pval | gval;
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wsec", wsec);
if (err) {
brcmf_err("error (%d)\n", err);
return err;
}
sec = &profile->sec;
sec->cipher_pairwise = sme->crypto.ciphers_pairwise[0];
sec->cipher_group = sme->crypto.cipher_group;
return err;
}
static s32
brcmf_set_key_mgmt(struct net_device *ndev, struct cfg80211_connect_params *sme)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
s32 val;
s32 err;
const struct brcmf_tlv *rsn_ie;
const u8 *ie;
u32 ie_len;
u32 offset;
u16 rsn_cap;
u32 mfp;
u16 count;
profile->use_fwsup = BRCMF_PROFILE_FWSUP_NONE;
if (!sme->crypto.n_akm_suites)
return 0;
err = brcmf_fil_bsscfg_int_get(netdev_priv(ndev), "wpa_auth", &val);
if (err) {
brcmf_err("could not get wpa_auth (%d)\n", err);
return err;
}
if (val & (WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA_AUTH_UNSPECIFIED;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
} else if (val & (WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED)) {
switch (sme->crypto.akm_suites[0]) {
case WLAN_AKM_SUITE_8021X:
val = WPA2_AUTH_UNSPECIFIED;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_8021X_SHA256:
val = WPA2_AUTH_1X_SHA256;
if (sme->want_1x)
profile->use_fwsup = BRCMF_PROFILE_FWSUP_1X;
break;
case WLAN_AKM_SUITE_PSK_SHA256:
val = WPA2_AUTH_PSK_SHA256;
break;
case WLAN_AKM_SUITE_PSK:
val = WPA2_AUTH_PSK;
break;
default:
brcmf_err("invalid cipher group (%d)\n",
sme->crypto.cipher_group);
return -EINVAL;
}
}
if (profile->use_fwsup == BRCMF_PROFILE_FWSUP_1X)
brcmf_dbg(INFO, "using 1X offload\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
goto skip_mfp_config;
/* The MFP mode (1 or 2) needs to be determined, parse IEs. The
* IE will not be verified, just a quick search for MFP config
*/
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie, sme->ie_len,
WLAN_EID_RSN);
if (!rsn_ie)
goto skip_mfp_config;
ie = (const u8 *)rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
/* Skip unicast suite */
offset = TLV_HDR_LEN + WPA_IE_VERSION_LEN + WPA_IE_MIN_OUI_LEN;
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip multicast suite */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len)
goto skip_mfp_config;
/* Skip auth key management suite(s) */
count = ie[offset] + (ie[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN);
if (offset + WPA_IE_SUITE_COUNT_LEN > ie_len)
goto skip_mfp_config;
/* Ready to read capabilities */
mfp = BRCMF_MFP_NONE;
rsn_cap = ie[offset] + (ie[offset + 1] << 8);
if (rsn_cap & RSN_CAP_MFPR_MASK)
mfp = BRCMF_MFP_REQUIRED;
else if (rsn_cap & RSN_CAP_MFPC_MASK)
mfp = BRCMF_MFP_CAPABLE;
brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "mfp", mfp);
skip_mfp_config:
brcmf_dbg(CONN, "setting wpa_auth to %d\n", val);
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "wpa_auth", val);
if (err) {
brcmf_err("could not set wpa_auth (%d)\n", err);
return err;
}
return err;
}
static s32
brcmf_set_sharedkey(struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_profile *profile = ndev_to_prof(ndev);
struct brcmf_cfg80211_security *sec;
struct brcmf_wsec_key key;
s32 val;
s32 err = 0;
brcmf_dbg(CONN, "key len (%d)\n", sme->key_len);
if (sme->key_len == 0)
return 0;
sec = &profile->sec;
brcmf_dbg(CONN, "wpa_versions 0x%x cipher_pairwise 0x%x\n",
sec->wpa_versions, sec->cipher_pairwise);
if (sec->wpa_versions & (NL80211_WPA_VERSION_1 | NL80211_WPA_VERSION_2))
return 0;
if (!(sec->cipher_pairwise &
(WLAN_CIPHER_SUITE_WEP40 | WLAN_CIPHER_SUITE_WEP104)))
return 0;
memset(&key, 0, sizeof(key));
key.len = (u32) sme->key_len;
key.index = (u32) sme->key_idx;
if (key.len > sizeof(key.data)) {
brcmf_err("Too long key length (%u)\n", key.len);
return -EINVAL;
}
memcpy(key.data, sme->key, key.len);
key.flags = BRCMF_PRIMARY_KEY;
switch (sec->cipher_pairwise) {
case WLAN_CIPHER_SUITE_WEP40:
key.algo = CRYPTO_ALGO_WEP1;
break;
case WLAN_CIPHER_SUITE_WEP104:
key.algo = CRYPTO_ALGO_WEP128;
break;
default:
brcmf_err("Invalid algorithm (%d)\n",
sme->crypto.ciphers_pairwise[0]);
return -EINVAL;
}
/* Set the new key/index */
brcmf_dbg(CONN, "key length (%d) key index (%d) algo (%d)\n",
key.len, key.index, key.algo);
brcmf_dbg(CONN, "key \"%s\"\n", key.data);
err = send_key_to_dongle(netdev_priv(ndev), &key);
if (err)
return err;
if (sec->auth_type == NL80211_AUTHTYPE_SHARED_KEY) {
brcmf_dbg(CONN, "set auth_type to shared key\n");
val = WL_AUTH_SHARED_KEY; /* shared key */
err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), "auth", val);
if (err)
brcmf_err("set auth failed (%d)\n", err);
}
return err;
}
static
enum nl80211_auth_type brcmf_war_auth_type(struct brcmf_if *ifp,
enum nl80211_auth_type type)
{
if (type == NL80211_AUTHTYPE_AUTOMATIC &&
brcmf_feat_is_quirk_enabled(ifp, BRCMF_FEAT_QUIRK_AUTO_AUTH)) {
brcmf_dbg(CONN, "WAR: use OPEN instead of AUTO\n");
type = NL80211_AUTHTYPE_OPEN_SYSTEM;
}
return type;
}
static void brcmf_set_join_pref(struct brcmf_if *ifp,
struct cfg80211_bss_selection *bss_select)
{
struct brcmf_join_pref_params join_pref_params[2];
enum nl80211_band band;
int err, i = 0;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
if (bss_select->behaviour != NL80211_BSS_SELECT_ATTR_BAND_PREF)
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_ASSOC_PREFER, WLC_BAND_AUTO);
switch (bss_select->behaviour) {
case __NL80211_BSS_SELECT_ATTR_INVALID:
brcmf_c_set_joinpref_default(ifp);
return;
case NL80211_BSS_SELECT_ATTR_BAND_PREF:
join_pref_params[i].type = BRCMF_JOIN_PREF_BAND;
band = bss_select->param.band_pref;
join_pref_params[i].band = nl80211_band_to_fwil(band);
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI_ADJUST:
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI_DELTA;
band = bss_select->param.adjust.band;
join_pref_params[i].band = nl80211_band_to_fwil(band);
join_pref_params[i].rssi_gain = bss_select->param.adjust.delta;
i++;
break;
case NL80211_BSS_SELECT_ATTR_RSSI:
default:
break;
}
join_pref_params[i].type = BRCMF_JOIN_PREF_RSSI;
join_pref_params[i].len = 2;
join_pref_params[i].rssi_gain = 0;
join_pref_params[i].band = 0;
err = brcmf_fil_iovar_data_set(ifp, "join_pref", join_pref_params,
sizeof(join_pref_params));
if (err)
brcmf_err("Set join_pref error (%d)\n", err);
}
static s32
brcmf_cfg80211_connect(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_connect_params *sme)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan = sme->channel;
struct brcmf_join_params join_params;
size_t join_params_size;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
const void *ie;
u32 ie_len;
struct brcmf_ext_join_params_le *ext_join_params;
u16 chanspec;
s32 err = 0;
u32 ssid_len;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
if (!sme->ssid) {
brcmf_err("Invalid ssid\n");
return -EOPNOTSUPP;
}
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif) {
/* A normal (non P2P) connection request setup. */
ie = NULL;
ie_len = 0;
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)sme->ie, sme->ie_len);
if (wpa_ie) {
ie = wpa_ie;
ie_len = wpa_ie->len + TLV_HDR_LEN;
} else {
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie,
sme->ie_len,
WLAN_EID_RSN);
if (rsn_ie) {
ie = rsn_ie;
ie_len = rsn_ie->len + TLV_HDR_LEN;
}
}
brcmf_fil_iovar_data_set(ifp, "wpaie", ie, ie_len);
}
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
set_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
if (chan) {
cfg->channel =
ieee80211_frequency_to_channel(chan->center_freq);
chanspec = channel_to_chanspec(&cfg->d11inf, chan);
brcmf_dbg(CONN, "channel=%d, center_req=%d, chanspec=0x%04x\n",
cfg->channel, chan->center_freq, chanspec);
} else {
cfg->channel = 0;
chanspec = 0;
}
brcmf_dbg(INFO, "ie (%p), ie_len (%zd)\n", sme->ie, sme->ie_len);
err = brcmf_set_wpa_version(ndev, sme);
if (err) {
brcmf_err("wl_set_wpa_version failed (%d)\n", err);
goto done;
}
sme->auth_type = brcmf_war_auth_type(ifp, sme->auth_type);
err = brcmf_set_auth_type(ndev, sme);
if (err) {
brcmf_err("wl_set_auth_type failed (%d)\n", err);
goto done;
}
err = brcmf_set_wsec_mode(ndev, sme);
if (err) {
brcmf_err("wl_set_set_cipher failed (%d)\n", err);
goto done;
}
err = brcmf_set_key_mgmt(ndev, sme);
if (err) {
brcmf_err("wl_set_key_mgmt failed (%d)\n", err);
goto done;
}
err = brcmf_set_sharedkey(ndev, sme);
if (err) {
brcmf_err("brcmf_set_sharedkey failed (%d)\n", err);
goto done;
}
if (sme->crypto.psk) {
if (WARN_ON(profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE)) {
err = -EINVAL;
goto done;
}
brcmf_dbg(INFO, "using PSK offload\n");
profile->use_fwsup = BRCMF_PROFILE_FWSUP_PSK;
}
if (profile->use_fwsup != BRCMF_PROFILE_FWSUP_NONE) {
/* enable firmware supplicant for this interface */
err = brcmf_fil_iovar_int_set(ifp, "sup_wpa", 1);
if (err < 0) {
brcmf_err("failed to enable fw supplicant\n");
goto done;
}
}
if (profile->use_fwsup == BRCMF_PROFILE_FWSUP_PSK) {
err = brcmf_set_pmk(ifp, sme->crypto.psk,
BRCMF_WSEC_MAX_PSK_LEN);
if (err)
goto done;
}
/* Join with specific BSSID and cached SSID
* If SSID is zero join based on BSSID only
*/
join_params_size = offsetof(struct brcmf_ext_join_params_le, assoc_le) +
offsetof(struct brcmf_assoc_params_le, chanspec_list);
if (cfg->channel)
join_params_size += sizeof(u16);
ext_join_params = kzalloc(join_params_size, GFP_KERNEL);
if (ext_join_params == NULL) {
err = -ENOMEM;
goto done;
}
ssid_len = min_t(u32, sme->ssid_len, IEEE80211_MAX_SSID_LEN);
ext_join_params->ssid_le.SSID_len = cpu_to_le32(ssid_len);
memcpy(&ext_join_params->ssid_le.SSID, sme->ssid, ssid_len);
if (ssid_len < IEEE80211_MAX_SSID_LEN)
brcmf_dbg(CONN, "SSID \"%s\", len (%d)\n",
ext_join_params->ssid_le.SSID, ssid_len);
/* Set up join scan parameters */
ext_join_params->scan_le.scan_type = -1;
ext_join_params->scan_le.home_time = cpu_to_le32(-1);
if (sme->bssid)
memcpy(&ext_join_params->assoc_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(ext_join_params->assoc_le.bssid);
if (cfg->channel) {
ext_join_params->assoc_le.chanspec_num = cpu_to_le32(1);
ext_join_params->assoc_le.chanspec_list[0] =
cpu_to_le16(chanspec);
/* Increase dwell time to receive probe response or detect
* beacon from target AP at a noisy air only during connect
* command.
*/
ext_join_params->scan_le.active_time =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS);
ext_join_params->scan_le.passive_time =
cpu_to_le32(BRCMF_SCAN_JOIN_PASSIVE_DWELL_TIME_MS);
/* To sync with presence period of VSDB GO send probe request
* more frequently. Probe request will be stopped when it gets
* probe response from target AP/GO.
*/
ext_join_params->scan_le.nprobes =
cpu_to_le32(BRCMF_SCAN_JOIN_ACTIVE_DWELL_TIME_MS /
BRCMF_SCAN_JOIN_PROBE_INTERVAL_MS);
} else {
ext_join_params->scan_le.active_time = cpu_to_le32(-1);
ext_join_params->scan_le.passive_time = cpu_to_le32(-1);
ext_join_params->scan_le.nprobes = cpu_to_le32(-1);
}
brcmf_set_join_pref(ifp, &sme->bss_select);
err = brcmf_fil_bsscfg_data_set(ifp, "join", ext_join_params,
join_params_size);
kfree(ext_join_params);
if (!err)
/* This is it. join command worked, we are done */
goto done;
/* join command failed, fallback to set ssid */
memset(&join_params, 0, sizeof(join_params));
join_params_size = sizeof(join_params.ssid_le);
memcpy(&join_params.ssid_le.SSID, sme->ssid, ssid_len);
join_params.ssid_le.SSID_len = cpu_to_le32(ssid_len);
if (sme->bssid)
memcpy(join_params.params_le.bssid, sme->bssid, ETH_ALEN);
else
eth_broadcast_addr(join_params.params_le.bssid);
if (cfg->channel) {
join_params.params_le.chanspec_list[0] = cpu_to_le16(chanspec);
join_params.params_le.chanspec_num = cpu_to_le32(1);
join_params_size += sizeof(join_params.params_le);
}
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, join_params_size);
if (err)
brcmf_err("BRCMF_C_SET_SSID failed (%d)\n", err);
done:
if (err)
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_disconnect(struct wiphy *wiphy, struct net_device *ndev,
u16 reason_code)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_scb_val_le scbval;
s32 err = 0;
brcmf_dbg(TRACE, "Enter. Reason code = %d\n", reason_code);
if (!check_vif_up(ifp->vif))
return -EIO;
clear_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
clear_bit(BRCMF_VIF_STATUS_CONNECTING, &ifp->vif->sme_state);
cfg80211_disconnected(ndev, reason_code, NULL, 0, true, GFP_KERNEL);
memcpy(&scbval.ea, &profile->bssid, ETH_ALEN);
scbval.val = cpu_to_le32(reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_DISASSOC,
&scbval, sizeof(scbval));
if (err)
brcmf_err("error (%d)\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_set_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
enum nl80211_tx_power_setting type, s32 mbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
s32 disable;
u32 qdbm = 127;
brcmf_dbg(TRACE, "Enter %d %d\n", type, mbm);
if (!check_vif_up(ifp->vif))
return -EIO;
switch (type) {
case NL80211_TX_POWER_AUTOMATIC:
break;
case NL80211_TX_POWER_LIMITED:
case NL80211_TX_POWER_FIXED:
if (mbm < 0) {
brcmf_err("TX_POWER_FIXED - dbm is negative\n");
err = -EINVAL;
goto done;
}
qdbm = MBM_TO_DBM(4 * mbm);
if (qdbm > 127)
qdbm = 127;
qdbm |= WL_TXPWR_OVERRIDE;
break;
default:
brcmf_err("Unsupported type %d\n", type);
err = -EINVAL;
goto done;
}
/* Make sure radio is off or on as far as software is concerned */
disable = WL_RADIO_SW_DISABLE << 16;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_RADIO, disable);
if (err)
brcmf_err("WLC_SET_RADIO error (%d)\n", err);
err = brcmf_fil_iovar_int_set(ifp, "qtxpower", qdbm);
if (err)
brcmf_err("qtxpower error (%d)\n", err);
done:
brcmf_dbg(TRACE, "Exit %d (qdbm)\n", qdbm & ~WL_TXPWR_OVERRIDE);
return err;
}
static s32
brcmf_cfg80211_get_tx_power(struct wiphy *wiphy, struct wireless_dev *wdev,
s32 *dbm)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 qdbm = 0;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_iovar_int_get(ifp, "qtxpower", &qdbm);
if (err) {
brcmf_err("error (%d)\n", err);
goto done;
}
*dbm = (qdbm & ~WL_TXPWR_OVERRIDE) / 4;
done:
brcmf_dbg(TRACE, "Exit (0x%x %d)\n", qdbm, *dbm);
return err;
}
static s32
brcmf_cfg80211_config_default_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool unicast, bool multicast)
{
struct brcmf_if *ifp = netdev_priv(ndev);
u32 index;
u32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
goto done;
}
if (wsec & WEP_ENABLED) {
/* Just select a new current key */
index = key_idx;
err = brcmf_fil_cmd_int_set(ifp,
BRCMF_C_SET_KEY_PRIMARY, index);
if (err)
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 err;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
return -EINVAL;
}
key = &ifp->vif->profile.key[key_idx];
if (key->algo == CRYPTO_ALGO_OFF) {
brcmf_dbg(CONN, "Ignore clearing of (never configured) key\n");
return -EINVAL;
}
memset(key, 0, sizeof(*key));
key->index = (u32)key_idx;
key->flags = BRCMF_PRIMARY_KEY;
/* Clear the key/index */
err = send_key_to_dongle(ifp, key);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_add_key(struct wiphy *wiphy, struct net_device *ndev,
u8 key_idx, bool pairwise, const u8 *mac_addr,
struct key_params *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_wsec_key *key;
s32 val;
s32 wsec;
s32 err;
u8 keybuf[8];
bool ext_key;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
if (key_idx >= BRCMF_MAX_DEFAULT_KEYS) {
/* we ignore this key index in this case */
brcmf_err("invalid key index (%d)\n", key_idx);
return -EINVAL;
}
if (params->key_len == 0)
return brcmf_cfg80211_del_key(wiphy, ndev, key_idx, pairwise,
mac_addr);
if (params->key_len > sizeof(key->data)) {
brcmf_err("Too long key length (%u)\n", params->key_len);
return -EINVAL;
}
ext_key = false;
if (mac_addr && (params->cipher != WLAN_CIPHER_SUITE_WEP40) &&
(params->cipher != WLAN_CIPHER_SUITE_WEP104)) {
brcmf_dbg(TRACE, "Ext key, mac %pM", mac_addr);
ext_key = true;
}
key = &ifp->vif->profile.key[key_idx];
memset(key, 0, sizeof(*key));
if ((ext_key) && (!is_multicast_ether_addr(mac_addr)))
memcpy((char *)&key->ea, (void *)mac_addr, ETH_ALEN);
key->len = params->key_len;
key->index = key_idx;
memcpy(key->data, params->key, key->len);
if (!ext_key)
key->flags = BRCMF_PRIMARY_KEY;
switch (params->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
key->algo = CRYPTO_ALGO_WEP1;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
break;
case WLAN_CIPHER_SUITE_WEP104:
key->algo = CRYPTO_ALGO_WEP128;
val = WEP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
break;
case WLAN_CIPHER_SUITE_TKIP:
if (!brcmf_is_apmode(ifp->vif)) {
brcmf_dbg(CONN, "Swapping RX/TX MIC key\n");
memcpy(keybuf, &key->data[24], sizeof(keybuf));
memcpy(&key->data[24], &key->data[16], sizeof(keybuf));
memcpy(&key->data[16], keybuf, sizeof(keybuf));
}
key->algo = CRYPTO_ALGO_TKIP;
val = TKIP_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
break;
case WLAN_CIPHER_SUITE_CCMP:
key->algo = CRYPTO_ALGO_AES_CCM;
val = AES_ENABLED;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_CCMP\n");
break;
default:
brcmf_err("Invalid cipher (0x%x)\n", params->cipher);
err = -EINVAL;
goto done;
}
err = send_key_to_dongle(ifp, key);
if (ext_key || err)
goto done;
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
goto done;
}
wsec |= val;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err) {
brcmf_err("set wsec error (%d)\n", err);
goto done;
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_get_key(struct wiphy *wiphy, struct net_device *ndev, u8 key_idx,
bool pairwise, const u8 *mac_addr, void *cookie,
void (*callback)(void *cookie,
struct key_params *params))
{
struct key_params params;
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_security *sec;
s32 wsec;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CONN, "key index (%d)\n", key_idx);
if (!check_vif_up(ifp->vif))
return -EIO;
memset(¶ms, 0, sizeof(params));
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("WLC_GET_WSEC error (%d)\n", err);
/* Ignore this error, may happen during DISASSOC */
err = -EAGAIN;
goto done;
}
if (wsec & WEP_ENABLED) {
sec = &profile->sec;
if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP40) {
params.cipher = WLAN_CIPHER_SUITE_WEP40;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP40\n");
} else if (sec->cipher_pairwise & WLAN_CIPHER_SUITE_WEP104) {
params.cipher = WLAN_CIPHER_SUITE_WEP104;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_WEP104\n");
}
} else if (wsec & TKIP_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_TKIP;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_TKIP\n");
} else if (wsec & AES_ENABLED) {
params.cipher = WLAN_CIPHER_SUITE_AES_CMAC;
brcmf_dbg(CONN, "WLAN_CIPHER_SUITE_AES_CMAC\n");
} else {
brcmf_err("Invalid algo (0x%x)\n", wsec);
err = -EINVAL;
goto done;
}
callback(cookie, ¶ms);
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_config_default_mgmt_key(struct wiphy *wiphy,
struct net_device *ndev, u8 key_idx)
{
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter key_idx %d\n", key_idx);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
return 0;
brcmf_dbg(INFO, "Not supported\n");
return -EOPNOTSUPP;
}
static void
brcmf_cfg80211_reconfigure_wep(struct brcmf_if *ifp)
{
s32 err;
u8 key_idx;
struct brcmf_wsec_key *key;
s32 wsec;
for (key_idx = 0; key_idx < BRCMF_MAX_DEFAULT_KEYS; key_idx++) {
key = &ifp->vif->profile.key[key_idx];
if ((key->algo == CRYPTO_ALGO_WEP1) ||
(key->algo == CRYPTO_ALGO_WEP128))
break;
}
if (key_idx == BRCMF_MAX_DEFAULT_KEYS)
return;
err = send_key_to_dongle(ifp, key);
if (err) {
brcmf_err("Setting WEP key failed (%d)\n", err);
return;
}
err = brcmf_fil_bsscfg_int_get(ifp, "wsec", &wsec);
if (err) {
brcmf_err("get wsec error (%d)\n", err);
return;
}
wsec |= WEP_ENABLED;
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err)
brcmf_err("set wsec error (%d)\n", err);
}
static void brcmf_convert_sta_flags(u32 fw_sta_flags, struct station_info *si)
{
struct nl80211_sta_flag_update *sfu;
brcmf_dbg(TRACE, "flags %08x\n", fw_sta_flags);
si->filled |= BIT(NL80211_STA_INFO_STA_FLAGS);
sfu = &si->sta_flags;
sfu->mask = BIT(NL80211_STA_FLAG_WME) |
BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED) |
BIT(NL80211_STA_FLAG_AUTHORIZED);
if (fw_sta_flags & BRCMF_STA_WME)
sfu->set |= BIT(NL80211_STA_FLAG_WME);
if (fw_sta_flags & BRCMF_STA_AUTHE)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
if (fw_sta_flags & BRCMF_STA_ASSOC)
sfu->set |= BIT(NL80211_STA_FLAG_ASSOCIATED);
if (fw_sta_flags & BRCMF_STA_AUTHO)
sfu->set |= BIT(NL80211_STA_FLAG_AUTHORIZED);
}
static void brcmf_fill_bss_param(struct brcmf_if *ifp, struct station_info *si)
{
struct {
__le32 len;
struct brcmf_bss_info_le bss_le;
} *buf;
u16 capability;
int err;
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (!buf)
return;
buf->len = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO, buf,
WL_BSS_INFO_MAX);
if (err) {
brcmf_err("Failed to get bss info (%d)\n", err);
goto out_kfree;
}
si->filled |= BIT(NL80211_STA_INFO_BSS_PARAM);
si->bss_param.beacon_interval = le16_to_cpu(buf->bss_le.beacon_period);
si->bss_param.dtim_period = buf->bss_le.dtim_period;
capability = le16_to_cpu(buf->bss_le.capability);
if (capability & IEEE80211_HT_STBC_PARAM_DUAL_CTS_PROT)
si->bss_param.flags |= BSS_PARAM_FLAGS_CTS_PROT;
if (capability & WLAN_CAPABILITY_SHORT_PREAMBLE)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_PREAMBLE;
if (capability & WLAN_CAPABILITY_SHORT_SLOT_TIME)
si->bss_param.flags |= BSS_PARAM_FLAGS_SHORT_SLOT_TIME;
out_kfree:
kfree(buf);
}
static s32
brcmf_cfg80211_get_station_ibss(struct brcmf_if *ifp,
struct station_info *sinfo)
{
struct brcmf_scb_val_le scbval;
struct brcmf_pktcnt_le pktcnt;
s32 err;
u32 rate;
u32 rssi;
/* Get the current tx rate */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_RATE, &rate);
if (err < 0) {
brcmf_err("BRCMF_C_GET_RATE error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy = rate * 5;
memset(&scbval, 0, sizeof(scbval));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI, &scbval,
sizeof(scbval));
if (err) {
brcmf_err("BRCMF_C_GET_RSSI error (%d)\n", err);
return err;
}
rssi = le32_to_cpu(scbval.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_GET_PKTCNTS, &pktcnt,
sizeof(pktcnt));
if (err) {
brcmf_err("BRCMF_C_GET_GET_PKTCNTS error (%d)\n", err);
return err;
}
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS) |
BIT(NL80211_STA_INFO_RX_DROP_MISC) |
BIT(NL80211_STA_INFO_TX_PACKETS) |
BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->rx_packets = le32_to_cpu(pktcnt.rx_good_pkt);
sinfo->rx_dropped_misc = le32_to_cpu(pktcnt.rx_bad_pkt);
sinfo->tx_packets = le32_to_cpu(pktcnt.tx_good_pkt);
sinfo->tx_failed = le32_to_cpu(pktcnt.tx_bad_pkt);
return 0;
}
static s32
brcmf_cfg80211_get_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_info *sinfo)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_scb_val_le scb_val;
s32 err = 0;
struct brcmf_sta_info_le sta_info_le;
u32 sta_flags;
u32 is_tdls_peer;
s32 total_rssi;
s32 count_rssi;
int rssi;
u32 i;
brcmf_dbg(TRACE, "Enter, MAC %pM\n", mac);
if (!check_vif_up(ifp->vif))
return -EIO;
if (brcmf_is_ibssmode(ifp->vif))
return brcmf_cfg80211_get_station_ibss(ifp, sinfo);
memset(&sta_info_le, 0, sizeof(sta_info_le));
memcpy(&sta_info_le, mac, ETH_ALEN);
err = brcmf_fil_iovar_data_get(ifp, "tdls_sta_info",
&sta_info_le,
sizeof(sta_info_le));
is_tdls_peer = !err;
if (err) {
err = brcmf_fil_iovar_data_get(ifp, "sta_info",
&sta_info_le,
sizeof(sta_info_le));
if (err < 0) {
brcmf_err("GET STA INFO failed, %d\n", err);
goto done;
}
}
brcmf_dbg(TRACE, "version %d\n", le16_to_cpu(sta_info_le.ver));
sinfo->filled = BIT(NL80211_STA_INFO_INACTIVE_TIME);
sinfo->inactive_time = le32_to_cpu(sta_info_le.idle) * 1000;
sta_flags = le32_to_cpu(sta_info_le.flags);
brcmf_convert_sta_flags(sta_flags, sinfo);
sinfo->sta_flags.mask |= BIT(NL80211_STA_FLAG_TDLS_PEER);
if (is_tdls_peer)
sinfo->sta_flags.set |= BIT(NL80211_STA_FLAG_TDLS_PEER);
else
sinfo->sta_flags.set &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
if (sta_flags & BRCMF_STA_ASSOC) {
sinfo->filled |= BIT(NL80211_STA_INFO_CONNECTED_TIME);
sinfo->connected_time = le32_to_cpu(sta_info_le.in);
brcmf_fill_bss_param(ifp, sinfo);
}
if (sta_flags & BRCMF_STA_SCBSTATS) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_FAILED);
sinfo->tx_failed = le32_to_cpu(sta_info_le.tx_failures);
sinfo->filled |= BIT(NL80211_STA_INFO_TX_PACKETS);
sinfo->tx_packets = le32_to_cpu(sta_info_le.tx_pkts);
sinfo->tx_packets += le32_to_cpu(sta_info_le.tx_mcast_pkts);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_PACKETS);
sinfo->rx_packets = le32_to_cpu(sta_info_le.rx_ucast_pkts);
sinfo->rx_packets += le32_to_cpu(sta_info_le.rx_mcast_pkts);
if (sinfo->tx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BITRATE);
sinfo->txrate.legacy =
le32_to_cpu(sta_info_le.tx_rate) / 100;
}
if (sinfo->rx_packets) {
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BITRATE);
sinfo->rxrate.legacy =
le32_to_cpu(sta_info_le.rx_rate) / 100;
}
if (le16_to_cpu(sta_info_le.ver) >= 4) {
sinfo->filled |= BIT(NL80211_STA_INFO_TX_BYTES);
sinfo->tx_bytes = le64_to_cpu(sta_info_le.tx_tot_bytes);
sinfo->filled |= BIT(NL80211_STA_INFO_RX_BYTES);
sinfo->rx_bytes = le64_to_cpu(sta_info_le.rx_tot_bytes);
}
total_rssi = 0;
count_rssi = 0;
for (i = 0; i < BRCMF_ANT_MAX; i++) {
if (sta_info_le.rssi[i]) {
sinfo->chain_signal_avg[count_rssi] =
sta_info_le.rssi[i];
sinfo->chain_signal[count_rssi] =
sta_info_le.rssi[i];
total_rssi += sta_info_le.rssi[i];
count_rssi++;
}
}
if (count_rssi) {
sinfo->filled |= BIT(NL80211_STA_INFO_CHAIN_SIGNAL);
sinfo->chains = count_rssi;
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
total_rssi /= count_rssi;
sinfo->signal = total_rssi;
} else if (test_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state)) {
memset(&scb_val, 0, sizeof(scb_val));
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_RSSI,
&scb_val, sizeof(scb_val));
if (err) {
brcmf_err("Could not get rssi (%d)\n", err);
goto done;
} else {
rssi = le32_to_cpu(scb_val.val);
sinfo->filled |= BIT(NL80211_STA_INFO_SIGNAL);
sinfo->signal = rssi;
brcmf_dbg(CONN, "RSSI %d dBm\n", rssi);
}
}
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_dump_station(struct wiphy *wiphy, struct net_device *ndev,
int idx, u8 *mac, struct station_info *sinfo)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, idx %d\n", idx);
if (idx == 0) {
cfg->assoclist.count = cpu_to_le32(BRCMF_MAX_ASSOCLIST);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_ASSOCLIST,
&cfg->assoclist,
sizeof(cfg->assoclist));
if (err) {
brcmf_err("BRCMF_C_GET_ASSOCLIST unsupported, err=%d\n",
err);
cfg->assoclist.count = 0;
return -EOPNOTSUPP;
}
}
if (idx < le32_to_cpu(cfg->assoclist.count)) {
memcpy(mac, cfg->assoclist.mac[idx], ETH_ALEN);
return brcmf_cfg80211_get_station(wiphy, ndev, mac, sinfo);
}
return -ENOENT;
}
static s32
brcmf_cfg80211_set_power_mgmt(struct wiphy *wiphy, struct net_device *ndev,
bool enabled, s32 timeout)
{
s32 pm;
s32 err = 0;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
/*
* Powersave enable/disable request is coming from the
* cfg80211 even before the interface is up. In that
* scenario, driver will be storing the power save
* preference in cfg struct to apply this to
* FW later while initializing the dongle
*/
cfg->pwr_save = enabled;
if (!check_vif_up(ifp->vif)) {
brcmf_dbg(INFO, "Device is not ready, storing the value in cfg_info struct\n");
goto done;
}
pm = enabled ? PM_FAST : PM_OFF;
/* Do not enable the power save after assoc if it is a p2p interface */
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_P2P_CLIENT) {
brcmf_dbg(INFO, "Do not enable power save for P2P clients\n");
pm = PM_OFF;
}
brcmf_dbg(INFO, "power save %s\n", (pm ? "enabled" : "disabled"));
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, pm);
if (err) {
if (err == -ENODEV)
brcmf_err("net_device is not ready yet\n");
else
brcmf_err("error (%d)\n", err);
}
done:
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_inform_single_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bi)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct cfg80211_bss *bss;
struct ieee80211_supported_band *band;
struct brcmu_chan ch;
u16 channel;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
if (le32_to_cpu(bi->length) > WL_BSS_INFO_MAX) {
brcmf_err("Bss info is larger than buffer. Discarding\n");
return 0;
}
if (!bi->ctl_ch) {
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
bi->ctl_ch = ch.control_ch_num;
}
channel = bi->ctl_ch;
if (channel <= CH_MAX_2G_CHANNEL)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(channel, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "bssid: %pM\n", bi->BSSID);
brcmf_dbg(CONN, "Channel: %d(%d)\n", channel, freq);
brcmf_dbg(CONN, "Capability: %X\n", notify_capability);
brcmf_dbg(CONN, "Beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "Signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN,
(const u8 *)bi->BSSID,
0, notify_capability,
notify_interval, notify_ie,
notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss)
return -ENOMEM;
cfg80211_put_bss(wiphy, bss);
return 0;
}
static struct brcmf_bss_info_le *
next_bss_le(struct brcmf_scan_results *list, struct brcmf_bss_info_le *bss)
{
if (bss == NULL)
return list->bss_info_le;
return (struct brcmf_bss_info_le *)((unsigned long)bss +
le32_to_cpu(bss->length));
}
static s32 brcmf_inform_bss(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_scan_results *bss_list;
struct brcmf_bss_info_le *bi = NULL; /* must be initialized */
s32 err = 0;
int i;
bss_list = (struct brcmf_scan_results *)cfg->escan_info.escan_buf;
if (bss_list->count != 0 &&
bss_list->version != BRCMF_BSS_INFO_VERSION) {
brcmf_err("Version %d != WL_BSS_INFO_VERSION\n",
bss_list->version);
return -EOPNOTSUPP;
}
brcmf_dbg(SCAN, "scanned AP count (%d)\n", bss_list->count);
for (i = 0; i < bss_list->count; i++) {
bi = next_bss_le(bss_list, bi);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
break;
}
return err;
}
static s32 brcmf_inform_ibss(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const u8 *bssid)
{
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel;
struct brcmf_bss_info_le *bi = NULL;
struct ieee80211_supported_band *band;
struct cfg80211_bss *bss;
struct brcmu_chan ch;
u8 *buf = NULL;
s32 err = 0;
u32 freq;
u16 notify_capability;
u16 notify_interval;
u8 *notify_ie;
size_t notify_ielen;
s32 notify_signal;
brcmf_dbg(TRACE, "Enter\n");
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto CleanUp;
}
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(netdev_priv(ndev), BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err) {
brcmf_err("WLC_GET_BSS_INFO failed: %d\n", err);
goto CleanUp;
}
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
cfg->channel = freq;
notify_channel = ieee80211_get_channel(wiphy, freq);
notify_capability = le16_to_cpu(bi->capability);
notify_interval = le16_to_cpu(bi->beacon_period);
notify_ie = (u8 *)bi + le16_to_cpu(bi->ie_offset);
notify_ielen = le32_to_cpu(bi->ie_length);
notify_signal = (s16)le16_to_cpu(bi->RSSI) * 100;
brcmf_dbg(CONN, "channel: %d(%d)\n", ch.control_ch_num, freq);
brcmf_dbg(CONN, "capability: %X\n", notify_capability);
brcmf_dbg(CONN, "beacon interval: %d\n", notify_interval);
brcmf_dbg(CONN, "signal: %d\n", notify_signal);
bss = cfg80211_inform_bss(wiphy, notify_channel,
CFG80211_BSS_FTYPE_UNKNOWN, bssid, 0,
notify_capability, notify_interval,
notify_ie, notify_ielen, notify_signal,
GFP_KERNEL);
if (!bss) {
err = -ENOMEM;
goto CleanUp;
}
cfg80211_put_bss(wiphy, bss);
CleanUp:
kfree(buf);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_update_bss_info(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_bss_info_le *bi;
const struct brcmf_tlv *tim;
u16 beacon_interval;
u8 dtim_period;
size_t ie_len;
u8 *ie;
s32 err = 0;
brcmf_dbg(TRACE, "Enter\n");
if (brcmf_is_ibssmode(ifp->vif))
return err;
*(__le32 *)cfg->extra_buf = cpu_to_le32(WL_EXTRA_BUF_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
cfg->extra_buf, WL_EXTRA_BUF_MAX);
if (err) {
brcmf_err("Could not get bss info %d\n", err);
goto update_bss_info_out;
}
bi = (struct brcmf_bss_info_le *)(cfg->extra_buf + 4);
err = brcmf_inform_single_bss(cfg, bi);
if (err)
goto update_bss_info_out;
ie = ((u8 *)bi) + le16_to_cpu(bi->ie_offset);
ie_len = le32_to_cpu(bi->ie_length);
beacon_interval = le16_to_cpu(bi->beacon_period);
tim = brcmf_parse_tlvs(ie, ie_len, WLAN_EID_TIM);
if (tim)
dtim_period = tim->data[1];
else {
/*
* active scan was done so we could not get dtim
* information out of probe response.
* so we speficially query dtim information to dongle.
*/
u32 var;
err = brcmf_fil_iovar_int_get(ifp, "dtim_assoc", &var);
if (err) {
brcmf_err("wl dtim_assoc failed (%d)\n", err);
goto update_bss_info_out;
}
dtim_period = (u8)var;
}
update_bss_info_out:
brcmf_dbg(TRACE, "Exit");
return err;
}
void brcmf_abort_scanning(struct brcmf_cfg80211_info *cfg)
{
struct escan_info *escan = &cfg->escan_info;
set_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
if (cfg->int_escan_map || cfg->scan_request) {
escan->escan_state = WL_ESCAN_STATE_IDLE;
brcmf_notify_escan_complete(cfg, escan->ifp, true, true);
}
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
clear_bit(BRCMF_SCAN_STATUS_ABORT, &cfg->scan_status);
}
static void brcmf_cfg80211_escan_timeout_worker(struct work_struct *work)
{
struct brcmf_cfg80211_info *cfg =
container_of(work, struct brcmf_cfg80211_info,
escan_timeout_work);
brcmf_inform_bss(cfg);
brcmf_notify_escan_complete(cfg, cfg->escan_info.ifp, true, true);
}
static void brcmf_escan_timeout(unsigned long data)
{
struct brcmf_cfg80211_info *cfg =
(struct brcmf_cfg80211_info *)data;
if (cfg->int_escan_map || cfg->scan_request) {
brcmf_err("timer expired\n");
schedule_work(&cfg->escan_timeout_work);
}
}
static s32
brcmf_compare_update_same_bss(struct brcmf_cfg80211_info *cfg,
struct brcmf_bss_info_le *bss,
struct brcmf_bss_info_le *bss_info_le)
{
struct brcmu_chan ch_bss, ch_bss_info_le;
ch_bss.chspec = le16_to_cpu(bss->chanspec);
cfg->d11inf.decchspec(&ch_bss);
ch_bss_info_le.chspec = le16_to_cpu(bss_info_le->chanspec);
cfg->d11inf.decchspec(&ch_bss_info_le);
if (!memcmp(&bss_info_le->BSSID, &bss->BSSID, ETH_ALEN) &&
ch_bss.band == ch_bss_info_le.band &&
bss_info_le->SSID_len == bss->SSID_len &&
!memcmp(bss_info_le->SSID, bss->SSID, bss_info_le->SSID_len)) {
if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) ==
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL)) {
s16 bss_rssi = le16_to_cpu(bss->RSSI);
s16 bss_info_rssi = le16_to_cpu(bss_info_le->RSSI);
/* preserve max RSSI if the measurements are
* both on-channel or both off-channel
*/
if (bss_info_rssi > bss_rssi)
bss->RSSI = bss_info_le->RSSI;
} else if ((bss->flags & BRCMF_BSS_RSSI_ON_CHANNEL) &&
(bss_info_le->flags & BRCMF_BSS_RSSI_ON_CHANNEL) == 0) {
/* preserve the on-channel rssi measurement
* if the new measurement is off channel
*/
bss->RSSI = bss_info_le->RSSI;
bss->flags |= BRCMF_BSS_RSSI_ON_CHANNEL;
}
return 1;
}
return 0;
}
static s32
brcmf_cfg80211_escan_handler(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 status;
struct brcmf_escan_result_le *escan_result_le;
struct brcmf_bss_info_le *bss_info_le;
struct brcmf_bss_info_le *bss = NULL;
u32 bi_length;
struct brcmf_scan_results *list;
u32 i;
bool aborted;
status = e->status;
if (status == BRCMF_E_STATUS_ABORT)
goto exit;
if (!test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
brcmf_err("scan not ready, bsscfgidx=%d\n", ifp->bsscfgidx);
return -EPERM;
}
if (status == BRCMF_E_STATUS_PARTIAL) {
brcmf_dbg(SCAN, "ESCAN Partial result\n");
escan_result_le = (struct brcmf_escan_result_le *) data;
if (!escan_result_le) {
brcmf_err("Invalid escan result (NULL pointer)\n");
goto exit;
}
if (le16_to_cpu(escan_result_le->bss_count) != 1) {
brcmf_err("Invalid bss_count %d: ignoring\n",
escan_result_le->bss_count);
goto exit;
}
bss_info_le = &escan_result_le->bss_info_le;
if (brcmf_p2p_scan_finding_common_channel(cfg, bss_info_le))
goto exit;
if (!cfg->int_escan_map && !cfg->scan_request) {
brcmf_dbg(SCAN, "result without cfg80211 request\n");
goto exit;
}
bi_length = le32_to_cpu(bss_info_le->length);
if (bi_length != (le32_to_cpu(escan_result_le->buflen) -
WL_ESCAN_RESULTS_FIXED_SIZE)) {
brcmf_err("Invalid bss_info length %d: ignoring\n",
bi_length);
goto exit;
}
if (!(cfg_to_wiphy(cfg)->interface_modes &
BIT(NL80211_IFTYPE_ADHOC))) {
if (le16_to_cpu(bss_info_le->capability) &
WLAN_CAPABILITY_IBSS) {
brcmf_err("Ignoring IBSS result\n");
goto exit;
}
}
list = (struct brcmf_scan_results *)
cfg->escan_info.escan_buf;
if (bi_length > BRCMF_ESCAN_BUF_SIZE - list->buflen) {
brcmf_err("Buffer is too small: ignoring\n");
goto exit;
}
for (i = 0; i < list->count; i++) {
bss = bss ? (struct brcmf_bss_info_le *)
((unsigned char *)bss +
le32_to_cpu(bss->length)) : list->bss_info_le;
if (brcmf_compare_update_same_bss(cfg, bss,
bss_info_le))
goto exit;
}
memcpy(&cfg->escan_info.escan_buf[list->buflen], bss_info_le,
bi_length);
list->version = le32_to_cpu(bss_info_le->version);
list->buflen += bi_length;
list->count++;
} else {
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
if (brcmf_p2p_scan_finding_common_channel(cfg, NULL))
goto exit;
if (cfg->int_escan_map || cfg->scan_request) {
brcmf_inform_bss(cfg);
aborted = status != BRCMF_E_STATUS_SUCCESS;
brcmf_notify_escan_complete(cfg, ifp, aborted, false);
} else
brcmf_dbg(SCAN, "Ignored scan complete result 0x%x\n",
status);
}
exit:
return 0;
}
static void brcmf_init_escan(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_ESCAN_RESULT,
brcmf_cfg80211_escan_handler);
cfg->escan_info.escan_state = WL_ESCAN_STATE_IDLE;
/* Init scan_timeout timer */
init_timer(&cfg->escan_timeout);
cfg->escan_timeout.data = (unsigned long) cfg;
cfg->escan_timeout.function = brcmf_escan_timeout;
INIT_WORK(&cfg->escan_timeout_work,
brcmf_cfg80211_escan_timeout_worker);
}
static struct cfg80211_scan_request *
brcmf_alloc_internal_escan_request(struct wiphy *wiphy, u32 n_netinfo) {
struct cfg80211_scan_request *req;
size_t req_size;
req_size = sizeof(*req) +
n_netinfo * sizeof(req->channels[0]) +
n_netinfo * sizeof(*req->ssids);
req = kzalloc(req_size, GFP_KERNEL);
if (req) {
req->wiphy = wiphy;
req->ssids = (void *)(&req->channels[0]) +
n_netinfo * sizeof(req->channels[0]);
}
return req;
}
static int brcmf_internal_escan_add_info(struct cfg80211_scan_request *req,
u8 *ssid, u8 ssid_len, u8 channel)
{
struct ieee80211_channel *chan;
enum nl80211_band band;
int freq, i;
if (channel <= CH_MAX_2G_CHANNEL)
band = NL80211_BAND_2GHZ;
else
band = NL80211_BAND_5GHZ;
freq = ieee80211_channel_to_frequency(channel, band);
if (!freq)
return -EINVAL;
chan = ieee80211_get_channel(req->wiphy, freq);
if (!chan)
return -EINVAL;
for (i = 0; i < req->n_channels; i++) {
if (req->channels[i] == chan)
break;
}
if (i == req->n_channels)
req->channels[req->n_channels++] = chan;
for (i = 0; i < req->n_ssids; i++) {
if (req->ssids[i].ssid_len == ssid_len &&
!memcmp(req->ssids[i].ssid, ssid, ssid_len))
break;
}
if (i == req->n_ssids) {
memcpy(req->ssids[req->n_ssids].ssid, ssid, ssid_len);
req->ssids[req->n_ssids++].ssid_len = ssid_len;
}
return 0;
}
static int brcmf_start_internal_escan(struct brcmf_if *ifp, u32 fwmap,
struct cfg80211_scan_request *request)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
int err;
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status)) {
if (cfg->int_escan_map)
brcmf_dbg(SCAN, "aborting internal scan: map=%u\n",
cfg->int_escan_map);
/* Abort any on-going scan */
brcmf_abort_scanning(cfg);
}
brcmf_dbg(SCAN, "start internal scan: map=%u\n", fwmap);
set_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
cfg->escan_info.run = brcmf_run_escan;
err = brcmf_do_escan(ifp, request);
if (err) {
clear_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status);
return err;
}
cfg->int_escan_map = fwmap;
return 0;
}
static struct brcmf_pno_net_info_le *
brcmf_get_netinfo_array(struct brcmf_pno_scanresults_le *pfn_v1)
{
struct brcmf_pno_scanresults_v2_le *pfn_v2;
struct brcmf_pno_net_info_le *netinfo;
switch (pfn_v1->version) {
default:
WARN_ON(1);
/* fall-thru */
case cpu_to_le32(1):
netinfo = (struct brcmf_pno_net_info_le *)(pfn_v1 + 1);
break;
case cpu_to_le32(2):
pfn_v2 = (struct brcmf_pno_scanresults_v2_le *)pfn_v1;
netinfo = (struct brcmf_pno_net_info_le *)(pfn_v2 + 1);
break;
}
return netinfo;
}
/* PFN result doesn't have all the info which are required by the supplicant
* (For e.g IEs) Do a target Escan so that sched scan results are reported
* via wl_inform_single_bss in the required format. Escan does require the
* scan request in the form of cfg80211_scan_request. For timebeing, create
* cfg80211_scan_request one out of the received PNO event.
*/
static s32
brcmf_notify_sched_scan_results(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_net_info_le *netinfo, *netinfo_start;
struct cfg80211_scan_request *request = NULL;
struct wiphy *wiphy = cfg_to_wiphy(cfg);
int i, err = 0;
struct brcmf_pno_scanresults_le *pfn_result;
u32 bucket_map;
u32 result_count;
u32 status;
u32 datalen;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Do Nothing\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
result_count = le32_to_cpu(pfn_result->count);
status = le32_to_cpu(pfn_result->status);
/* PFN event is limited to fit 512 bytes so we may get
* multiple NET_FOUND events. For now place a warning here.
*/
WARN_ON(status != BRCMF_PNO_SCAN_COMPLETE);
brcmf_dbg(SCAN, "PFN NET FOUND event. count: %d\n", result_count);
if (!result_count) {
brcmf_err("FALSE PNO Event. (pfn_count == 0)\n");
goto out_err;
}
netinfo_start = brcmf_get_netinfo_array(pfn_result);
datalen = e->datalen - ((void *)netinfo_start - (void *)pfn_result);
if (datalen < result_count * sizeof(*netinfo)) {
brcmf_err("insufficient event data\n");
goto out_err;
}
request = brcmf_alloc_internal_escan_request(wiphy,
result_count);
if (!request) {
err = -ENOMEM;
goto out_err;
}
bucket_map = 0;
for (i = 0; i < result_count; i++) {
netinfo = &netinfo_start[i];
if (netinfo->SSID_len > IEEE80211_MAX_SSID_LEN)
netinfo->SSID_len = IEEE80211_MAX_SSID_LEN;
brcmf_dbg(SCAN, "SSID:%.32s Channel:%d\n",
netinfo->SSID, netinfo->channel);
bucket_map |= brcmf_pno_get_bucket_map(cfg->pno, netinfo);
err = brcmf_internal_escan_add_info(request,
netinfo->SSID,
netinfo->SSID_len,
netinfo->channel);
if (err)
goto out_err;
}
if (!bucket_map)
goto free_req;
err = brcmf_start_internal_escan(ifp, bucket_map, request);
if (!err)
goto free_req;
out_err:
cfg80211_sched_scan_stopped(wiphy, 0);
free_req:
kfree(request);
return err;
}
static int
brcmf_cfg80211_sched_scan_start(struct wiphy *wiphy,
struct net_device *ndev,
struct cfg80211_sched_scan_request *req)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
brcmf_dbg(SCAN, "Enter: n_match_sets=%d n_ssids=%d\n",
req->n_match_sets, req->n_ssids);
if (test_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status)) {
brcmf_err("Scanning suppressed: status=%lu\n",
cfg->scan_status);
return -EAGAIN;
}
if (req->n_match_sets <= 0) {
brcmf_dbg(SCAN, "invalid number of matchsets specified: %d\n",
req->n_match_sets);
return -EINVAL;
}
return brcmf_pno_start_sched_scan(ifp, req);
}
static int brcmf_cfg80211_sched_scan_stop(struct wiphy *wiphy,
struct net_device *ndev, u64 reqid)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(SCAN, "enter\n");
brcmf_pno_stop_sched_scan(ifp, reqid);
if (cfg->int_escan_map)
brcmf_notify_escan_complete(cfg, ifp, true, true);
return 0;
}
static __always_inline void brcmf_delay(u32 ms)
{
if (ms < 1000 / HZ) {
cond_resched();
mdelay(ms);
} else {
msleep(ms);
}
}
static s32 brcmf_config_wowl_pattern(struct brcmf_if *ifp, u8 cmd[4],
u8 *pattern, u32 patternsize, u8 *mask,
u32 packet_offset)
{
struct brcmf_fil_wowl_pattern_le *filter;
u32 masksize;
u32 patternoffset;
u8 *buf;
u32 bufsize;
s32 ret;
masksize = (patternsize + 7) / 8;
patternoffset = sizeof(*filter) - sizeof(filter->cmd) + masksize;
bufsize = sizeof(*filter) + patternsize + masksize;
buf = kzalloc(bufsize, GFP_KERNEL);
if (!buf)
return -ENOMEM;
filter = (struct brcmf_fil_wowl_pattern_le *)buf;
memcpy(filter->cmd, cmd, 4);
filter->masksize = cpu_to_le32(masksize);
filter->offset = cpu_to_le32(packet_offset);
filter->patternoffset = cpu_to_le32(patternoffset);
filter->patternsize = cpu_to_le32(patternsize);
filter->type = cpu_to_le32(BRCMF_WOWL_PATTERN_TYPE_BITMAP);
if ((mask) && (masksize))
memcpy(buf + sizeof(*filter), mask, masksize);
if ((pattern) && (patternsize))
memcpy(buf + sizeof(*filter) + masksize, pattern, patternsize);
ret = brcmf_fil_iovar_data_set(ifp, "wowl_pattern", buf, bufsize);
kfree(buf);
return ret;
}
static s32
brcmf_wowl_nd_results(struct brcmf_if *ifp, const struct brcmf_event_msg *e,
void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_pno_scanresults_le *pfn_result;
struct brcmf_pno_net_info_le *netinfo;
brcmf_dbg(SCAN, "Enter\n");
if (e->datalen < (sizeof(*pfn_result) + sizeof(*netinfo))) {
brcmf_dbg(SCAN, "Event data to small. Ignore\n");
return 0;
}
pfn_result = (struct brcmf_pno_scanresults_le *)data;
if (e->event_code == BRCMF_E_PFN_NET_LOST) {
brcmf_dbg(SCAN, "PFN NET LOST event. Ignore\n");
return 0;
}
if (le32_to_cpu(pfn_result->count) < 1) {
brcmf_err("Invalid result count, expected 1 (%d)\n",
le32_to_cpu(pfn_result->count));
return -EINVAL;
}
netinfo = brcmf_get_netinfo_array(pfn_result);
memcpy(cfg->wowl.nd->ssid.ssid, netinfo->SSID, netinfo->SSID_len);
cfg->wowl.nd->ssid.ssid_len = netinfo->SSID_len;
cfg->wowl.nd->n_channels = 1;
cfg->wowl.nd->channels[0] =
ieee80211_channel_to_frequency(netinfo->channel,
netinfo->channel <= CH_MAX_2G_CHANNEL ?
NL80211_BAND_2GHZ : NL80211_BAND_5GHZ);
cfg->wowl.nd_info->n_matches = 1;
cfg->wowl.nd_info->matches[0] = cfg->wowl.nd;
/* Inform (the resume task) that the net detect information was recvd */
cfg->wowl.nd_data_completed = true;
wake_up(&cfg->wowl.nd_data_wait);
return 0;
}
#ifdef CONFIG_PM
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_wowl_wakeind_le wake_ind_le;
struct cfg80211_wowlan_wakeup wakeup_data;
struct cfg80211_wowlan_wakeup *wakeup;
u32 wakeind;
s32 err;
int timeout;
err = brcmf_fil_iovar_data_get(ifp, "wowl_wakeind", &wake_ind_le,
sizeof(wake_ind_le));
if (err) {
brcmf_err("Get wowl_wakeind failed, err = %d\n", err);
return;
}
wakeind = le32_to_cpu(wake_ind_le.ucode_wakeind);
if (wakeind & (BRCMF_WOWL_MAGIC | BRCMF_WOWL_DIS | BRCMF_WOWL_BCN |
BRCMF_WOWL_RETR | BRCMF_WOWL_NET |
BRCMF_WOWL_PFN_FOUND)) {
wakeup = &wakeup_data;
memset(&wakeup_data, 0, sizeof(wakeup_data));
wakeup_data.pattern_idx = -1;
if (wakeind & BRCMF_WOWL_MAGIC) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_MAGIC\n");
wakeup_data.magic_pkt = true;
}
if (wakeind & BRCMF_WOWL_DIS) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_DIS\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_BCN) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_BCN\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_RETR) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_RETR\n");
wakeup_data.disconnect = true;
}
if (wakeind & BRCMF_WOWL_NET) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_NET\n");
/* For now always map to pattern 0, no API to get
* correct information available at the moment.
*/
wakeup_data.pattern_idx = 0;
}
if (wakeind & BRCMF_WOWL_PFN_FOUND) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_PFN_FOUND\n");
timeout = wait_event_timeout(cfg->wowl.nd_data_wait,
cfg->wowl.nd_data_completed,
BRCMF_ND_INFO_TIMEOUT);
if (!timeout)
brcmf_err("No result for wowl net detect\n");
else
wakeup_data.net_detect = cfg->wowl.nd_info;
}
if (wakeind & BRCMF_WOWL_GTK_FAILURE) {
brcmf_dbg(INFO, "WOWL Wake indicator: BRCMF_WOWL_GTK_FAILURE\n");
wakeup_data.gtk_rekey_failure = true;
}
} else {
wakeup = NULL;
}
cfg80211_report_wowlan_wakeup(&ifp->vif->wdev, wakeup, GFP_KERNEL);
}
#else
static void brcmf_report_wowl_wakeind(struct wiphy *wiphy, struct brcmf_if *ifp)
{
}
#endif /* CONFIG_PM */
static s32 brcmf_cfg80211_resume(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
brcmf_dbg(TRACE, "Enter\n");
if (cfg->wowl.active) {
brcmf_report_wowl_wakeind(wiphy, ifp);
brcmf_fil_iovar_int_set(ifp, "wowl_clear", 0);
brcmf_config_wowl_pattern(ifp, "clr", NULL, 0, NULL, 0);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, true);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM,
cfg->wowl.pre_pmmode);
cfg->wowl.active = false;
if (cfg->wowl.nd_enabled) {
brcmf_cfg80211_sched_scan_stop(cfg->wiphy, ifp->ndev, 0);
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
cfg->wowl.nd_enabled = false;
}
}
return 0;
}
static void brcmf_configure_wowl(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp,
struct cfg80211_wowlan *wowl)
{
u32 wowl_config;
struct brcmf_wowl_wakeind_le wowl_wakeind;
u32 i;
brcmf_dbg(TRACE, "Suspend, wowl config.\n");
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ARP_ND))
brcmf_configure_arp_nd_offload(ifp, false);
brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_PM, &cfg->wowl.pre_pmmode);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, PM_MAX);
wowl_config = 0;
if (wowl->disconnect)
wowl_config = BRCMF_WOWL_DIS | BRCMF_WOWL_BCN | BRCMF_WOWL_RETR;
if (wowl->magic_pkt)
wowl_config |= BRCMF_WOWL_MAGIC;
if ((wowl->patterns) && (wowl->n_patterns)) {
wowl_config |= BRCMF_WOWL_NET;
for (i = 0; i < wowl->n_patterns; i++) {
brcmf_config_wowl_pattern(ifp, "add",
(u8 *)wowl->patterns[i].pattern,
wowl->patterns[i].pattern_len,
(u8 *)wowl->patterns[i].mask,
wowl->patterns[i].pkt_offset);
}
}
if (wowl->nd_config) {
brcmf_cfg80211_sched_scan_start(cfg->wiphy, ifp->ndev,
wowl->nd_config);
wowl_config |= BRCMF_WOWL_PFN_FOUND;
cfg->wowl.nd_data_completed = false;
cfg->wowl.nd_enabled = true;
/* Now reroute the event for PFN to the wowl function. */
brcmf_fweh_unregister(cfg->pub, BRCMF_E_PFN_NET_FOUND);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_wowl_nd_results);
}
if (wowl->gtk_rekey_failure)
wowl_config |= BRCMF_WOWL_GTK_FAILURE;
if (!test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
wowl_config |= BRCMF_WOWL_UNASSOC;
memcpy(&wowl_wakeind, "clear", 6);
brcmf_fil_iovar_data_set(ifp, "wowl_wakeind", &wowl_wakeind,
sizeof(wowl_wakeind));
brcmf_fil_iovar_int_set(ifp, "wowl", wowl_config);
brcmf_fil_iovar_int_set(ifp, "wowl_activate", 1);
brcmf_bus_wowl_config(cfg->pub->bus_if, true);
cfg->wowl.active = true;
}
static s32 brcmf_cfg80211_suspend(struct wiphy *wiphy,
struct cfg80211_wowlan *wowl)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = cfg_to_ndev(cfg);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter\n");
/* if the primary net_device is not READY there is nothing
* we can do but pray resume goes smoothly.
*/
if (!check_vif_up(ifp->vif))
goto exit;
/* Stop scheduled scan */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO))
brcmf_cfg80211_sched_scan_stop(wiphy, ndev, 0);
/* end any scanning */
if (test_bit(BRCMF_SCAN_STATUS_BUSY, &cfg->scan_status))
brcmf_abort_scanning(cfg);
if (wowl == NULL) {
brcmf_bus_wowl_config(cfg->pub->bus_if, false);
list_for_each_entry(vif, &cfg->vif_list, list) {
if (!test_bit(BRCMF_VIF_STATUS_READY, &vif->sme_state))
continue;
/* While going to suspend if associated with AP
* disassociate from AP to save power while system is
* in suspended state
*/
brcmf_link_down(vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
* generated due to DISASSOC call to the fw to keep
* the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
/* Configure MPC */
brcmf_set_mpc(ifp, 1);
} else {
/* Configure WOWL paramaters */
brcmf_configure_wowl(cfg, ifp, wowl);
}
exit:
brcmf_dbg(TRACE, "Exit\n");
/* clear any scanning activity */
cfg->scan_status = 0;
return 0;
}
static __used s32
brcmf_update_pmklist(struct brcmf_cfg80211_info *cfg, struct brcmf_if *ifp)
{
struct brcmf_pmk_list_le *pmk_list;
int i;
u32 npmk;
s32 err;
pmk_list = &cfg->pmk_list;
npmk = le32_to_cpu(pmk_list->npmk);
brcmf_dbg(CONN, "No of elements %d\n", npmk);
for (i = 0; i < npmk; i++)
brcmf_dbg(CONN, "PMK[%d]: %pM\n", i, &pmk_list->pmk[i].bssid);
err = brcmf_fil_iovar_data_set(ifp, "pmkid_info", pmk_list,
sizeof(*pmk_list));
return err;
}
static s32
brcmf_cfg80211_set_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(pmksa->bssid, pmk[i].bssid, ETH_ALEN))
break;
if (i < BRCMF_MAXPMKID) {
memcpy(pmk[i].bssid, pmksa->bssid, ETH_ALEN);
memcpy(pmk[i].pmkid, pmksa->pmkid, WLAN_PMKID_LEN);
if (i == npmk) {
npmk++;
cfg->pmk_list.npmk = cpu_to_le32(npmk);
}
} else {
brcmf_err("Too many PMKSA entries cached %d\n", npmk);
return -EINVAL;
}
brcmf_dbg(CONN, "set_pmksa - PMK bssid: %pM =\n", pmk[npmk].bssid);
for (i = 0; i < WLAN_PMKID_LEN; i += 4)
brcmf_dbg(CONN, "%02x %02x %02x %02x\n", pmk[npmk].pmkid[i],
pmk[npmk].pmkid[i + 1], pmk[npmk].pmkid[i + 2],
pmk[npmk].pmkid[i + 3]);
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_del_pmksa(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_pmksa *pmksa)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_pmksa *pmk = &cfg->pmk_list.pmk[0];
s32 err;
u32 npmk, i;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
brcmf_dbg(CONN, "del_pmksa - PMK bssid = %pM\n", pmksa->bssid);
npmk = le32_to_cpu(cfg->pmk_list.npmk);
for (i = 0; i < npmk; i++)
if (!memcmp(pmksa->bssid, pmk[i].bssid, ETH_ALEN))
break;
if ((npmk > 0) && (i < npmk)) {
for (; i < (npmk - 1); i++) {
memcpy(&pmk[i].bssid, &pmk[i + 1].bssid, ETH_ALEN);
memcpy(&pmk[i].pmkid, &pmk[i + 1].pmkid,
WLAN_PMKID_LEN);
}
memset(&pmk[i], 0, sizeof(*pmk));
cfg->pmk_list.npmk = cpu_to_le32(npmk - 1);
} else {
brcmf_err("Cache entry not found\n");
return -EINVAL;
}
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_cfg80211_flush_pmksa(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
if (!check_vif_up(ifp->vif))
return -EIO;
memset(&cfg->pmk_list, 0, sizeof(cfg->pmk_list));
err = brcmf_update_pmklist(cfg, ifp);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32 brcmf_configure_opensecurity(struct brcmf_if *ifp)
{
s32 err;
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", 0);
if (err < 0) {
brcmf_err("auth error %d\n", err);
return err;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", 0);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
return err;
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", WPA_AUTH_NONE);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
return err;
}
return 0;
}
static bool brcmf_valid_wpa_oui(u8 *oui, bool is_rsn_ie)
{
if (is_rsn_ie)
return (memcmp(oui, RSN_OUI, TLV_OUI_LEN) == 0);
return (memcmp(oui, WPA_OUI, TLV_OUI_LEN) == 0);
}
static s32
brcmf_configure_wpaie(struct brcmf_if *ifp,
const struct brcmf_vs_tlv *wpa_ie,
bool is_rsn_ie)
{
u32 auth = 0; /* d11 open authentication */
u16 count;
s32 err = 0;
s32 len;
u32 i;
u32 wsec;
u32 pval = 0;
u32 gval = 0;
u32 wpa_auth = 0;
u32 offset;
u8 *data;
u16 rsn_cap;
u32 wme_bss_disable;
u32 mfp;
brcmf_dbg(TRACE, "Enter\n");
if (wpa_ie == NULL)
goto exit;
len = wpa_ie->len + TLV_HDR_LEN;
data = (u8 *)wpa_ie;
offset = TLV_HDR_LEN;
if (!is_rsn_ie)
offset += VS_IE_FIXED_HDR_LEN;
else
offset += WPA_IE_VERSION_LEN;
/* check for multicast cipher suite */
if (offset + WPA_IE_MIN_OUI_LEN > len) {
err = -EINVAL;
brcmf_err("no multicast cipher suite\n");
goto exit;
}
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
/* pick up multicast cipher */
switch (data[offset]) {
case WPA_CIPHER_NONE:
gval = 0;
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
gval = WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
gval = TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
gval = AES_ENABLED;
break;
default:
err = -EINVAL;
brcmf_err("Invalid multi cast cipher info\n");
goto exit;
}
offset++;
/* walk thru unicast cipher list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for unicast suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no unicast cipher suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case WPA_CIPHER_NONE:
break;
case WPA_CIPHER_WEP_40:
case WPA_CIPHER_WEP_104:
pval |= WEP_ENABLED;
break;
case WPA_CIPHER_TKIP:
pval |= TKIP_ENABLED;
break;
case WPA_CIPHER_AES_CCM:
pval |= AES_ENABLED;
break;
default:
brcmf_err("Invalid unicast security info\n");
}
offset++;
}
/* walk thru auth management suite list and pick up what we recognize */
count = data[offset] + (data[offset + 1] << 8);
offset += WPA_IE_SUITE_COUNT_LEN;
/* Check for auth key management suite(s) */
if (offset + (WPA_IE_MIN_OUI_LEN * count) > len) {
err = -EINVAL;
brcmf_err("no auth key mgmt suite\n");
goto exit;
}
for (i = 0; i < count; i++) {
if (!brcmf_valid_wpa_oui(&data[offset], is_rsn_ie)) {
err = -EINVAL;
brcmf_err("ivalid OUI\n");
goto exit;
}
offset += TLV_OUI_LEN;
switch (data[offset]) {
case RSN_AKM_NONE:
brcmf_dbg(TRACE, "RSN_AKM_NONE\n");
wpa_auth |= WPA_AUTH_NONE;
break;
case RSN_AKM_UNSPECIFIED:
brcmf_dbg(TRACE, "RSN_AKM_UNSPECIFIED\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_UNSPECIFIED) :
(wpa_auth |= WPA_AUTH_UNSPECIFIED);
break;
case RSN_AKM_PSK:
brcmf_dbg(TRACE, "RSN_AKM_PSK\n");
is_rsn_ie ? (wpa_auth |= WPA2_AUTH_PSK) :
(wpa_auth |= WPA_AUTH_PSK);
break;
case RSN_AKM_SHA256_PSK:
brcmf_dbg(TRACE, "RSN_AKM_MFP_PSK\n");
wpa_auth |= WPA2_AUTH_PSK_SHA256;
break;
case RSN_AKM_SHA256_1X:
brcmf_dbg(TRACE, "RSN_AKM_MFP_1X\n");
wpa_auth |= WPA2_AUTH_1X_SHA256;
break;
default:
brcmf_err("Invalid key mgmt info\n");
}
offset++;
}
mfp = BRCMF_MFP_NONE;
if (is_rsn_ie) {
wme_bss_disable = 1;
if ((offset + RSN_CAP_LEN) <= len) {
rsn_cap = data[offset] + (data[offset + 1] << 8);
if (rsn_cap & RSN_CAP_PTK_REPLAY_CNTR_MASK)
wme_bss_disable = 0;
if (rsn_cap & RSN_CAP_MFPR_MASK) {
brcmf_dbg(TRACE, "MFP Required\n");
mfp = BRCMF_MFP_REQUIRED;
/* Firmware only supports mfp required in
* combination with WPA2_AUTH_PSK_SHA256 or
* WPA2_AUTH_1X_SHA256.
*/
if (!(wpa_auth & (WPA2_AUTH_PSK_SHA256 |
WPA2_AUTH_1X_SHA256))) {
err = -EINVAL;
goto exit;
}
/* Firmware has requirement that WPA2_AUTH_PSK/
* WPA2_AUTH_UNSPECIFIED be set, if SHA256 OUI
* is to be included in the rsn ie.
*/
if (wpa_auth & WPA2_AUTH_PSK_SHA256)
wpa_auth |= WPA2_AUTH_PSK;
else if (wpa_auth & WPA2_AUTH_1X_SHA256)
wpa_auth |= WPA2_AUTH_UNSPECIFIED;
} else if (rsn_cap & RSN_CAP_MFPC_MASK) {
brcmf_dbg(TRACE, "MFP Capable\n");
mfp = BRCMF_MFP_CAPABLE;
}
}
offset += RSN_CAP_LEN;
/* set wme_bss_disable to sync RSN Capabilities */
err = brcmf_fil_bsscfg_int_set(ifp, "wme_bss_disable",
wme_bss_disable);
if (err < 0) {
brcmf_err("wme_bss_disable error %d\n", err);
goto exit;
}
/* Skip PMKID cnt as it is know to be 0 for AP. */
offset += RSN_PMKID_COUNT_LEN;
/* See if there is BIP wpa suite left for MFP */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP) &&
((offset + WPA_IE_MIN_OUI_LEN) <= len)) {
err = brcmf_fil_bsscfg_data_set(ifp, "bip",
&data[offset],
WPA_IE_MIN_OUI_LEN);
if (err < 0) {
brcmf_err("bip error %d\n", err);
goto exit;
}
}
}
/* FOR WPS , set SES_OW_ENABLED */
wsec = (pval | gval | SES_OW_ENABLED);
/* set auth */
err = brcmf_fil_bsscfg_int_set(ifp, "auth", auth);
if (err < 0) {
brcmf_err("auth error %d\n", err);
goto exit;
}
/* set wsec */
err = brcmf_fil_bsscfg_int_set(ifp, "wsec", wsec);
if (err < 0) {
brcmf_err("wsec error %d\n", err);
goto exit;
}
/* Configure MFP, this needs to go after wsec otherwise the wsec command
* will overwrite the values set by MFP
*/
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP)) {
err = brcmf_fil_bsscfg_int_set(ifp, "mfp", mfp);
if (err < 0) {
brcmf_err("mfp error %d\n", err);
goto exit;
}
}
/* set upper-layer auth */
err = brcmf_fil_bsscfg_int_set(ifp, "wpa_auth", wpa_auth);
if (err < 0) {
brcmf_err("wpa_auth error %d\n", err);
goto exit;
}
exit:
return err;
}
static s32
brcmf_parse_vndr_ies(const u8 *vndr_ie_buf, u32 vndr_ie_len,
struct parsed_vndr_ies *vndr_ies)
{
struct brcmf_vs_tlv *vndrie;
struct brcmf_tlv *ie;
struct parsed_vndr_ie_info *parsed_info;
s32 remaining_len;
remaining_len = (s32)vndr_ie_len;
memset(vndr_ies, 0, sizeof(*vndr_ies));
ie = (struct brcmf_tlv *)vndr_ie_buf;
while (ie) {
if (ie->id != WLAN_EID_VENDOR_SPECIFIC)
goto next;
vndrie = (struct brcmf_vs_tlv *)ie;
/* len should be bigger than OUI length + one */
if (vndrie->len < (VS_IE_FIXED_HDR_LEN - TLV_HDR_LEN + 1)) {
brcmf_err("invalid vndr ie. length is too small %d\n",
vndrie->len);
goto next;
}
/* if wpa or wme ie, do not add ie */
if (!memcmp(vndrie->oui, (u8 *)WPA_OUI, TLV_OUI_LEN) &&
((vndrie->oui_type == WPA_OUI_TYPE) ||
(vndrie->oui_type == WME_OUI_TYPE))) {
brcmf_dbg(TRACE, "Found WPA/WME oui. Do not add it\n");
goto next;
}
parsed_info = &vndr_ies->ie_info[vndr_ies->count];
/* save vndr ie information */
parsed_info->ie_ptr = (char *)vndrie;
parsed_info->ie_len = vndrie->len + TLV_HDR_LEN;
memcpy(&parsed_info->vndrie, vndrie, sizeof(*vndrie));
vndr_ies->count++;
brcmf_dbg(TRACE, "** OUI %02x %02x %02x, type 0x%02x\n",
parsed_info->vndrie.oui[0],
parsed_info->vndrie.oui[1],
parsed_info->vndrie.oui[2],
parsed_info->vndrie.oui_type);
if (vndr_ies->count >= VNDR_IE_PARSE_LIMIT)
break;
next:
remaining_len -= (ie->len + TLV_HDR_LEN);
if (remaining_len <= TLV_HDR_LEN)
ie = NULL;
else
ie = (struct brcmf_tlv *)(((u8 *)ie) + ie->len +
TLV_HDR_LEN);
}
return 0;
}
static u32
brcmf_vndr_ie(u8 *iebuf, s32 pktflag, u8 *ie_ptr, u32 ie_len, s8 *add_del_cmd)
{
strncpy(iebuf, add_del_cmd, VNDR_IE_CMD_LEN - 1);
iebuf[VNDR_IE_CMD_LEN - 1] = '\0';
put_unaligned_le32(1, &iebuf[VNDR_IE_COUNT_OFFSET]);
put_unaligned_le32(pktflag, &iebuf[VNDR_IE_PKTFLAG_OFFSET]);
memcpy(&iebuf[VNDR_IE_VSIE_OFFSET], ie_ptr, ie_len);
return ie_len + VNDR_IE_HDR_SIZE;
}
s32 brcmf_vif_set_mgmt_ie(struct brcmf_cfg80211_vif *vif, s32 pktflag,
const u8 *vndr_ie_buf, u32 vndr_ie_len)
{
struct brcmf_if *ifp;
struct vif_saved_ie *saved_ie;
s32 err = 0;
u8 *iovar_ie_buf;
u8 *curr_ie_buf;
u8 *mgmt_ie_buf = NULL;
int mgmt_ie_buf_len;
u32 *mgmt_ie_len;
u32 del_add_ie_buf_len = 0;
u32 total_ie_buf_len = 0;
u32 parsed_ie_buf_len = 0;
struct parsed_vndr_ies old_vndr_ies;
struct parsed_vndr_ies new_vndr_ies;
struct parsed_vndr_ie_info *vndrie_info;
s32 i;
u8 *ptr;
int remained_buf_len;
if (!vif)
return -ENODEV;
ifp = vif->ifp;
saved_ie = &vif->saved_ie;
brcmf_dbg(TRACE, "bsscfgidx %d, pktflag : 0x%02X\n", ifp->bsscfgidx,
pktflag);
iovar_ie_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!iovar_ie_buf)
return -ENOMEM;
curr_ie_buf = iovar_ie_buf;
switch (pktflag) {
case BRCMF_VNDR_IE_PRBREQ_FLAG:
mgmt_ie_buf = saved_ie->probe_req_ie;
mgmt_ie_len = &saved_ie->probe_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_req_ie);
break;
case BRCMF_VNDR_IE_PRBRSP_FLAG:
mgmt_ie_buf = saved_ie->probe_res_ie;
mgmt_ie_len = &saved_ie->probe_res_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->probe_res_ie);
break;
case BRCMF_VNDR_IE_BEACON_FLAG:
mgmt_ie_buf = saved_ie->beacon_ie;
mgmt_ie_len = &saved_ie->beacon_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->beacon_ie);
break;
case BRCMF_VNDR_IE_ASSOCREQ_FLAG:
mgmt_ie_buf = saved_ie->assoc_req_ie;
mgmt_ie_len = &saved_ie->assoc_req_ie_len;
mgmt_ie_buf_len = sizeof(saved_ie->assoc_req_ie);
break;
default:
err = -EPERM;
brcmf_err("not suitable type\n");
goto exit;
}
if (vndr_ie_len > mgmt_ie_buf_len) {
err = -ENOMEM;
brcmf_err("extra IE size too big\n");
goto exit;
}
/* parse and save new vndr_ie in curr_ie_buff before comparing it */
if (vndr_ie_buf && vndr_ie_len && curr_ie_buf) {
ptr = curr_ie_buf;
brcmf_parse_vndr_ies(vndr_ie_buf, vndr_ie_len, &new_vndr_ies);
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
memcpy(ptr + parsed_ie_buf_len, vndrie_info->ie_ptr,
vndrie_info->ie_len);
parsed_ie_buf_len += vndrie_info->ie_len;
}
}
if (mgmt_ie_buf && *mgmt_ie_len) {
if (parsed_ie_buf_len && (parsed_ie_buf_len == *mgmt_ie_len) &&
(memcmp(mgmt_ie_buf, curr_ie_buf,
parsed_ie_buf_len) == 0)) {
brcmf_dbg(TRACE, "Previous mgmt IE equals to current IE\n");
goto exit;
}
/* parse old vndr_ie */
brcmf_parse_vndr_ies(mgmt_ie_buf, *mgmt_ie_len, &old_vndr_ies);
/* make a command to delete old ie */
for (i = 0; i < old_vndr_ies.count; i++) {
vndrie_info = &old_vndr_ies.ie_info[i];
brcmf_dbg(TRACE, "DEL ID : %d, Len: %d , OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"del");
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
*mgmt_ie_len = 0;
/* Add if there is any extra IE */
if (mgmt_ie_buf && parsed_ie_buf_len) {
ptr = mgmt_ie_buf;
remained_buf_len = mgmt_ie_buf_len;
/* make a command to add new ie */
for (i = 0; i < new_vndr_ies.count; i++) {
vndrie_info = &new_vndr_ies.ie_info[i];
/* verify remained buf size before copy data */
if (remained_buf_len < (vndrie_info->vndrie.len +
VNDR_IE_VSIE_OFFSET)) {
brcmf_err("no space in mgmt_ie_buf: len left %d",
remained_buf_len);
break;
}
remained_buf_len -= (vndrie_info->ie_len +
VNDR_IE_VSIE_OFFSET);
brcmf_dbg(TRACE, "ADDED ID : %d, Len: %d, OUI:%02x:%02x:%02x\n",
vndrie_info->vndrie.id,
vndrie_info->vndrie.len,
vndrie_info->vndrie.oui[0],
vndrie_info->vndrie.oui[1],
vndrie_info->vndrie.oui[2]);
del_add_ie_buf_len = brcmf_vndr_ie(curr_ie_buf, pktflag,
vndrie_info->ie_ptr,
vndrie_info->ie_len,
"add");
/* save the parsed IE in wl struct */
memcpy(ptr + (*mgmt_ie_len), vndrie_info->ie_ptr,
vndrie_info->ie_len);
*mgmt_ie_len += vndrie_info->ie_len;
curr_ie_buf += del_add_ie_buf_len;
total_ie_buf_len += del_add_ie_buf_len;
}
}
if (total_ie_buf_len) {
err = brcmf_fil_bsscfg_data_set(ifp, "vndr_ie", iovar_ie_buf,
total_ie_buf_len);
if (err)
brcmf_err("vndr ie set error : %d\n", err);
}
exit:
kfree(iovar_ie_buf);
return err;
}
s32 brcmf_vif_clear_mgmt_ies(struct brcmf_cfg80211_vif *vif)
{
s32 pktflags[] = {
BRCMF_VNDR_IE_PRBREQ_FLAG,
BRCMF_VNDR_IE_PRBRSP_FLAG,
BRCMF_VNDR_IE_BEACON_FLAG
};
int i;
for (i = 0; i < ARRAY_SIZE(pktflags); i++)
brcmf_vif_set_mgmt_ie(vif, pktflags[i], NULL, 0);
memset(&vif->saved_ie, 0, sizeof(vif->saved_ie));
return 0;
}
static s32
brcmf_config_ap_mgmt_ie(struct brcmf_cfg80211_vif *vif,
struct cfg80211_beacon_data *beacon)
{
s32 err;
/* Set Beacon IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_BEACON_FLAG,
beacon->tail, beacon->tail_len);
if (err) {
brcmf_err("Set Beacon IE Failed\n");
return err;
}
brcmf_dbg(TRACE, "Applied Vndr IEs for Beacon\n");
/* Set Probe Response IEs to FW */
err = brcmf_vif_set_mgmt_ie(vif, BRCMF_VNDR_IE_PRBRSP_FLAG,
beacon->proberesp_ies,
beacon->proberesp_ies_len);
if (err)
brcmf_err("Set Probe Resp IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Probe Resp\n");
return err;
}
static s32
brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_ap_settings *settings)
{
s32 ie_offset;
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_if *ifp = netdev_priv(ndev);
const struct brcmf_tlv *ssid_ie;
const struct brcmf_tlv *country_ie;
struct brcmf_ssid_le ssid_le;
s32 err = -EPERM;
const struct brcmf_tlv *rsn_ie;
const struct brcmf_vs_tlv *wpa_ie;
struct brcmf_join_params join_params;
enum nl80211_iftype dev_role;
struct brcmf_fil_bss_enable_le bss_enable;
u16 chanspec = chandef_to_chanspec(&cfg->d11inf, &settings->chandef);
bool mbss;
int is_11d;
bool supports_11d;
brcmf_dbg(TRACE, "ctrlchn=%d, center=%d, bw=%d, beacon_interval=%d, dtim_period=%d,\n",
settings->chandef.chan->hw_value,
settings->chandef.center_freq1, settings->chandef.width,
settings->beacon_interval, settings->dtim_period);
brcmf_dbg(TRACE, "ssid=%s(%zu), auth_type=%d, inactivity_timeout=%d\n",
settings->ssid, settings->ssid_len, settings->auth_type,
settings->inactivity_timeout);
dev_role = ifp->vif->wdev.iftype;
mbss = ifp->vif->mbss;
/* store current 11d setting */
if (brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_REGULATORY,
&ifp->vif->is_11d)) {
is_11d = supports_11d = false;
} else {
country_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len,
WLAN_EID_COUNTRY);
is_11d = country_ie ? 1 : 0;
supports_11d = true;
}
memset(&ssid_le, 0, sizeof(ssid_le));
if (settings->ssid == NULL || settings->ssid_len == 0) {
ie_offset = DOT11_MGMT_HDR_LEN + DOT11_BCN_PRB_FIXED_LEN;
ssid_ie = brcmf_parse_tlvs(
(u8 *)&settings->beacon.head[ie_offset],
settings->beacon.head_len - ie_offset,
WLAN_EID_SSID);
if (!ssid_ie || ssid_ie->len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);
ssid_le.SSID_len = cpu_to_le32(ssid_ie->len);
brcmf_dbg(TRACE, "SSID is (%s) in Head\n", ssid_le.SSID);
} else {
memcpy(ssid_le.SSID, settings->ssid, settings->ssid_len);
ssid_le.SSID_len = cpu_to_le32((u32)settings->ssid_len);
}
if (!mbss) {
brcmf_set_mpc(ifp, 0);
brcmf_configure_arp_nd_offload(ifp, false);
}
/* find the RSN_IE */
rsn_ie = brcmf_parse_tlvs((u8 *)settings->beacon.tail,
settings->beacon.tail_len, WLAN_EID_RSN);
/* find the WPA_IE */
wpa_ie = brcmf_find_wpaie((u8 *)settings->beacon.tail,
settings->beacon.tail_len);
if ((wpa_ie != NULL || rsn_ie != NULL)) {
brcmf_dbg(TRACE, "WPA(2) IE is found\n");
if (wpa_ie != NULL) {
/* WPA IE */
err = brcmf_configure_wpaie(ifp, wpa_ie, false);
if (err < 0)
goto exit;
} else {
struct brcmf_vs_tlv *tmp_ie;
tmp_ie = (struct brcmf_vs_tlv *)rsn_ie;
/* RSN IE */
err = brcmf_configure_wpaie(ifp, tmp_ie, true);
if (err < 0)
goto exit;
}
} else {
brcmf_dbg(TRACE, "No WPA(2) IEs found\n");
brcmf_configure_opensecurity(ifp);
}
/* Parameters shared by all radio interfaces */
if (!mbss) {
if ((supports_11d) && (is_11d != ifp->vif->is_11d)) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
is_11d);
if (err < 0) {
brcmf_err("Regulatory Set Error, %d\n", err);
goto exit;
}
}
if (settings->beacon_interval) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_BCNPRD,
settings->beacon_interval);
if (err < 0) {
brcmf_err("Beacon Interval Set Error, %d\n",
err);
goto exit;
}
}
if (settings->dtim_period) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_DTIMPRD,
settings->dtim_period);
if (err < 0) {
brcmf_err("DTIM Interval Set Error, %d\n", err);
goto exit;
}
}
if ((dev_role == NL80211_IFTYPE_AP) &&
((ifp->ifidx == 0) ||
!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_RSDB))) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0) {
brcmf_err("BRCMF_C_DOWN error %d\n", err);
goto exit;
}
brcmf_fil_iovar_int_set(ifp, "apsta", 0);
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_INFRA, 1);
if (err < 0) {
brcmf_err("SET INFRA error %d\n", err);
goto exit;
}
} else if (WARN_ON(supports_11d && (is_11d != ifp->vif->is_11d))) {
/* Multiple-BSS should use same 11d configuration */
err = -EINVAL;
goto exit;
}
/* Interface specific setup */
if (dev_role == NL80211_IFTYPE_AP) {
if ((brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS)) && (!mbss))
brcmf_fil_iovar_int_set(ifp, "mbss", 1);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 1);
if (err < 0) {
brcmf_err("setting AP mode failed %d\n", err);
goto exit;
}
if (!mbss) {
/* Firmware 10.x requires setting channel after enabling
* AP and before bringing interface up.
*/
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0) {
brcmf_err("BRCMF_C_UP error (%d)\n", err);
goto exit;
}
/* On DOWN the firmware removes the WEP keys, reconfigure
* them if they were set.
*/
brcmf_cfg80211_reconfigure_wep(ifp);
memset(&join_params, 0, sizeof(join_params));
/* join parameters starts with ssid */
memcpy(&join_params.ssid_le, &ssid_le, sizeof(ssid_le));
/* create softap */
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0) {
brcmf_err("SET SSID error (%d)\n", err);
goto exit;
}
if (settings->hidden_ssid) {
err = brcmf_fil_iovar_int_set(ifp, "closednet", 1);
if (err) {
brcmf_err("closednet error (%d)\n", err);
goto exit;
}
}
brcmf_dbg(TRACE, "AP mode configuration complete\n");
} else if (dev_role == NL80211_IFTYPE_P2P_GO) {
err = brcmf_fil_iovar_int_set(ifp, "chanspec", chanspec);
if (err < 0) {
brcmf_err("Set Channel failed: chspec=%d, %d\n",
chanspec, err);
goto exit;
}
err = brcmf_fil_bsscfg_data_set(ifp, "ssid", &ssid_le,
sizeof(ssid_le));
if (err < 0) {
brcmf_err("setting ssid failed %d\n", err);
goto exit;
}
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(1);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0) {
brcmf_err("bss_enable config failed %d\n", err);
goto exit;
}
brcmf_dbg(TRACE, "GO mode configuration complete\n");
} else {
WARN_ON(1);
}
brcmf_config_ap_mgmt_ie(ifp->vif, &settings->beacon);
set_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, true);
exit:
if ((err) && (!mbss)) {
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
}
return err;
}
static int brcmf_cfg80211_stop_ap(struct wiphy *wiphy, struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
struct brcmf_fil_bss_enable_le bss_enable;
struct brcmf_join_params join_params;
brcmf_dbg(TRACE, "Enter\n");
if (ifp->vif->wdev.iftype == NL80211_IFTYPE_AP) {
/* Due to most likely deauths outstanding we sleep */
/* first to make sure they get processed by fw. */
msleep(400);
if (ifp->vif->mbss) {
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
return err;
}
/* First BSS doesn't get a full reset */
if (ifp->bsscfgidx == 0)
brcmf_fil_iovar_int_set(ifp, "closednet", 0);
memset(&join_params, 0, sizeof(join_params));
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SSID,
&join_params, sizeof(join_params));
if (err < 0)
brcmf_err("SET SSID error (%d)\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_DOWN, 1);
if (err < 0)
brcmf_err("BRCMF_C_DOWN error %d\n", err);
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_AP, 0);
if (err < 0)
brcmf_err("setting AP mode failed %d\n", err);
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS))
brcmf_fil_iovar_int_set(ifp, "mbss", 0);
brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_REGULATORY,
ifp->vif->is_11d);
/* Bring device back up so it can be used again */
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 1);
if (err < 0)
brcmf_err("BRCMF_C_UP error %d\n", err);
brcmf_vif_clear_mgmt_ies(ifp->vif);
} else {
bss_enable.bsscfgidx = cpu_to_le32(ifp->bsscfgidx);
bss_enable.enable = cpu_to_le32(0);
err = brcmf_fil_iovar_data_set(ifp, "bss", &bss_enable,
sizeof(bss_enable));
if (err < 0)
brcmf_err("bss_enable config failed %d\n", err);
}
brcmf_set_mpc(ifp, 1);
brcmf_configure_arp_nd_offload(ifp, true);
clear_bit(BRCMF_VIF_STATUS_AP_CREATED, &ifp->vif->sme_state);
brcmf_net_setcarrier(ifp, false);
return err;
}
static s32
brcmf_cfg80211_change_beacon(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_beacon_data *info)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter\n");
err = brcmf_config_ap_mgmt_ie(ifp->vif, info);
return err;
}
static int
brcmf_cfg80211_del_station(struct wiphy *wiphy, struct net_device *ndev,
struct station_del_parameters *params)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_scb_val_le scbval;
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
if (!params->mac)
return -EFAULT;
brcmf_dbg(TRACE, "Enter %pM\n", params->mac);
if (ifp->vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif)
ifp = cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif->ifp;
if (!check_vif_up(ifp->vif))
return -EIO;
memcpy(&scbval.ea, params->mac, ETH_ALEN);
scbval.val = cpu_to_le32(params->reason_code);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SCB_DEAUTHENTICATE_FOR_REASON,
&scbval, sizeof(scbval));
if (err)
brcmf_err("SCB_DEAUTHENTICATE_FOR_REASON failed %d\n", err);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static int
brcmf_cfg80211_change_station(struct wiphy *wiphy, struct net_device *ndev,
const u8 *mac, struct station_parameters *params)
{
struct brcmf_if *ifp = netdev_priv(ndev);
s32 err;
brcmf_dbg(TRACE, "Enter, MAC %pM, mask 0x%04x set 0x%04x\n", mac,
params->sta_flags_mask, params->sta_flags_set);
/* Ignore all 00 MAC */
if (is_zero_ether_addr(mac))
return 0;
if (!(params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)))
return 0;
if (params->sta_flags_set & BIT(NL80211_STA_FLAG_AUTHORIZED))
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_AUTHORIZE,
(void *)mac, ETH_ALEN);
else
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_SCB_DEAUTHORIZE,
(void *)mac, ETH_ALEN);
if (err < 0)
brcmf_err("Setting SCB (de-)authorize failed, %d\n", err);
return err;
}
static void
brcmf_cfg80211_mgmt_frame_register(struct wiphy *wiphy,
struct wireless_dev *wdev,
u16 frame_type, bool reg)
{
struct brcmf_cfg80211_vif *vif;
u16 mgmt_type;
brcmf_dbg(TRACE, "Enter, frame_type %04x, reg=%d\n", frame_type, reg);
mgmt_type = (frame_type & IEEE80211_FCTL_STYPE) >> 4;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (reg)
vif->mgmt_rx_reg |= BIT(mgmt_type);
else
vif->mgmt_rx_reg &= ~BIT(mgmt_type);
}
static int
brcmf_cfg80211_mgmt_tx(struct wiphy *wiphy, struct wireless_dev *wdev,
struct cfg80211_mgmt_tx_params *params, u64 *cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct ieee80211_channel *chan = params->chan;
const u8 *buf = params->buf;
size_t len = params->len;
const struct ieee80211_mgmt *mgmt;
struct brcmf_cfg80211_vif *vif;
s32 err = 0;
s32 ie_offset;
s32 ie_len;
struct brcmf_fil_action_frame_le *action_frame;
struct brcmf_fil_af_params_le *af_params;
bool ack;
s32 chan_nr;
u32 freq;
brcmf_dbg(TRACE, "Enter\n");
*cookie = 0;
mgmt = (const struct ieee80211_mgmt *)buf;
if (!ieee80211_is_mgmt(mgmt->frame_control)) {
brcmf_err("Driver only allows MGMT packet type\n");
return -EPERM;
}
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
if (ieee80211_is_probe_resp(mgmt->frame_control)) {
/* Right now the only reason to get a probe response */
/* is for p2p listen response or for p2p GO from */
/* wpa_supplicant. Unfortunately the probe is send */
/* on primary ndev, while dongle wants it on the p2p */
/* vif. Since this is only reason for a probe */
/* response to be sent, the vif is taken from cfg. */
/* If ever desired to send proberesp for non p2p */
/* response then data should be checked for */
/* "DIRECT-". Note in future supplicant will take */
/* dedicated p2p wdev to do this and then this 'hack'*/
/* is not needed anymore. */
ie_offset = DOT11_MGMT_HDR_LEN +
DOT11_BCN_PRB_FIXED_LEN;
ie_len = len - ie_offset;
if (vif == cfg->p2p.bss_idx[P2PAPI_BSSCFG_PRIMARY].vif)
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
err = brcmf_vif_set_mgmt_ie(vif,
BRCMF_VNDR_IE_PRBRSP_FLAG,
&buf[ie_offset],
ie_len);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, true,
GFP_KERNEL);
} else if (ieee80211_is_action(mgmt->frame_control)) {
if (len > BRCMF_FIL_ACTION_FRAME_SIZE + DOT11_MGMT_HDR_LEN) {
brcmf_err("invalid action frame length\n");
err = -EINVAL;
goto exit;
}
af_params = kzalloc(sizeof(*af_params), GFP_KERNEL);
if (af_params == NULL) {
brcmf_err("unable to allocate frame\n");
err = -ENOMEM;
goto exit;
}
action_frame = &af_params->action_frame;
/* Add the packet Id */
action_frame->packet_id = cpu_to_le32(*cookie);
/* Add BSSID */
memcpy(&action_frame->da[0], &mgmt->da[0], ETH_ALEN);
memcpy(&af_params->bssid[0], &mgmt->bssid[0], ETH_ALEN);
/* Add the length exepted for 802.11 header */
action_frame->len = cpu_to_le16(len - DOT11_MGMT_HDR_LEN);
/* Add the channel. Use the one specified as parameter if any or
* the current one (got from the firmware) otherwise
*/
if (chan)
freq = chan->center_freq;
else
brcmf_fil_cmd_int_get(vif->ifp, BRCMF_C_GET_CHANNEL,
&freq);
chan_nr = ieee80211_frequency_to_channel(freq);
af_params->channel = cpu_to_le32(chan_nr);
memcpy(action_frame->data, &buf[DOT11_MGMT_HDR_LEN],
le16_to_cpu(action_frame->len));
brcmf_dbg(TRACE, "Action frame, cookie=%lld, len=%d, freq=%d\n",
*cookie, le16_to_cpu(action_frame->len), freq);
ack = brcmf_p2p_send_action_frame(cfg, cfg_to_ndev(cfg),
af_params);
cfg80211_mgmt_tx_status(wdev, *cookie, buf, len, ack,
GFP_KERNEL);
kfree(af_params);
} else {
brcmf_dbg(TRACE, "Unhandled, fc=%04x!!\n", mgmt->frame_control);
brcmf_dbg_hex_dump(true, buf, len, "payload, len=%zu\n", len);
}
exit:
return err;
}
static int
brcmf_cfg80211_cancel_remain_on_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
u64 cookie)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
int err = 0;
brcmf_dbg(TRACE, "Enter p2p listen cancel\n");
vif = cfg->p2p.bss_idx[P2PAPI_BSSCFG_DEVICE].vif;
if (vif == NULL) {
brcmf_err("No p2p device available for probe response\n");
err = -ENODEV;
goto exit;
}
brcmf_p2p_cancel_remain_on_channel(vif->ifp);
exit:
return err;
}
static int brcmf_cfg80211_get_channel(struct wiphy *wiphy,
struct wireless_dev *wdev,
struct cfg80211_chan_def *chandef)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct net_device *ndev = wdev->netdev;
struct brcmf_if *ifp;
struct brcmu_chan ch;
enum nl80211_band band = 0;
enum nl80211_chan_width width = 0;
u32 chanspec;
int freq, err;
if (!ndev)
return -ENODEV;
ifp = netdev_priv(ndev);
err = brcmf_fil_iovar_int_get(ifp, "chanspec", &chanspec);
if (err) {
brcmf_err("chanspec failed (%d)\n", err);
return err;
}
ch.chspec = chanspec;
cfg->d11inf.decchspec(&ch);
switch (ch.band) {
case BRCMU_CHAN_BAND_2G:
band = NL80211_BAND_2GHZ;
break;
case BRCMU_CHAN_BAND_5G:
band = NL80211_BAND_5GHZ;
break;
}
switch (ch.bw) {
case BRCMU_CHAN_BW_80:
width = NL80211_CHAN_WIDTH_80;
break;
case BRCMU_CHAN_BW_40:
width = NL80211_CHAN_WIDTH_40;
break;
case BRCMU_CHAN_BW_20:
width = NL80211_CHAN_WIDTH_20;
break;
case BRCMU_CHAN_BW_80P80:
width = NL80211_CHAN_WIDTH_80P80;
break;
case BRCMU_CHAN_BW_160:
width = NL80211_CHAN_WIDTH_160;
break;
}
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band);
chandef->chan = ieee80211_get_channel(wiphy, freq);
chandef->width = width;
chandef->center_freq1 = ieee80211_channel_to_frequency(ch.chnum, band);
chandef->center_freq2 = 0;
return 0;
}
static int brcmf_cfg80211_crit_proto_start(struct wiphy *wiphy,
struct wireless_dev *wdev,
enum nl80211_crit_proto_id proto,
u16 duration)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
/* only DHCP support for now */
if (proto != NL80211_CRIT_PROTO_DHCP)
return -EINVAL;
/* suppress and abort scanning */
set_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
brcmf_abort_scanning(cfg);
return brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_DISABLED, duration);
}
static void brcmf_cfg80211_crit_proto_stop(struct wiphy *wiphy,
struct wireless_dev *wdev)
{
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct brcmf_cfg80211_vif *vif;
vif = container_of(wdev, struct brcmf_cfg80211_vif, wdev);
brcmf_btcoex_set_mode(vif, BRCMF_BTCOEX_ENABLED, 0);
clear_bit(BRCMF_SCAN_STATUS_SUPPRESS, &cfg->scan_status);
}
static s32
brcmf_notify_tdls_peer_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
switch (e->reason) {
case BRCMF_E_REASON_TDLS_PEER_DISCOVERED:
brcmf_dbg(TRACE, "TDLS Peer Discovered\n");
break;
case BRCMF_E_REASON_TDLS_PEER_CONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Connected\n");
brcmf_proto_add_tdls_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
case BRCMF_E_REASON_TDLS_PEER_DISCONNECTED:
brcmf_dbg(TRACE, "TDLS Peer Disconnected\n");
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
break;
}
return 0;
}
static int brcmf_convert_nl80211_tdls_oper(enum nl80211_tdls_operation oper)
{
int ret;
switch (oper) {
case NL80211_TDLS_DISCOVERY_REQ:
ret = BRCMF_TDLS_MANUAL_EP_DISCOVERY;
break;
case NL80211_TDLS_SETUP:
ret = BRCMF_TDLS_MANUAL_EP_CREATE;
break;
case NL80211_TDLS_TEARDOWN:
ret = BRCMF_TDLS_MANUAL_EP_DELETE;
break;
default:
brcmf_err("unsupported operation: %d\n", oper);
ret = -EOPNOTSUPP;
}
return ret;
}
static int brcmf_cfg80211_tdls_oper(struct wiphy *wiphy,
struct net_device *ndev, const u8 *peer,
enum nl80211_tdls_operation oper)
{
struct brcmf_if *ifp;
struct brcmf_tdls_iovar_le info;
int ret = 0;
ret = brcmf_convert_nl80211_tdls_oper(oper);
if (ret < 0)
return ret;
ifp = netdev_priv(ndev);
memset(&info, 0, sizeof(info));
info.mode = (u8)ret;
if (peer)
memcpy(info.ea, peer, ETH_ALEN);
ret = brcmf_fil_iovar_data_set(ifp, "tdls_endpoint",
&info, sizeof(info));
if (ret < 0)
brcmf_err("tdls_endpoint iovar failed: ret=%d\n", ret);
return ret;
}
static int
brcmf_cfg80211_update_conn_params(struct wiphy *wiphy,
struct net_device *ndev,
struct cfg80211_connect_params *sme,
u32 changed)
{
struct brcmf_if *ifp;
int err;
if (!(changed & UPDATE_ASSOC_IES))
return 0;
ifp = netdev_priv(ndev);
err = brcmf_vif_set_mgmt_ie(ifp->vif, BRCMF_VNDR_IE_ASSOCREQ_FLAG,
sme->ie, sme->ie_len);
if (err)
brcmf_err("Set Assoc REQ IE Failed\n");
else
brcmf_dbg(TRACE, "Applied Vndr IEs for Assoc request\n");
return err;
}
#ifdef CONFIG_PM
static int
brcmf_cfg80211_set_rekey_data(struct wiphy *wiphy, struct net_device *ndev,
struct cfg80211_gtk_rekey_data *gtk)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_gtk_keyinfo_le gtk_le;
int ret;
brcmf_dbg(TRACE, "Enter, bssidx=%d\n", ifp->bsscfgidx);
memcpy(gtk_le.kck, gtk->kck, sizeof(gtk_le.kck));
memcpy(gtk_le.kek, gtk->kek, sizeof(gtk_le.kek));
memcpy(gtk_le.replay_counter, gtk->replay_ctr,
sizeof(gtk_le.replay_counter));
ret = brcmf_fil_iovar_data_set(ifp, "gtk_key_info", >k_le,
sizeof(gtk_le));
if (ret < 0)
brcmf_err("gtk_key_info iovar failed: ret=%d\n", ret);
return ret;
}
#endif
static int brcmf_cfg80211_set_pmk(struct wiphy *wiphy, struct net_device *dev,
const struct cfg80211_pmk_conf *conf)
{
struct brcmf_if *ifp;
brcmf_dbg(TRACE, "enter\n");
/* expect using firmware supplicant for 1X */
ifp = netdev_priv(dev);
if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X))
return -EINVAL;
return brcmf_set_pmk(ifp, conf->pmk, conf->pmk_len);
}
static int brcmf_cfg80211_del_pmk(struct wiphy *wiphy, struct net_device *dev,
const u8 *aa)
{
struct brcmf_if *ifp;
brcmf_dbg(TRACE, "enter\n");
ifp = netdev_priv(dev);
if (WARN_ON(ifp->vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_1X))
return -EINVAL;
return brcmf_set_pmk(ifp, NULL, 0);
}
static struct cfg80211_ops brcmf_cfg80211_ops = {
.add_virtual_intf = brcmf_cfg80211_add_iface,
.del_virtual_intf = brcmf_cfg80211_del_iface,
.change_virtual_intf = brcmf_cfg80211_change_iface,
.scan = brcmf_cfg80211_scan,
.set_wiphy_params = brcmf_cfg80211_set_wiphy_params,
.join_ibss = brcmf_cfg80211_join_ibss,
.leave_ibss = brcmf_cfg80211_leave_ibss,
.get_station = brcmf_cfg80211_get_station,
.dump_station = brcmf_cfg80211_dump_station,
.set_tx_power = brcmf_cfg80211_set_tx_power,
.get_tx_power = brcmf_cfg80211_get_tx_power,
.add_key = brcmf_cfg80211_add_key,
.del_key = brcmf_cfg80211_del_key,
.get_key = brcmf_cfg80211_get_key,
.set_default_key = brcmf_cfg80211_config_default_key,
.set_default_mgmt_key = brcmf_cfg80211_config_default_mgmt_key,
.set_power_mgmt = brcmf_cfg80211_set_power_mgmt,
.connect = brcmf_cfg80211_connect,
.disconnect = brcmf_cfg80211_disconnect,
.suspend = brcmf_cfg80211_suspend,
.resume = brcmf_cfg80211_resume,
.set_pmksa = brcmf_cfg80211_set_pmksa,
.del_pmksa = brcmf_cfg80211_del_pmksa,
.flush_pmksa = brcmf_cfg80211_flush_pmksa,
.start_ap = brcmf_cfg80211_start_ap,
.stop_ap = brcmf_cfg80211_stop_ap,
.change_beacon = brcmf_cfg80211_change_beacon,
.del_station = brcmf_cfg80211_del_station,
.change_station = brcmf_cfg80211_change_station,
.sched_scan_start = brcmf_cfg80211_sched_scan_start,
.sched_scan_stop = brcmf_cfg80211_sched_scan_stop,
.mgmt_frame_register = brcmf_cfg80211_mgmt_frame_register,
.mgmt_tx = brcmf_cfg80211_mgmt_tx,
.remain_on_channel = brcmf_p2p_remain_on_channel,
.cancel_remain_on_channel = brcmf_cfg80211_cancel_remain_on_channel,
.get_channel = brcmf_cfg80211_get_channel,
.start_p2p_device = brcmf_p2p_start_device,
.stop_p2p_device = brcmf_p2p_stop_device,
.crit_proto_start = brcmf_cfg80211_crit_proto_start,
.crit_proto_stop = brcmf_cfg80211_crit_proto_stop,
.tdls_oper = brcmf_cfg80211_tdls_oper,
.update_connect_params = brcmf_cfg80211_update_conn_params,
.set_pmk = brcmf_cfg80211_set_pmk,
.del_pmk = brcmf_cfg80211_del_pmk,
};
struct brcmf_cfg80211_vif *brcmf_alloc_vif(struct brcmf_cfg80211_info *cfg,
enum nl80211_iftype type)
{
struct brcmf_cfg80211_vif *vif_walk;
struct brcmf_cfg80211_vif *vif;
bool mbss;
brcmf_dbg(TRACE, "allocating virtual interface (size=%zu)\n",
sizeof(*vif));
vif = kzalloc(sizeof(*vif), GFP_KERNEL);
if (!vif)
return ERR_PTR(-ENOMEM);
vif->wdev.wiphy = cfg->wiphy;
vif->wdev.iftype = type;
brcmf_init_prof(&vif->profile);
if (type == NL80211_IFTYPE_AP) {
mbss = false;
list_for_each_entry(vif_walk, &cfg->vif_list, list) {
if (vif_walk->wdev.iftype == NL80211_IFTYPE_AP) {
mbss = true;
break;
}
}
vif->mbss = mbss;
}
list_add_tail(&vif->list, &cfg->vif_list);
return vif;
}
void brcmf_free_vif(struct brcmf_cfg80211_vif *vif)
{
list_del(&vif->list);
kfree(vif);
}
void brcmf_cfg80211_free_netdev(struct net_device *ndev)
{
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
ifp = netdev_priv(ndev);
vif = ifp->vif;
if (vif)
brcmf_free_vif(vif);
}
static bool brcmf_is_linkup(struct brcmf_cfg80211_vif *vif,
const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (vif->profile.use_fwsup == BRCMF_PROFILE_FWSUP_PSK &&
event == BRCMF_E_PSK_SUP &&
status == BRCMF_E_STATUS_FWSUP_COMPLETED)
set_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state);
if (event == BRCMF_E_SET_SSID && status == BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing set ssid\n");
memcpy(vif->profile.bssid, e->addr, ETH_ALEN);
if (vif->profile.use_fwsup != BRCMF_PROFILE_FWSUP_PSK)
return true;
set_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state);
}
if (test_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state) &&
test_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state)) {
clear_bit(BRCMF_VIF_STATUS_EAP_SUCCESS, &vif->sme_state);
clear_bit(BRCMF_VIF_STATUS_ASSOC_SUCCESS, &vif->sme_state);
return true;
}
return false;
}
static bool brcmf_is_linkdown(const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u16 flags = e->flags;
if ((event == BRCMF_E_DEAUTH) || (event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DISASSOC_IND) ||
((event == BRCMF_E_LINK) && (!(flags & BRCMF_EVENT_MSG_LINK)))) {
brcmf_dbg(CONN, "Processing link down\n");
return true;
}
return false;
}
static bool brcmf_is_nonetwork(struct brcmf_cfg80211_info *cfg,
const struct brcmf_event_msg *e)
{
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_LINK && status == BRCMF_E_STATUS_NO_NETWORKS) {
brcmf_dbg(CONN, "Processing Link %s & no network found\n",
e->flags & BRCMF_EVENT_MSG_LINK ? "up" : "down");
return true;
}
if (event == BRCMF_E_SET_SSID && status != BRCMF_E_STATUS_SUCCESS) {
brcmf_dbg(CONN, "Processing connecting & no network found\n");
return true;
}
if (event == BRCMF_E_PSK_SUP &&
status != BRCMF_E_STATUS_FWSUP_COMPLETED) {
brcmf_dbg(CONN, "Processing failed supplicant state: %u\n",
status);
return true;
}
return false;
}
static void brcmf_clear_assoc_ies(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
kfree(conn_info->req_ie);
conn_info->req_ie = NULL;
conn_info->req_ie_len = 0;
kfree(conn_info->resp_ie);
conn_info->resp_ie = NULL;
conn_info->resp_ie_len = 0;
}
static s32 brcmf_get_assoc_ies(struct brcmf_cfg80211_info *cfg,
struct brcmf_if *ifp)
{
struct brcmf_cfg80211_assoc_ielen_le *assoc_info;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
u32 req_len;
u32 resp_len;
s32 err = 0;
brcmf_clear_assoc_ies(cfg);
err = brcmf_fil_iovar_data_get(ifp, "assoc_info",
cfg->extra_buf, WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc info (%d)\n", err);
return err;
}
assoc_info =
(struct brcmf_cfg80211_assoc_ielen_le *)cfg->extra_buf;
req_len = le32_to_cpu(assoc_info->req_len);
resp_len = le32_to_cpu(assoc_info->resp_len);
if (req_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_req_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc req (%d)\n", err);
return err;
}
conn_info->req_ie_len = req_len;
conn_info->req_ie =
kmemdup(cfg->extra_buf, conn_info->req_ie_len,
GFP_KERNEL);
} else {
conn_info->req_ie_len = 0;
conn_info->req_ie = NULL;
}
if (resp_len) {
err = brcmf_fil_iovar_data_get(ifp, "assoc_resp_ies",
cfg->extra_buf,
WL_ASSOC_INFO_MAX);
if (err) {
brcmf_err("could not get assoc resp (%d)\n", err);
return err;
}
conn_info->resp_ie_len = resp_len;
conn_info->resp_ie =
kmemdup(cfg->extra_buf, conn_info->resp_ie_len,
GFP_KERNEL);
} else {
conn_info->resp_ie_len = 0;
conn_info->resp_ie = NULL;
}
brcmf_dbg(CONN, "req len (%d) resp len (%d)\n",
conn_info->req_ie_len, conn_info->resp_ie_len);
return err;
}
static s32
brcmf_bss_roaming_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
struct wiphy *wiphy = cfg_to_wiphy(cfg);
struct ieee80211_channel *notify_channel = NULL;
struct ieee80211_supported_band *band;
struct brcmf_bss_info_le *bi;
struct brcmu_chan ch;
struct cfg80211_roam_info roam_info = {};
u32 freq;
s32 err = 0;
u8 *buf;
brcmf_dbg(TRACE, "Enter\n");
brcmf_get_assoc_ies(cfg, ifp);
memcpy(profile->bssid, e->addr, ETH_ALEN);
brcmf_update_bss_info(cfg, ifp);
buf = kzalloc(WL_BSS_INFO_MAX, GFP_KERNEL);
if (buf == NULL) {
err = -ENOMEM;
goto done;
}
/* data sent to dongle has to be little endian */
*(__le32 *)buf = cpu_to_le32(WL_BSS_INFO_MAX);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BSS_INFO,
buf, WL_BSS_INFO_MAX);
if (err)
goto done;
bi = (struct brcmf_bss_info_le *)(buf + 4);
ch.chspec = le16_to_cpu(bi->chanspec);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G)
band = wiphy->bands[NL80211_BAND_2GHZ];
else
band = wiphy->bands[NL80211_BAND_5GHZ];
freq = ieee80211_channel_to_frequency(ch.control_ch_num, band->band);
notify_channel = ieee80211_get_channel(wiphy, freq);
done:
kfree(buf);
roam_info.channel = notify_channel;
roam_info.bssid = profile->bssid;
roam_info.req_ie = conn_info->req_ie;
roam_info.req_ie_len = conn_info->req_ie_len;
roam_info.resp_ie = conn_info->resp_ie;
roam_info.resp_ie_len = conn_info->resp_ie_len;
cfg80211_roamed(ndev, &roam_info, GFP_KERNEL);
brcmf_dbg(CONN, "Report roaming result\n");
set_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state);
brcmf_dbg(TRACE, "Exit\n");
return err;
}
static s32
brcmf_bss_connect_done(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev, const struct brcmf_event_msg *e,
bool completed)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct brcmf_cfg80211_connect_info *conn_info = cfg_to_conn(cfg);
struct cfg80211_connect_resp_params conn_params;
brcmf_dbg(TRACE, "Enter\n");
if (test_and_clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state)) {
memset(&conn_params, 0, sizeof(conn_params));
if (completed) {
brcmf_get_assoc_ies(cfg, ifp);
brcmf_update_bss_info(cfg, ifp);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
conn_params.status = WLAN_STATUS_SUCCESS;
} else {
conn_params.status = WLAN_STATUS_AUTH_TIMEOUT;
}
conn_params.bssid = profile->bssid;
conn_params.req_ie = conn_info->req_ie;
conn_params.req_ie_len = conn_info->req_ie_len;
conn_params.resp_ie = conn_info->resp_ie;
conn_params.resp_ie_len = conn_info->resp_ie_len;
cfg80211_connect_done(ndev, &conn_params, GFP_KERNEL);
brcmf_dbg(CONN, "Report connect result - connection %s\n",
completed ? "succeeded" : "failed");
}
brcmf_dbg(TRACE, "Exit\n");
return 0;
}
static s32
brcmf_notify_connect_status_ap(struct brcmf_cfg80211_info *cfg,
struct net_device *ndev,
const struct brcmf_event_msg *e, void *data)
{
static int generation;
u32 event = e->event_code;
u32 reason = e->reason;
struct station_info sinfo;
brcmf_dbg(CONN, "event %s (%u), reason %d\n",
brcmf_fweh_event_name(event), event, reason);
if (event == BRCMF_E_LINK && reason == BRCMF_E_REASON_LINK_BSSCFG_DIS &&
ndev != cfg_to_ndev(cfg)) {
brcmf_dbg(CONN, "AP mode link down\n");
complete(&cfg->vif_disabled);
return 0;
}
if (((event == BRCMF_E_ASSOC_IND) || (event == BRCMF_E_REASSOC_IND)) &&
(reason == BRCMF_E_STATUS_SUCCESS)) {
memset(&sinfo, 0, sizeof(sinfo));
if (!data) {
brcmf_err("No IEs present in ASSOC/REASSOC_IND");
return -EINVAL;
}
sinfo.assoc_req_ies = data;
sinfo.assoc_req_ies_len = e->datalen;
generation++;
sinfo.generation = generation;
cfg80211_new_sta(ndev, e->addr, &sinfo, GFP_KERNEL);
} else if ((event == BRCMF_E_DISASSOC_IND) ||
(event == BRCMF_E_DEAUTH_IND) ||
(event == BRCMF_E_DEAUTH)) {
cfg80211_del_sta(ndev, e->addr, GFP_KERNEL);
}
return 0;
}
static s32
brcmf_notify_connect_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct net_device *ndev = ifp->ndev;
struct brcmf_cfg80211_profile *profile = &ifp->vif->profile;
struct ieee80211_channel *chan;
s32 err = 0;
if ((e->event_code == BRCMF_E_DEAUTH) ||
(e->event_code == BRCMF_E_DEAUTH_IND) ||
(e->event_code == BRCMF_E_DISASSOC_IND) ||
((e->event_code == BRCMF_E_LINK) && (!e->flags))) {
brcmf_proto_delete_peer(ifp->drvr, ifp->ifidx, (u8 *)e->addr);
}
if (brcmf_is_apmode(ifp->vif)) {
err = brcmf_notify_connect_status_ap(cfg, ndev, e, data);
} else if (brcmf_is_linkup(ifp->vif, e)) {
brcmf_dbg(CONN, "Linkup\n");
if (brcmf_is_ibssmode(ifp->vif)) {
brcmf_inform_ibss(cfg, ndev, e->addr);
chan = ieee80211_get_channel(cfg->wiphy, cfg->channel);
memcpy(profile->bssid, e->addr, ETH_ALEN);
cfg80211_ibss_joined(ndev, e->addr, chan, GFP_KERNEL);
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
set_bit(BRCMF_VIF_STATUS_CONNECTED,
&ifp->vif->sme_state);
} else
brcmf_bss_connect_done(cfg, ndev, e, true);
brcmf_net_setcarrier(ifp, true);
} else if (brcmf_is_linkdown(e)) {
brcmf_dbg(CONN, "Linkdown\n");
if (!brcmf_is_ibssmode(ifp->vif)) {
brcmf_bss_connect_done(cfg, ndev, e, false);
brcmf_link_down(ifp->vif,
brcmf_map_fw_linkdown_reason(e));
brcmf_init_prof(ndev_to_prof(ndev));
if (ndev != cfg_to_ndev(cfg))
complete(&cfg->vif_disabled);
brcmf_net_setcarrier(ifp, false);
}
} else if (brcmf_is_nonetwork(cfg, e)) {
if (brcmf_is_ibssmode(ifp->vif))
clear_bit(BRCMF_VIF_STATUS_CONNECTING,
&ifp->vif->sme_state);
else
brcmf_bss_connect_done(cfg, ndev, e, false);
}
return err;
}
static s32
brcmf_notify_roaming_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
u32 event = e->event_code;
u32 status = e->status;
if (event == BRCMF_E_ROAM && status == BRCMF_E_STATUS_SUCCESS) {
if (test_bit(BRCMF_VIF_STATUS_CONNECTED, &ifp->vif->sme_state))
brcmf_bss_roaming_done(cfg, ifp->ndev, e);
else
brcmf_bss_connect_done(cfg, ifp->ndev, e, true);
}
return 0;
}
static s32
brcmf_notify_mic_status(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
u16 flags = e->flags;
enum nl80211_key_type key_type;
if (flags & BRCMF_EVENT_MSG_GROUP)
key_type = NL80211_KEYTYPE_GROUP;
else
key_type = NL80211_KEYTYPE_PAIRWISE;
cfg80211_michael_mic_failure(ifp->ndev, (u8 *)&e->addr, key_type, -1,
NULL, GFP_KERNEL);
return 0;
}
static s32 brcmf_notify_vif_event(struct brcmf_if *ifp,
const struct brcmf_event_msg *e, void *data)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
struct brcmf_if_event *ifevent = (struct brcmf_if_event *)data;
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
struct brcmf_cfg80211_vif *vif;
brcmf_dbg(TRACE, "Enter: action %u flags %u ifidx %u bsscfgidx %u\n",
ifevent->action, ifevent->flags, ifevent->ifidx,
ifevent->bsscfgidx);
spin_lock(&event->vif_event_lock);
event->action = ifevent->action;
vif = event->vif;
switch (ifevent->action) {
case BRCMF_E_IF_ADD:
/* waiting process may have timed out */
if (!cfg->vif_event.vif) {
spin_unlock(&event->vif_event_lock);
return -EBADF;
}
ifp->vif = vif;
vif->ifp = ifp;
if (ifp->ndev) {
vif->wdev.netdev = ifp->ndev;
ifp->ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ifp->ndev, wiphy_dev(cfg->wiphy));
}
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_DEL:
spin_unlock(&event->vif_event_lock);
/* event may not be upon user request */
if (brcmf_cfg80211_vif_event_armed(cfg))
wake_up(&event->vif_wq);
return 0;
case BRCMF_E_IF_CHANGE:
spin_unlock(&event->vif_event_lock);
wake_up(&event->vif_wq);
return 0;
default:
spin_unlock(&event->vif_event_lock);
break;
}
return -EINVAL;
}
static void brcmf_init_conf(struct brcmf_cfg80211_conf *conf)
{
conf->frag_threshold = (u32)-1;
conf->rts_threshold = (u32)-1;
conf->retry_short = (u32)-1;
conf->retry_long = (u32)-1;
}
static void brcmf_register_event_handlers(struct brcmf_cfg80211_info *cfg)
{
brcmf_fweh_register(cfg->pub, BRCMF_E_LINK,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DEAUTH,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_DISASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_REASSOC_IND,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_ROAM,
brcmf_notify_roaming_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_MIC_ERROR,
brcmf_notify_mic_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_SET_SSID,
brcmf_notify_connect_status);
brcmf_fweh_register(cfg->pub, BRCMF_E_PFN_NET_FOUND,
brcmf_notify_sched_scan_results);
brcmf_fweh_register(cfg->pub, BRCMF_E_IF,
brcmf_notify_vif_event);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_PROBEREQ_MSG,
brcmf_p2p_notify_rx_mgmt_p2p_probereq);
brcmf_fweh_register(cfg->pub, BRCMF_E_P2P_DISC_LISTEN_COMPLETE,
brcmf_p2p_notify_listen_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_RX,
brcmf_p2p_notify_action_frame_rx);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_ACTION_FRAME_OFF_CHAN_COMPLETE,
brcmf_p2p_notify_action_tx_complete);
brcmf_fweh_register(cfg->pub, BRCMF_E_PSK_SUP,
brcmf_notify_connect_status);
}
static void brcmf_deinit_priv_mem(struct brcmf_cfg80211_info *cfg)
{
kfree(cfg->conf);
cfg->conf = NULL;
kfree(cfg->extra_buf);
cfg->extra_buf = NULL;
kfree(cfg->wowl.nd);
cfg->wowl.nd = NULL;
kfree(cfg->wowl.nd_info);
cfg->wowl.nd_info = NULL;
kfree(cfg->escan_info.escan_buf);
cfg->escan_info.escan_buf = NULL;
}
static s32 brcmf_init_priv_mem(struct brcmf_cfg80211_info *cfg)
{
cfg->conf = kzalloc(sizeof(*cfg->conf), GFP_KERNEL);
if (!cfg->conf)
goto init_priv_mem_out;
cfg->extra_buf = kzalloc(WL_EXTRA_BUF_MAX, GFP_KERNEL);
if (!cfg->extra_buf)
goto init_priv_mem_out;
cfg->wowl.nd = kzalloc(sizeof(*cfg->wowl.nd) + sizeof(u32), GFP_KERNEL);
if (!cfg->wowl.nd)
goto init_priv_mem_out;
cfg->wowl.nd_info = kzalloc(sizeof(*cfg->wowl.nd_info) +
sizeof(struct cfg80211_wowlan_nd_match *),
GFP_KERNEL);
if (!cfg->wowl.nd_info)
goto init_priv_mem_out;
cfg->escan_info.escan_buf = kzalloc(BRCMF_ESCAN_BUF_SIZE, GFP_KERNEL);
if (!cfg->escan_info.escan_buf)
goto init_priv_mem_out;
return 0;
init_priv_mem_out:
brcmf_deinit_priv_mem(cfg);
return -ENOMEM;
}
static s32 wl_init_priv(struct brcmf_cfg80211_info *cfg)
{
s32 err = 0;
cfg->scan_request = NULL;
cfg->pwr_save = true;
cfg->active_scan = true; /* we do active scan per default */
cfg->dongle_up = false; /* dongle is not up yet */
err = brcmf_init_priv_mem(cfg);
if (err)
return err;
brcmf_register_event_handlers(cfg);
mutex_init(&cfg->usr_sync);
brcmf_init_escan(cfg);
brcmf_init_conf(cfg->conf);
init_completion(&cfg->vif_disabled);
return err;
}
static void wl_deinit_priv(struct brcmf_cfg80211_info *cfg)
{
cfg->dongle_up = false; /* dongle down */
brcmf_abort_scanning(cfg);
brcmf_deinit_priv_mem(cfg);
}
static void init_vif_event(struct brcmf_cfg80211_vif_event *event)
{
init_waitqueue_head(&event->vif_wq);
spin_lock_init(&event->vif_event_lock);
}
static s32 brcmf_dongle_roam(struct brcmf_if *ifp)
{
s32 err;
u32 bcn_timeout;
__le32 roamtrigger[2];
__le32 roam_delta[2];
/* Configure beacon timeout value based upon roaming setting */
if (ifp->drvr->settings->roamoff)
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_OFF;
else
bcn_timeout = BRCMF_DEFAULT_BCN_TIMEOUT_ROAM_ON;
err = brcmf_fil_iovar_int_set(ifp, "bcn_timeout", bcn_timeout);
if (err) {
brcmf_err("bcn_timeout error (%d)\n", err);
goto roam_setup_done;
}
/* Enable/Disable built-in roaming to allow supplicant to take care of
* roaming.
*/
brcmf_dbg(INFO, "Internal Roaming = %s\n",
ifp->drvr->settings->roamoff ? "Off" : "On");
err = brcmf_fil_iovar_int_set(ifp, "roam_off",
ifp->drvr->settings->roamoff);
if (err) {
brcmf_err("roam_off error (%d)\n", err);
goto roam_setup_done;
}
roamtrigger[0] = cpu_to_le32(WL_ROAM_TRIGGER_LEVEL);
roamtrigger[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_TRIGGER,
(void *)roamtrigger, sizeof(roamtrigger));
if (err) {
brcmf_err("WLC_SET_ROAM_TRIGGER error (%d)\n", err);
goto roam_setup_done;
}
roam_delta[0] = cpu_to_le32(WL_ROAM_DELTA);
roam_delta[1] = cpu_to_le32(BRCM_BAND_ALL);
err = brcmf_fil_cmd_data_set(ifp, BRCMF_C_SET_ROAM_DELTA,
(void *)roam_delta, sizeof(roam_delta));
if (err) {
brcmf_err("WLC_SET_ROAM_DELTA error (%d)\n", err);
goto roam_setup_done;
}
roam_setup_done:
return err;
}
static s32
brcmf_dongle_scantime(struct brcmf_if *ifp)
{
s32 err = 0;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_CHANNEL_TIME,
BRCMF_SCAN_CHANNEL_TIME);
if (err) {
brcmf_err("Scan assoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_UNASSOC_TIME,
BRCMF_SCAN_UNASSOC_TIME);
if (err) {
brcmf_err("Scan unassoc time error (%d)\n", err);
goto dongle_scantime_out;
}
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_SCAN_PASSIVE_TIME,
BRCMF_SCAN_PASSIVE_TIME);
if (err) {
brcmf_err("Scan passive time error (%d)\n", err);
goto dongle_scantime_out;
}
dongle_scantime_out:
return err;
}
static void brcmf_update_bw40_channel_flag(struct ieee80211_channel *channel,
struct brcmu_chan *ch)
{
u32 ht40_flag;
ht40_flag = channel->flags & IEEE80211_CHAN_NO_HT40;
if (ch->sb == BRCMU_CHAN_SB_U) {
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
channel->flags |= IEEE80211_CHAN_NO_HT40PLUS;
} else {
/* It should be one of
* IEEE80211_CHAN_NO_HT40 or
* IEEE80211_CHAN_NO_HT40PLUS
*/
channel->flags &= ~IEEE80211_CHAN_NO_HT40;
if (ht40_flag == IEEE80211_CHAN_NO_HT40)
channel->flags |= IEEE80211_CHAN_NO_HT40MINUS;
}
}
static int brcmf_construct_chaninfo(struct brcmf_cfg80211_info *cfg,
u32 bw_cap[])
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct ieee80211_channel *channel;
struct wiphy *wiphy;
struct brcmf_chanspec_list *list;
struct brcmu_chan ch;
int err;
u8 *pbuf;
u32 i, j;
u32 total;
u32 chaninfo;
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
list = (struct brcmf_chanspec_list *)pbuf;
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
goto fail_pbuf;
}
wiphy = cfg_to_wiphy(cfg);
band = wiphy->bands[NL80211_BAND_2GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
band = wiphy->bands[NL80211_BAND_5GHZ];
if (band)
for (i = 0; i < band->n_channels; i++)
band->channels[i].flags = IEEE80211_CHAN_DISABLED;
total = le32_to_cpu(list->count);
for (i = 0; i < total; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (ch.band == BRCMU_CHAN_BAND_2G) {
band = wiphy->bands[NL80211_BAND_2GHZ];
} else if (ch.band == BRCMU_CHAN_BAND_5G) {
band = wiphy->bands[NL80211_BAND_5GHZ];
} else {
brcmf_err("Invalid channel Spec. 0x%x.\n", ch.chspec);
continue;
}
if (!band)
continue;
if (!(bw_cap[band->band] & WLC_BW_40MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_40)
continue;
if (!(bw_cap[band->band] & WLC_BW_80MHZ_BIT) &&
ch.bw == BRCMU_CHAN_BW_80)
continue;
channel = NULL;
for (j = 0; j < band->n_channels; j++) {
if (band->channels[j].hw_value == ch.control_ch_num) {
channel = &band->channels[j];
break;
}
}
if (!channel) {
/* It seems firmware supports some channel we never
* considered. Something new in IEEE standard?
*/
brcmf_err("Ignoring unexpected firmware channel %d\n",
ch.control_ch_num);
continue;
}
if (channel->orig_flags & IEEE80211_CHAN_DISABLED)
continue;
/* assuming the chanspecs order is HT20,
* HT40 upper, HT40 lower, and VHT80.
*/
if (ch.bw == BRCMU_CHAN_BW_80) {
channel->flags &= ~IEEE80211_CHAN_NO_80MHZ;
} else if (ch.bw == BRCMU_CHAN_BW_40) {
brcmf_update_bw40_channel_flag(channel, &ch);
} else {
/* enable the channel and disable other bandwidths
* for now as mentioned order assure they are enabled
* for subsequent chanspecs.
*/
channel->flags = IEEE80211_CHAN_NO_HT40 |
IEEE80211_CHAN_NO_80MHZ;
ch.bw = BRCMU_CHAN_BW_20;
cfg->d11inf.encchspec(&ch);
chaninfo = ch.chspec;
err = brcmf_fil_bsscfg_int_get(ifp, "per_chan_info",
&chaninfo);
if (!err) {
if (chaninfo & WL_CHAN_RADAR)
channel->flags |=
(IEEE80211_CHAN_RADAR |
IEEE80211_CHAN_NO_IR);
if (chaninfo & WL_CHAN_PASSIVE)
channel->flags |=
IEEE80211_CHAN_NO_IR;
}
}
}
fail_pbuf:
kfree(pbuf);
return err;
}
static int brcmf_enable_bw40_2g(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct ieee80211_supported_band *band;
struct brcmf_fil_bwcap_le band_bwcap;
struct brcmf_chanspec_list *list;
u8 *pbuf;
u32 val;
int err;
struct brcmu_chan ch;
u32 num_chan;
int i, j;
/* verify support for bw_cap command */
val = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &val);
if (!err) {
/* only set 2G bandwidth using bw_cap command */
band_bwcap.band = cpu_to_le32(WLC_BAND_2G);
band_bwcap.bw_cap = cpu_to_le32(WLC_BW_CAP_40MHZ);
err = brcmf_fil_iovar_data_set(ifp, "bw_cap", &band_bwcap,
sizeof(band_bwcap));
} else {
brcmf_dbg(INFO, "fallback to mimo_bw_cap\n");
val = WLC_N_BW_40ALL;
err = brcmf_fil_iovar_int_set(ifp, "mimo_bw_cap", val);
}
if (!err) {
/* update channel info in 2G band */
pbuf = kzalloc(BRCMF_DCMD_MEDLEN, GFP_KERNEL);
if (pbuf == NULL)
return -ENOMEM;
ch.band = BRCMU_CHAN_BAND_2G;
ch.bw = BRCMU_CHAN_BW_40;
ch.sb = BRCMU_CHAN_SB_NONE;
ch.chnum = 0;
cfg->d11inf.encchspec(&ch);
/* pass encoded chanspec in query */
*(__le16 *)pbuf = cpu_to_le16(ch.chspec);
err = brcmf_fil_iovar_data_get(ifp, "chanspecs", pbuf,
BRCMF_DCMD_MEDLEN);
if (err) {
brcmf_err("get chanspecs error (%d)\n", err);
kfree(pbuf);
return err;
}
band = cfg_to_wiphy(cfg)->bands[NL80211_BAND_2GHZ];
list = (struct brcmf_chanspec_list *)pbuf;
num_chan = le32_to_cpu(list->count);
for (i = 0; i < num_chan; i++) {
ch.chspec = (u16)le32_to_cpu(list->element[i]);
cfg->d11inf.decchspec(&ch);
if (WARN_ON(ch.band != BRCMU_CHAN_BAND_2G))
continue;
if (WARN_ON(ch.bw != BRCMU_CHAN_BW_40))
continue;
for (j = 0; j < band->n_channels; j++) {
if (band->channels[j].hw_value == ch.control_ch_num)
break;
}
if (WARN_ON(j == band->n_channels))
continue;
brcmf_update_bw40_channel_flag(&band->channels[j], &ch);
}
kfree(pbuf);
}
return err;
}
static void brcmf_get_bwcap(struct brcmf_if *ifp, u32 bw_cap[])
{
u32 band, mimo_bwcap;
int err;
band = WLC_BAND_2G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_2GHZ] = band;
band = WLC_BAND_5G;
err = brcmf_fil_iovar_int_get(ifp, "bw_cap", &band);
if (!err) {
bw_cap[NL80211_BAND_5GHZ] = band;
return;
}
WARN_ON(1);
return;
}
brcmf_dbg(INFO, "fallback to mimo_bw_cap info\n");
mimo_bwcap = 0;
err = brcmf_fil_iovar_int_get(ifp, "mimo_bw_cap", &mimo_bwcap);
if (err)
/* assume 20MHz if firmware does not give a clue */
mimo_bwcap = WLC_N_BW_20ALL;
switch (mimo_bwcap) {
case WLC_N_BW_40ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20IN2G_40IN5G:
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_40MHZ_BIT;
/* fall-thru */
case WLC_N_BW_20ALL:
bw_cap[NL80211_BAND_2GHZ] |= WLC_BW_20MHZ_BIT;
bw_cap[NL80211_BAND_5GHZ] |= WLC_BW_20MHZ_BIT;
break;
default:
brcmf_err("invalid mimo_bw_cap value\n");
}
}
static void brcmf_update_ht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain)
{
band->ht_cap.ht_supported = true;
if (bw_cap[band->band] & WLC_BW_40MHZ_BIT) {
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_40;
band->ht_cap.cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
band->ht_cap.cap |= IEEE80211_HT_CAP_SGI_20;
band->ht_cap.cap |= IEEE80211_HT_CAP_DSSSCCK40;
band->ht_cap.ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K;
band->ht_cap.ampdu_density = IEEE80211_HT_MPDU_DENSITY_16;
memset(band->ht_cap.mcs.rx_mask, 0xff, nchain);
band->ht_cap.mcs.tx_params = IEEE80211_HT_MCS_TX_DEFINED;
}
static __le16 brcmf_get_mcs_map(u32 nchain, enum ieee80211_vht_mcs_support supp)
{
u16 mcs_map;
int i;
for (i = 0, mcs_map = 0xFFFF; i < nchain; i++)
mcs_map = (mcs_map << 2) | supp;
return cpu_to_le16(mcs_map);
}
static void brcmf_update_vht_cap(struct ieee80211_supported_band *band,
u32 bw_cap[2], u32 nchain, u32 txstreams,
u32 txbf_bfe_cap, u32 txbf_bfr_cap)
{
__le16 mcs_map;
/* not allowed in 2.4G band */
if (band->band == NL80211_BAND_2GHZ)
return;
band->vht_cap.vht_supported = true;
/* 80MHz is mandatory */
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_80;
if (bw_cap[band->band] & WLC_BW_160MHZ_BIT) {
band->vht_cap.cap |= IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ;
band->vht_cap.cap |= IEEE80211_VHT_CAP_SHORT_GI_160;
}
/* all support 256-QAM */
mcs_map = brcmf_get_mcs_map(nchain, IEEE80211_VHT_MCS_SUPPORT_0_9);
band->vht_cap.vht_mcs.rx_mcs_map = mcs_map;
band->vht_cap.vht_mcs.tx_mcs_map = mcs_map;
/* Beamforming support information */
if (txbf_bfe_cap & BRCMF_TXBF_SU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE;
if (txbf_bfe_cap & BRCMF_TXBF_MU_BFE_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMEE_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_SU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE;
if (txbf_bfr_cap & BRCMF_TXBF_MU_BFR_CAP)
band->vht_cap.cap |= IEEE80211_VHT_CAP_MU_BEAMFORMER_CAPABLE;
if ((txbf_bfe_cap || txbf_bfr_cap) && (txstreams > 1)) {
band->vht_cap.cap |=
(2 << IEEE80211_VHT_CAP_BEAMFORMEE_STS_SHIFT);
band->vht_cap.cap |= ((txstreams - 1) <<
IEEE80211_VHT_CAP_SOUNDING_DIMENSIONS_SHIFT);
band->vht_cap.cap |=
IEEE80211_VHT_CAP_VHT_LINK_ADAPTATION_VHT_MRQ_MFB;
}
}
static int brcmf_setup_wiphybands(struct wiphy *wiphy)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
u32 nmode = 0;
u32 vhtmode = 0;
u32 bw_cap[2] = { WLC_BW_20MHZ_BIT, WLC_BW_20MHZ_BIT };
u32 rxchain;
u32 nchain;
int err;
s32 i;
struct ieee80211_supported_band *band;
u32 txstreams = 0;
u32 txbf_bfe_cap = 0;
u32 txbf_bfr_cap = 0;
(void)brcmf_fil_iovar_int_get(ifp, "vhtmode", &vhtmode);
err = brcmf_fil_iovar_int_get(ifp, "nmode", &nmode);
if (err) {
brcmf_err("nmode error (%d)\n", err);
} else {
brcmf_get_bwcap(ifp, bw_cap);
}
brcmf_dbg(INFO, "nmode=%d, vhtmode=%d, bw_cap=(%d, %d)\n",
nmode, vhtmode, bw_cap[NL80211_BAND_2GHZ],
bw_cap[NL80211_BAND_5GHZ]);
err = brcmf_fil_iovar_int_get(ifp, "rxchain", &rxchain);
if (err) {
brcmf_err("rxchain error (%d)\n", err);
nchain = 1;
} else {
for (nchain = 0; rxchain; nchain++)
rxchain = rxchain & (rxchain - 1);
}
brcmf_dbg(INFO, "nchain=%d\n", nchain);
err = brcmf_construct_chaninfo(cfg, bw_cap);
if (err) {
brcmf_err("brcmf_construct_chaninfo failed (%d)\n", err);
return err;
}
if (vhtmode) {
(void)brcmf_fil_iovar_int_get(ifp, "txstreams", &txstreams);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfe_cap",
&txbf_bfe_cap);
(void)brcmf_fil_iovar_int_get(ifp, "txbf_bfr_cap",
&txbf_bfr_cap);
}
wiphy = cfg_to_wiphy(cfg);
for (i = 0; i < ARRAY_SIZE(wiphy->bands); i++) {
band = wiphy->bands[i];
if (band == NULL)
continue;
if (nmode)
brcmf_update_ht_cap(band, bw_cap, nchain);
if (vhtmode)
brcmf_update_vht_cap(band, bw_cap, nchain, txstreams,
txbf_bfe_cap, txbf_bfr_cap);
}
return 0;
}
static const struct ieee80211_txrx_stypes
brcmf_txrx_stypes[NUM_NL80211_IFTYPES] = {
[NL80211_IFTYPE_STATION] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_CLIENT] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
},
[NL80211_IFTYPE_P2P_GO] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4) |
BIT(IEEE80211_STYPE_DISASSOC >> 4) |
BIT(IEEE80211_STYPE_AUTH >> 4) |
BIT(IEEE80211_STYPE_DEAUTH >> 4) |
BIT(IEEE80211_STYPE_ACTION >> 4)
},
[NL80211_IFTYPE_P2P_DEVICE] = {
.tx = 0xffff,
.rx = BIT(IEEE80211_STYPE_ACTION >> 4) |
BIT(IEEE80211_STYPE_PROBE_REQ >> 4)
}
};
/**
* brcmf_setup_ifmodes() - determine interface modes and combinations.
*
* @wiphy: wiphy object.
* @ifp: interface object needed for feat module api.
*
* The interface modes and combinations are determined dynamically here
* based on firmware functionality.
*
* no p2p and no mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
*
* no p2p and mbss:
*
* #STA <= 1, #AP <= 1, channels = 1, 2 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, no mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 1, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*
* p2p, mchan, and mbss:
*
* #STA <= 1, #P2P-DEV <= 1, #{P2P-CL, P2P-GO} <= 1, channels = 2, 3 total
* #STA <= 1, #P2P-DEV <= 1, #AP <= 1, #P2P-CL <= 1, channels = 1, 4 total
* #AP <= 4, matching BI, channels = 1, 4 total
*/
static int brcmf_setup_ifmodes(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct ieee80211_iface_combination *combo = NULL;
struct ieee80211_iface_limit *c0_limits = NULL;
struct ieee80211_iface_limit *p2p_limits = NULL;
struct ieee80211_iface_limit *mbss_limits = NULL;
bool mbss, p2p;
int i, c, n_combos;
mbss = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MBSS);
p2p = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_P2P);
n_combos = 1 + !!p2p + !!mbss;
combo = kcalloc(n_combos, sizeof(*combo), GFP_KERNEL);
if (!combo)
goto err;
wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) |
BIT(NL80211_IFTYPE_ADHOC) |
BIT(NL80211_IFTYPE_AP);
c = 0;
i = 0;
c0_limits = kcalloc(p2p ? 3 : 2, sizeof(*c0_limits), GFP_KERNEL);
if (!c0_limits)
goto err;
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
if (p2p) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MCHAN))
combo[c].num_different_channels = 2;
wiphy->interface_modes |= BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO) |
BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT) |
BIT(NL80211_IFTYPE_P2P_GO);
} else {
c0_limits[i].max = 1;
c0_limits[i++].types = BIT(NL80211_IFTYPE_AP);
}
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = c0_limits;
if (p2p) {
c++;
i = 0;
p2p_limits = kcalloc(4, sizeof(*p2p_limits), GFP_KERNEL);
if (!p2p_limits)
goto err;
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_STATION);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_AP);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_CLIENT);
p2p_limits[i].max = 1;
p2p_limits[i++].types = BIT(NL80211_IFTYPE_P2P_DEVICE);
combo[c].num_different_channels = 1;
combo[c].max_interfaces = i;
combo[c].n_limits = i;
combo[c].limits = p2p_limits;
}
if (mbss) {
c++;
i = 0;
mbss_limits = kcalloc(1, sizeof(*mbss_limits), GFP_KERNEL);
if (!mbss_limits)
goto err;
mbss_limits[i].max = 4;
mbss_limits[i++].types = BIT(NL80211_IFTYPE_AP);
combo[c].beacon_int_infra_match = true;
combo[c].num_different_channels = 1;
combo[c].max_interfaces = 4;
combo[c].n_limits = i;
combo[c].limits = mbss_limits;
}
wiphy->n_iface_combinations = n_combos;
wiphy->iface_combinations = combo;
return 0;
err:
kfree(c0_limits);
kfree(p2p_limits);
kfree(mbss_limits);
kfree(combo);
return -ENOMEM;
}
#ifdef CONFIG_PM
static const struct wiphy_wowlan_support brcmf_wowlan_support = {
.flags = WIPHY_WOWLAN_MAGIC_PKT | WIPHY_WOWLAN_DISCONNECT,
.n_patterns = BRCMF_WOWL_MAXPATTERNS,
.pattern_max_len = BRCMF_WOWL_MAXPATTERNSIZE,
.pattern_min_len = 1,
.max_pkt_offset = 1500,
};
#endif
static void brcmf_wiphy_wowl_params(struct wiphy *wiphy, struct brcmf_if *ifp)
{
#ifdef CONFIG_PM
struct brcmf_cfg80211_info *cfg = wiphy_to_cfg(wiphy);
struct wiphy_wowlan_support *wowl;
wowl = kmemdup(&brcmf_wowlan_support, sizeof(brcmf_wowlan_support),
GFP_KERNEL);
if (!wowl) {
brcmf_err("only support basic wowlan features\n");
wiphy->wowlan = &brcmf_wowlan_support;
return;
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO)) {
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_ND)) {
wowl->flags |= WIPHY_WOWLAN_NET_DETECT;
wowl->max_nd_match_sets = BRCMF_PNO_MAX_PFN_COUNT;
init_waitqueue_head(&cfg->wowl.nd_data_wait);
}
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK)) {
wowl->flags |= WIPHY_WOWLAN_SUPPORTS_GTK_REKEY;
wowl->flags |= WIPHY_WOWLAN_GTK_REKEY_FAILURE;
}
wiphy->wowlan = wowl;
#endif
}
static int brcmf_setup_wiphy(struct wiphy *wiphy, struct brcmf_if *ifp)
{
struct brcmf_pub *drvr = ifp->drvr;
const struct ieee80211_iface_combination *combo;
struct ieee80211_supported_band *band;
u16 max_interfaces = 0;
bool gscan;
__le32 bandlist[3];
u32 n_bands;
int err, i;
wiphy->max_scan_ssids = WL_NUM_SCAN_MAX;
wiphy->max_scan_ie_len = BRCMF_SCAN_IE_LEN_MAX;
wiphy->max_num_pmkids = BRCMF_MAXPMKID;
err = brcmf_setup_ifmodes(wiphy, ifp);
if (err)
return err;
for (i = 0, combo = wiphy->iface_combinations;
i < wiphy->n_iface_combinations; i++, combo++) {
max_interfaces = max(max_interfaces, combo->max_interfaces);
}
for (i = 0; i < max_interfaces && i < ARRAY_SIZE(drvr->addresses);
i++) {
u8 *addr = drvr->addresses[i].addr;
memcpy(addr, drvr->mac, ETH_ALEN);
if (i) {
addr[0] |= BIT(1);
addr[ETH_ALEN - 1] ^= i;
}
}
wiphy->addresses = drvr->addresses;
wiphy->n_addresses = i;
wiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM;
wiphy->cipher_suites = brcmf_cipher_suites;
wiphy->n_cipher_suites = ARRAY_SIZE(brcmf_cipher_suites);
if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP))
wiphy->n_cipher_suites--;
wiphy->bss_select_support = BIT(NL80211_BSS_SELECT_ATTR_RSSI) |
BIT(NL80211_BSS_SELECT_ATTR_BAND_PREF) |
BIT(NL80211_BSS_SELECT_ATTR_RSSI_ADJUST);
wiphy->flags |= WIPHY_FLAG_NETNS_OK |
WIPHY_FLAG_PS_ON_BY_DEFAULT |
WIPHY_FLAG_OFFCHAN_TX |
WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS))
wiphy->flags |= WIPHY_FLAG_SUPPORTS_TDLS;
if (!ifp->drvr->settings->roamoff)
wiphy->flags |= WIPHY_FLAG_SUPPORTS_FW_ROAM;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_FWSUP)) {
wiphy_ext_feature_set(wiphy,
NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_PSK);
wiphy_ext_feature_set(wiphy,
NL80211_EXT_FEATURE_4WAY_HANDSHAKE_STA_1X);
}
wiphy->mgmt_stypes = brcmf_txrx_stypes;
wiphy->max_remain_on_channel_duration = 5000;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_PNO)) {
gscan = brcmf_feat_is_enabled(ifp, BRCMF_FEAT_GSCAN);
brcmf_pno_wiphy_params(wiphy, gscan);
}
/* vendor commands/events support */
wiphy->vendor_commands = brcmf_vendor_cmds;
wiphy->n_vendor_commands = BRCMF_VNDR_CMDS_LAST - 1;
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL))
brcmf_wiphy_wowl_params(wiphy, ifp);
err = brcmf_fil_cmd_data_get(ifp, BRCMF_C_GET_BANDLIST, &bandlist,
sizeof(bandlist));
if (err) {
brcmf_err("could not obtain band info: err=%d\n", err);
return err;
}
/* first entry in bandlist is number of bands */
n_bands = le32_to_cpu(bandlist[0]);
for (i = 1; i <= n_bands && i < ARRAY_SIZE(bandlist); i++) {
if (bandlist[i] == cpu_to_le32(WLC_BAND_2G)) {
band = kmemdup(&__wl_band_2ghz, sizeof(__wl_band_2ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_2ghz_channels,
sizeof(__wl_2ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_2ghz_channels);
wiphy->bands[NL80211_BAND_2GHZ] = band;
}
if (bandlist[i] == cpu_to_le32(WLC_BAND_5G)) {
band = kmemdup(&__wl_band_5ghz, sizeof(__wl_band_5ghz),
GFP_KERNEL);
if (!band)
return -ENOMEM;
band->channels = kmemdup(&__wl_5ghz_channels,
sizeof(__wl_5ghz_channels),
GFP_KERNEL);
if (!band->channels) {
kfree(band);
return -ENOMEM;
}
band->n_channels = ARRAY_SIZE(__wl_5ghz_channels);
wiphy->bands[NL80211_BAND_5GHZ] = band;
}
}
wiphy_read_of_freq_limits(wiphy);
return 0;
}
static s32 brcmf_config_dongle(struct brcmf_cfg80211_info *cfg)
{
struct net_device *ndev;
struct wireless_dev *wdev;
struct brcmf_if *ifp;
s32 power_mode;
s32 err = 0;
if (cfg->dongle_up)
return err;
ndev = cfg_to_ndev(cfg);
wdev = ndev->ieee80211_ptr;
ifp = netdev_priv(ndev);
/* make sure RF is ready for work */
brcmf_fil_cmd_int_set(ifp, BRCMF_C_UP, 0);
brcmf_dongle_scantime(ifp);
power_mode = cfg->pwr_save ? PM_FAST : PM_OFF;
err = brcmf_fil_cmd_int_set(ifp, BRCMF_C_SET_PM, power_mode);
if (err)
goto default_conf_out;
brcmf_dbg(INFO, "power save set to %s\n",
(power_mode ? "enabled" : "disabled"));
err = brcmf_dongle_roam(ifp);
if (err)
goto default_conf_out;
err = brcmf_cfg80211_change_iface(wdev->wiphy, ndev, wdev->iftype,
NULL);
if (err)
goto default_conf_out;
brcmf_configure_arp_nd_offload(ifp, true);
cfg->dongle_up = true;
default_conf_out:
return err;
}
static s32 __brcmf_cfg80211_up(struct brcmf_if *ifp)
{
set_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return brcmf_config_dongle(ifp->drvr->config);
}
static s32 __brcmf_cfg80211_down(struct brcmf_if *ifp)
{
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
/*
* While going down, if associated with AP disassociate
* from AP to save power
*/
if (check_vif_up(ifp->vif)) {
brcmf_link_down(ifp->vif, WLAN_REASON_UNSPECIFIED);
/* Make sure WPA_Supplicant receives all the event
generated due to DISASSOC call to the fw to keep
the state fw and WPA_Supplicant state consistent
*/
brcmf_delay(500);
}
brcmf_abort_scanning(cfg);
clear_bit(BRCMF_VIF_STATUS_READY, &ifp->vif->sme_state);
return 0;
}
s32 brcmf_cfg80211_up(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_up(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
s32 brcmf_cfg80211_down(struct net_device *ndev)
{
struct brcmf_if *ifp = netdev_priv(ndev);
struct brcmf_cfg80211_info *cfg = ifp->drvr->config;
s32 err = 0;
mutex_lock(&cfg->usr_sync);
err = __brcmf_cfg80211_down(ifp);
mutex_unlock(&cfg->usr_sync);
return err;
}
enum nl80211_iftype brcmf_cfg80211_get_iftype(struct brcmf_if *ifp)
{
struct wireless_dev *wdev = &ifp->vif->wdev;
return wdev->iftype;
}
bool brcmf_get_vif_state_any(struct brcmf_cfg80211_info *cfg,
unsigned long state)
{
struct brcmf_cfg80211_vif *vif;
list_for_each_entry(vif, &cfg->vif_list, list) {
if (test_bit(state, &vif->sme_state))
return true;
}
return false;
}
static inline bool vif_event_equals(struct brcmf_cfg80211_vif_event *event,
u8 action)
{
u8 evt_action;
spin_lock(&event->vif_event_lock);
evt_action = event->action;
spin_unlock(&event->vif_event_lock);
return evt_action == action;
}
void brcmf_cfg80211_arm_vif_event(struct brcmf_cfg80211_info *cfg,
struct brcmf_cfg80211_vif *vif)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
spin_lock(&event->vif_event_lock);
event->vif = vif;
event->action = 0;
spin_unlock(&event->vif_event_lock);
}
bool brcmf_cfg80211_vif_event_armed(struct brcmf_cfg80211_info *cfg)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
bool armed;
spin_lock(&event->vif_event_lock);
armed = event->vif != NULL;
spin_unlock(&event->vif_event_lock);
return armed;
}
int brcmf_cfg80211_wait_vif_event(struct brcmf_cfg80211_info *cfg,
u8 action, ulong timeout)
{
struct brcmf_cfg80211_vif_event *event = &cfg->vif_event;
return wait_event_timeout(event->vif_wq,
vif_event_equals(event, action), timeout);
}
static s32 brcmf_translate_country_code(struct brcmf_pub *drvr, char alpha2[2],
struct brcmf_fil_country_le *ccreq)
{
struct brcmfmac_pd_cc *country_codes;
struct brcmfmac_pd_cc_entry *cc;
s32 found_index;
int i;
country_codes = drvr->settings->country_codes;
if (!country_codes) {
brcmf_dbg(TRACE, "No country codes configured for device\n");
return -EINVAL;
}
if ((alpha2[0] == ccreq->country_abbrev[0]) &&
(alpha2[1] == ccreq->country_abbrev[1])) {
brcmf_dbg(TRACE, "Country code already set\n");
return -EAGAIN;
}
found_index = -1;
for (i = 0; i < country_codes->table_size; i++) {
cc = &country_codes->table[i];
if ((cc->iso3166[0] == '\0') && (found_index == -1))
found_index = i;
if ((cc->iso3166[0] == alpha2[0]) &&
(cc->iso3166[1] == alpha2[1])) {
found_index = i;
break;
}
}
if (found_index == -1) {
brcmf_dbg(TRACE, "No country code match found\n");
return -EINVAL;
}
memset(ccreq, 0, sizeof(*ccreq));
ccreq->rev = cpu_to_le32(country_codes->table[found_index].rev);
memcpy(ccreq->ccode, country_codes->table[found_index].cc,
BRCMF_COUNTRY_BUF_SZ);
ccreq->country_abbrev[0] = alpha2[0];
ccreq->country_abbrev[1] = alpha2[1];
ccreq->country_abbrev[2] = 0;
return 0;
}
static void brcmf_cfg80211_reg_notifier(struct wiphy *wiphy,
struct regulatory_request *req)
{
struct brcmf_cfg80211_info *cfg = wiphy_priv(wiphy);
struct brcmf_if *ifp = netdev_priv(cfg_to_ndev(cfg));
struct brcmf_fil_country_le ccreq;
s32 err;
int i;
/* The country code gets set to "00" by default at boot, ignore */
if (req->alpha2[0] == '0' && req->alpha2[1] == '0')
return;
/* ignore non-ISO3166 country codes */
for (i = 0; i < sizeof(req->alpha2); i++)
if (req->alpha2[i] < 'A' || req->alpha2[i] > 'Z') {
brcmf_err("not an ISO3166 code (0x%02x 0x%02x)\n",
req->alpha2[0], req->alpha2[1]);
return;
}
brcmf_dbg(TRACE, "Enter: initiator=%d, alpha=%c%c\n", req->initiator,
req->alpha2[0], req->alpha2[1]);
err = brcmf_fil_iovar_data_get(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Country code iovar returned err = %d\n", err);
return;
}
err = brcmf_translate_country_code(ifp->drvr, req->alpha2, &ccreq);
if (err)
return;
err = brcmf_fil_iovar_data_set(ifp, "country", &ccreq, sizeof(ccreq));
if (err) {
brcmf_err("Firmware rejected country setting\n");
return;
}
brcmf_setup_wiphybands(wiphy);
}
static void brcmf_free_wiphy(struct wiphy *wiphy)
{
int i;
if (!wiphy)
return;
if (wiphy->iface_combinations) {
for (i = 0; i < wiphy->n_iface_combinations; i++)
kfree(wiphy->iface_combinations[i].limits);
}
kfree(wiphy->iface_combinations);
if (wiphy->bands[NL80211_BAND_2GHZ]) {
kfree(wiphy->bands[NL80211_BAND_2GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_2GHZ]);
}
if (wiphy->bands[NL80211_BAND_5GHZ]) {
kfree(wiphy->bands[NL80211_BAND_5GHZ]->channels);
kfree(wiphy->bands[NL80211_BAND_5GHZ]);
}
#if IS_ENABLED(CONFIG_PM)
if (wiphy->wowlan != &brcmf_wowlan_support)
kfree(wiphy->wowlan);
#endif
wiphy_free(wiphy);
}
struct brcmf_cfg80211_info *brcmf_cfg80211_attach(struct brcmf_pub *drvr,
struct device *busdev,
bool p2pdev_forced)
{
struct net_device *ndev = brcmf_get_ifp(drvr, 0)->ndev;
struct brcmf_cfg80211_info *cfg;
struct wiphy *wiphy;
struct cfg80211_ops *ops;
struct brcmf_cfg80211_vif *vif;
struct brcmf_if *ifp;
s32 err = 0;
s32 io_type;
u16 *cap = NULL;
if (!ndev) {
brcmf_err("ndev is invalid\n");
return NULL;
}
ops = kmemdup(&brcmf_cfg80211_ops, sizeof(*ops), GFP_KERNEL);
if (!ops)
return NULL;
ifp = netdev_priv(ndev);
#ifdef CONFIG_PM
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_WOWL_GTK))
ops->set_rekey_data = brcmf_cfg80211_set_rekey_data;
#endif
wiphy = wiphy_new(ops, sizeof(struct brcmf_cfg80211_info));
if (!wiphy) {
brcmf_err("Could not allocate wiphy device\n");
goto ops_out;
}
memcpy(wiphy->perm_addr, drvr->mac, ETH_ALEN);
set_wiphy_dev(wiphy, busdev);
cfg = wiphy_priv(wiphy);
cfg->wiphy = wiphy;
cfg->ops = ops;
cfg->pub = drvr;
init_vif_event(&cfg->vif_event);
INIT_LIST_HEAD(&cfg->vif_list);
vif = brcmf_alloc_vif(cfg, NL80211_IFTYPE_STATION);
if (IS_ERR(vif))
goto wiphy_out;
vif->ifp = ifp;
vif->wdev.netdev = ndev;
ndev->ieee80211_ptr = &vif->wdev;
SET_NETDEV_DEV(ndev, wiphy_dev(cfg->wiphy));
err = wl_init_priv(cfg);
if (err) {
brcmf_err("Failed to init iwm_priv (%d)\n", err);
brcmf_free_vif(vif);
goto wiphy_out;
}
ifp->vif = vif;
/* determine d11 io type before wiphy setup */
err = brcmf_fil_cmd_int_get(ifp, BRCMF_C_GET_VERSION, &io_type);
if (err) {
brcmf_err("Failed to get D11 version (%d)\n", err);
goto priv_out;
}
cfg->d11inf.io_type = (u8)io_type;
brcmu_d11_attach(&cfg->d11inf);
err = brcmf_setup_wiphy(wiphy, ifp);
if (err < 0)
goto priv_out;
brcmf_dbg(INFO, "Registering custom regulatory\n");
wiphy->reg_notifier = brcmf_cfg80211_reg_notifier;
wiphy->regulatory_flags |= REGULATORY_CUSTOM_REG;
wiphy_apply_custom_regulatory(wiphy, &brcmf_regdom);
/* firmware defaults to 40MHz disabled in 2G band. We signal
* cfg80211 here that we do and have it decide we can enable
* it. But first check if device does support 2G operation.
*/
if (wiphy->bands[NL80211_BAND_2GHZ]) {
cap = &wiphy->bands[NL80211_BAND_2GHZ]->ht_cap.cap;
*cap |= IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
err = wiphy_register(wiphy);
if (err < 0) {
brcmf_err("Could not register wiphy device (%d)\n", err);
goto priv_out;
}
err = brcmf_setup_wiphybands(wiphy);
if (err) {
brcmf_err("Setting wiphy bands failed (%d)\n", err);
goto wiphy_unreg_out;
}
/* If cfg80211 didn't disable 40MHz HT CAP in wiphy_register(),
* setup 40MHz in 2GHz band and enable OBSS scanning.
*/
if (cap && (*cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40)) {
err = brcmf_enable_bw40_2g(cfg);
if (!err)
err = brcmf_fil_iovar_int_set(ifp, "obss_coex",
BRCMF_OBSS_COEX_AUTO);
else
*cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
}
/* p2p might require that "if-events" get processed by fweh. So
* activate the already registered event handlers now and activate
* the rest when initialization has completed. drvr->config needs to
* be assigned before activating events.
*/
drvr->config = cfg;
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_p2p_attach(cfg, p2pdev_forced);
if (err) {
brcmf_err("P2P initialisation failed (%d)\n", err);
goto wiphy_unreg_out;
}
err = brcmf_btcoex_attach(cfg);
if (err) {
brcmf_err("BT-coex initialisation failed (%d)\n", err);
brcmf_p2p_detach(&cfg->p2p);
goto wiphy_unreg_out;
}
err = brcmf_pno_attach(cfg);
if (err) {
brcmf_err("PNO initialisation failed (%d)\n", err);
brcmf_btcoex_detach(cfg);
brcmf_p2p_detach(&cfg->p2p);
goto wiphy_unreg_out;
}
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_TDLS)) {
err = brcmf_fil_iovar_int_set(ifp, "tdls_enable", 1);
if (err) {
brcmf_dbg(INFO, "TDLS not enabled (%d)\n", err);
wiphy->flags &= ~WIPHY_FLAG_SUPPORTS_TDLS;
} else {
brcmf_fweh_register(cfg->pub, BRCMF_E_TDLS_PEER_EVENT,
brcmf_notify_tdls_peer_event);
}
}
/* (re-) activate FWEH event handling */
err = brcmf_fweh_activate_events(ifp);
if (err) {
brcmf_err("FWEH activation failed (%d)\n", err);
goto detach;
}
/* Fill in some of the advertised nl80211 supported features */
if (brcmf_feat_is_enabled(ifp, BRCMF_FEAT_SCAN_RANDOM_MAC)) {
wiphy->features |= NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR;
#ifdef CONFIG_PM
if (wiphy->wowlan &&
wiphy->wowlan->flags & WIPHY_WOWLAN_NET_DETECT)
wiphy->features |= NL80211_FEATURE_ND_RANDOM_MAC_ADDR;
#endif
}
return cfg;
detach:
brcmf_pno_detach(cfg);
brcmf_btcoex_detach(cfg);
brcmf_p2p_detach(&cfg->p2p);
wiphy_unreg_out:
wiphy_unregister(cfg->wiphy);
priv_out:
wl_deinit_priv(cfg);
brcmf_free_vif(vif);
ifp->vif = NULL;
wiphy_out:
brcmf_free_wiphy(wiphy);
ops_out:
kfree(ops);
return NULL;
}
void brcmf_cfg80211_detach(struct brcmf_cfg80211_info *cfg)
{
if (!cfg)
return;
brcmf_pno_detach(cfg);
brcmf_btcoex_detach(cfg);
wiphy_unregister(cfg->wiphy);
kfree(cfg->ops);
wl_deinit_priv(cfg);
brcmf_free_wiphy(cfg->wiphy);
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3277_0 |
crossvul-cpp_data_good_4787_3 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% AAA V V SSSSS %
% A A V V SS %
% AAAAA V V SSS %
% A A V V SS %
% A A V SSSSS %
% %
% %
% Read/Write AVS X 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/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/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"
/*
Forward declarations.
*/
static MagickBooleanType
WriteAVSImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d A V S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadAVSImage() reads an AVS X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadAVSImage method is:
%
% Image *ReadAVSImage(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 *ReadAVSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
register PixelPacket
*q;
register ssize_t
x;
register unsigned char
*p;
size_t
height,
width;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read AVS X image.
*/
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((width == 0UL) || (height == 0UL))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
ssize_t
length;
/*
Convert AVS raster image to pixel packets.
*/
image->columns=width;
image->rows=height;
image->depth=8;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
length=(size_t) 4*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
count=ReadBlob(image,length,pixels);
if (count != length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (q->opacity != OpaqueOpacity)
image->matte=MagickTrue;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(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;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
if ((width != 0UL) && (height != 0UL))
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while ((width != 0UL) && (height != 0UL));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r A V S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterAVSImage() adds attributes for the AVS X 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 RegisterAVSImage method is:
%
% size_t RegisterAVSImage(void)
%
*/
ModuleExport size_t RegisterAVSImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("AVS");
entry->decoder=(DecodeImageHandler *) ReadAVSImage;
entry->encoder=(EncodeImageHandler *) WriteAVSImage;
entry->description=ConstantString("AVS X image");
entry->module=ConstantString("AVS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r A V S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterAVSImage() removes format registrations made by the
% AVS module from the list of supported formats.
%
% The format of the UnregisterAVSImage method is:
%
% UnregisterAVSImage(void)
%
*/
ModuleExport void UnregisterAVSImage(void)
{
(void) UnregisterMagickInfo("AVS");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e A V S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteAVSImage() writes an image to a file in AVS X image format.
%
% The format of the WriteAVSImage method is:
%
% MagickBooleanType WriteAVSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteAVSImage(const ImageInfo *image_info,Image *image)
{
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*restrict p;
register ssize_t
x;
register unsigned char
*restrict q;
ssize_t
count,
y;
unsigned char
*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);
scene=0;
do
{
/*
Write AVS header.
*/
(void) TransformImageColorspace(image,sRGBColorspace);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
/*
Allocate memory for pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert MIFF to AVS raster pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar((Quantum) (QuantumRange-(image->matte !=
MagickFalse ? GetPixelOpacity(p) : OpaqueOpacity)));
*q++=ScaleQuantumToChar(GetPixelRed(p));
*q++=ScaleQuantumToChar(GetPixelGreen(p));
*q++=ScaleQuantumToChar(GetPixelBlue(p));
p++;
}
count=WriteBlob(image,(size_t) (q-pixels),pixels);
if (count != (ssize_t) (q-pixels))
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
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_4787_3 |
crossvul-cpp_data_bad_2038_1 | /*-
* Copyright (c) 2008 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: readcdf.c,v 1.39 2014/02/27 23:26:18 christos Exp $")
#endif
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#if defined(HAVE_LOCALE_H)
#include <locale.h>
#endif
#include "cdf.h"
#include "magic.h"
#define NOTMIME(ms) (((ms)->flags & MAGIC_MIME) == 0)
static const struct nv {
const char *pattern;
const char *mime;
} app2mime[] = {
{ "Word", "msword", },
{ "Excel", "vnd.ms-excel", },
{ "Powerpoint", "vnd.ms-powerpoint", },
{ "Crystal Reports", "x-rpt", },
{ "Advanced Installer", "vnd.ms-msi", },
{ "InstallShield", "vnd.ms-msi", },
{ "Microsoft Patch Compiler", "vnd.ms-msi", },
{ "NAnt", "vnd.ms-msi", },
{ "Windows Installer", "vnd.ms-msi", },
{ NULL, NULL, },
}, name2mime[] = {
{ "WordDocument", "msword", },
{ "PowerPoint", "vnd.ms-powerpoint", },
{ "DigitalSignature", "vnd.ms-msi", },
{ NULL, NULL, },
}, name2desc[] = {
{ "WordDocument", "Microsoft Office Word",},
{ "PowerPoint", "Microsoft PowerPoint", },
{ "DigitalSignature", "Microsoft Installer", },
{ NULL, NULL, },
};
static const struct cv {
uint64_t clsid[2];
const char *mime;
} clsid2mime[] = {
{
{ 0x00000000000c1084LLU, 0x46000000000000c0LLU },
"x-msi",
}
}, clsid2desc[] = {
{
{ 0x00000000000c1084LLU, 0x46000000000000c0LLU },
"MSI Installer",
},
};
private const char *
cdf_clsid_to_mime(const uint64_t clsid[2], const struct cv *cv)
{
size_t i;
for (i = 0; cv[i].mime != NULL; i++) {
if (clsid[0] == cv[i].clsid[0] && clsid[1] == cv[i].clsid[1])
return cv[i].mime;
}
return NULL;
}
private const char *
cdf_app_to_mime(const char *vbuf, const struct nv *nv)
{
size_t i;
const char *rv = NULL;
char *old_lc_ctype;
old_lc_ctype = setlocale(LC_CTYPE, NULL);
assert(old_lc_ctype != NULL);
old_lc_ctype = strdup(old_lc_ctype);
assert(old_lc_ctype != NULL);
(void)setlocale(LC_CTYPE, "C");
for (i = 0; nv[i].pattern != NULL; i++)
if (strcasestr(vbuf, nv[i].pattern) != NULL) {
rv = nv[i].mime;
break;
}
(void)setlocale(LC_CTYPE, old_lc_ctype);
free(old_lc_ctype);
return rv;
}
private int
cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info,
size_t count, const uint64_t clsid[2])
{
size_t i;
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
const char *str = NULL;
const char *s;
int len;
if (!NOTMIME(ms))
str = cdf_clsid_to_mime(clsid, clsid2mime);
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
if (NOTMIME(ms) && file_printf(ms, ", %s: %hd", buf,
info[i].pi_s16) == -1)
return -1;
break;
case CDF_SIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %d", buf,
info[i].pi_s32) == -1)
return -1;
break;
case CDF_UNSIGNED32:
if (NOTMIME(ms) && file_printf(ms, ", %s: %u", buf,
info[i].pi_u32) == -1)
return -1;
break;
case CDF_FLOAT:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_f) == -1)
return -1;
break;
case CDF_DOUBLE:
if (NOTMIME(ms) && file_printf(ms, ", %s: %g", buf,
info[i].pi_d) == -1)
return -1;
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
len = info[i].pi_str.s_len;
if (len > 1) {
char vbuf[1024];
size_t j, k = 1;
if (info[i].pi_type == CDF_LENGTH32_WSTRING)
k++;
s = info[i].pi_str.s_buf;
for (j = 0; j < sizeof(vbuf) && len--;
j++, s += k) {
if (*s == '\0')
break;
if (isprint((unsigned char)*s))
vbuf[j] = *s;
}
if (j == sizeof(vbuf))
--j;
vbuf[j] = '\0';
if (NOTMIME(ms)) {
if (vbuf[0]) {
if (file_printf(ms, ", %s: %s",
buf, vbuf) == -1)
return -1;
}
} else if (str == NULL && info[i].pi_id ==
CDF_PROPERTY_NAME_OF_APPLICATION) {
str = cdf_app_to_mime(vbuf, app2mime);
}
}
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp != 0) {
char tbuf[64];
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(tbuf,
sizeof(tbuf), tp);
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, tbuf) == -1)
return -1;
} else {
char *c, *ec;
cdf_timestamp_to_timespec(&ts, tp);
c = cdf_ctime(&ts.tv_sec, tbuf);
if (c != NULL &&
(ec = strchr(c, '\n')) != NULL)
*ec = '\0';
if (NOTMIME(ms) && file_printf(ms,
", %s: %s", buf, c) == -1)
return -1;
}
}
break;
case CDF_CLIPBOARD:
break;
default:
return -1;
}
}
if (!NOTMIME(ms)) {
if (str == NULL)
return 0;
if (file_printf(ms, "application/%s", str) == -1)
return -1;
}
return 1;
}
private int
cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h,
const cdf_stream_t *sst, const uint64_t clsid[2])
{
cdf_summary_info_header_t si;
cdf_property_info_t *info;
size_t count;
int m;
if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1)
return -1;
if (NOTMIME(ms)) {
const char *str;
if (file_printf(ms, "Composite Document File V2 Document")
== -1)
return -1;
if (file_printf(ms, ", %s Endian",
si.si_byte_order == 0xfffe ? "Little" : "Big") == -1)
return -2;
switch (si.si_os) {
case 2:
if (file_printf(ms, ", Os: Windows, Version %d.%d",
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
case 1:
if (file_printf(ms, ", Os: MacOS, Version %d.%d",
(uint32_t)si.si_os_version >> 8,
si.si_os_version & 0xff) == -1)
return -2;
break;
default:
if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os,
si.si_os_version & 0xff,
(uint32_t)si.si_os_version >> 8) == -1)
return -2;
break;
}
str = cdf_clsid_to_mime(clsid, clsid2desc);
if (str)
if (file_printf(ms, ", %s", str) == -1)
return -2;
}
m = cdf_file_property_info(ms, info, count, clsid);
free(info);
return m == -1 ? -2 : m;
}
#ifdef notdef
private char *
format_clsid(char *buf, size_t len, const uint64_t uuid[2]) {
snprintf(buf, len, "%.8" PRIx64 "-%.4" PRIx64 "-%.4" PRIx64 "-%.4"
PRIx64 "-%.12" PRIx64,
(uuid[0] >> 32) & (uint64_t)0x000000000ffffffffLLU,
(uuid[0] >> 16) & (uint64_t)0x0000000000000ffffLLU,
(uuid[0] >> 0) & (uint64_t)0x0000000000000ffffLLU,
(uuid[1] >> 48) & (uint64_t)0x0000000000000ffffLLU,
(uuid[1] >> 0) & (uint64_t)0x0000fffffffffffffLLU);
return buf;
}
#endif
protected int
file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
cdf_info_t info;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
int i;
const char *expn = "";
const char *corrupt = "corrupt: ";
info.i_fd = fd;
info.i_buf = buf;
info.i_len = nbytes;
if (ms->flags & MAGIC_APPLE)
return 0;
if (cdf_read_header(&info, &h) == -1)
return 0;
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if ((i = cdf_read_sat(&info, &h, &sat)) == -1) {
expn = "Can't read SAT";
goto out0;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) {
expn = "Can't read SSAT";
goto out1;
}
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) {
expn = "Can't read directory";
goto out2;
}
const cdf_directory_t *root_storage;
if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst,
&root_storage)) == -1) {
expn = "Cannot read short stream";
goto out3;
}
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
#ifdef notdef
if (root_storage) {
if (NOTMIME(ms)) {
char clsbuf[128];
if (file_printf(ms, "CLSID %s, ",
format_clsid(clsbuf, sizeof(clsbuf),
root_storage->d_storage_uuid)) == -1)
return -1;
}
}
#endif
if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn)) == -1) {
if (errno == ESRCH) {
corrupt = expn;
expn = "No summary info";
} else {
expn = "Cannot read summary info";
}
goto out4;
}
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
if ((i = cdf_file_summary_info(ms, &h, &scn,
root_storage->d_storage_uuid)) < 0)
expn = "Can't expand summary_info";
if (i == 0) {
const char *str = NULL;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
size_t j, k;
for (j = 0; str == NULL && j < dir.dir_len; j++) {
d = &dir.dir_tab[j];
for (k = 0; k < sizeof(name); k++)
name[k] = (char)cdf_tole2(d->d_name[k]);
str = cdf_app_to_mime(name,
NOTMIME(ms) ? name2desc : name2mime);
}
if (NOTMIME(ms)) {
if (str != NULL) {
if (file_printf(ms, "%s", str) == -1)
return -1;
i = 1;
}
} else {
if (str == NULL)
str = "vnd.ms-office";
if (file_printf(ms, "application/%s", str) == -1)
return -1;
i = 1;
}
}
free(scn.sst_tab);
out4:
free(sst.sst_tab);
out3:
free(dir.dir_tab);
out2:
free(ssat.sat_tab);
out1:
free(sat.sat_tab);
out0:
if (i == -1) {
if (NOTMIME(ms)) {
if (file_printf(ms,
"Composite Document File V2 Document") == -1)
return -1;
if (*expn)
if (file_printf(ms, ", %s%s", corrupt, expn) == -1)
return -1;
} else {
if (file_printf(ms, "application/CDFV2-corrupt") == -1)
return -1;
}
i = 1;
}
return i;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2038_1 |
crossvul-cpp_data_bad_344_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_344_10 |
crossvul-cpp_data_bad_1579_0 | /*
* 8253/8254 interval timer emulation
*
* Copyright (c) 2003-2004 Fabrice Bellard
* Copyright (c) 2006 Intel Corporation
* Copyright (c) 2007 Keir Fraser, XenSource Inc
* Copyright (c) 2008 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Authors:
* Sheng Yang <sheng.yang@intel.com>
* Based on QEMU and Xen.
*/
#define pr_fmt(fmt) "pit: " fmt
#include <linux/kvm_host.h>
#include "irq.h"
#include "i8254.h"
#ifndef CONFIG_X86_64
#define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
#else
#define mod_64(x, y) ((x) % (y))
#endif
#define RW_STATE_LSB 1
#define RW_STATE_MSB 2
#define RW_STATE_WORD0 3
#define RW_STATE_WORD1 4
/* Compute with 96 bit intermediate result: (a*b)/c */
static u64 muldiv64(u64 a, u32 b, u32 c)
{
union {
u64 ll;
struct {
u32 low, high;
} l;
} u, res;
u64 rl, rh;
u.ll = a;
rl = (u64)u.l.low * (u64)b;
rh = (u64)u.l.high * (u64)b;
rh += (rl >> 32);
res.l.high = div64_u64(rh, c);
res.l.low = div64_u64(((mod_64(rh, c) << 32) + (rl & 0xffffffff)), c);
return res.ll;
}
static void pit_set_gate(struct kvm *kvm, int channel, u32 val)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
switch (c->mode) {
default:
case 0:
case 4:
/* XXX: just disable/enable counting */
break;
case 1:
case 2:
case 3:
case 5:
/* Restart counting on rising edge. */
if (c->gate < val)
c->count_load_time = ktime_get();
break;
}
c->gate = val;
}
static int pit_get_gate(struct kvm *kvm, int channel)
{
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
return kvm->arch.vpit->pit_state.channels[channel].gate;
}
static s64 __kpit_elapsed(struct kvm *kvm)
{
s64 elapsed;
ktime_t remaining;
struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
if (!ps->pit_timer.period)
return 0;
/*
* The Counter does not stop when it reaches zero. In
* Modes 0, 1, 4, and 5 the Counter ``wraps around'' to
* the highest count, either FFFF hex for binary counting
* or 9999 for BCD counting, and continues counting.
* Modes 2 and 3 are periodic; the Counter reloads
* itself with the initial count and continues counting
* from there.
*/
remaining = hrtimer_get_remaining(&ps->pit_timer.timer);
elapsed = ps->pit_timer.period - ktime_to_ns(remaining);
elapsed = mod_64(elapsed, ps->pit_timer.period);
return elapsed;
}
static s64 kpit_elapsed(struct kvm *kvm, struct kvm_kpit_channel_state *c,
int channel)
{
if (channel == 0)
return __kpit_elapsed(kvm);
return ktime_to_ns(ktime_sub(ktime_get(), c->count_load_time));
}
static int pit_get_count(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
s64 d, t;
int counter;
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
t = kpit_elapsed(kvm, c, channel);
d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
switch (c->mode) {
case 0:
case 1:
case 4:
case 5:
counter = (c->count - d) & 0xffff;
break;
case 3:
/* XXX: may be incorrect for odd counts */
counter = c->count - (mod_64((2 * d), c->count));
break;
default:
counter = c->count - mod_64(d, c->count);
break;
}
return counter;
}
static int pit_get_out(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
s64 d, t;
int out;
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
t = kpit_elapsed(kvm, c, channel);
d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
switch (c->mode) {
default:
case 0:
out = (d >= c->count);
break;
case 1:
out = (d < c->count);
break;
case 2:
out = ((mod_64(d, c->count) == 0) && (d != 0));
break;
case 3:
out = (mod_64(d, c->count) < ((c->count + 1) >> 1));
break;
case 4:
case 5:
out = (d == c->count);
break;
}
return out;
}
static void pit_latch_count(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
if (!c->count_latched) {
c->latched_count = pit_get_count(kvm, channel);
c->count_latched = c->rw_mode;
}
}
static void pit_latch_status(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
if (!c->status_latched) {
/* TODO: Return NULL COUNT (bit 6). */
c->status = ((pit_get_out(kvm, channel) << 7) |
(c->rw_mode << 4) |
(c->mode << 1) |
c->bcd);
c->status_latched = 1;
}
}
int pit_has_pending_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
if (pit && kvm_vcpu_is_bsp(vcpu) && pit->pit_state.irq_ack)
return atomic_read(&pit->pit_state.pit_timer.pending);
return 0;
}
static void kvm_pit_ack_irq(struct kvm_irq_ack_notifier *kian)
{
struct kvm_kpit_state *ps = container_of(kian, struct kvm_kpit_state,
irq_ack_notifier);
spin_lock(&ps->inject_lock);
if (atomic_dec_return(&ps->pit_timer.pending) < 0)
atomic_inc(&ps->pit_timer.pending);
ps->irq_ack = 1;
spin_unlock(&ps->inject_lock);
}
void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct hrtimer *timer;
if (!kvm_vcpu_is_bsp(vcpu) || !pit)
return;
timer = &pit->pit_state.pit_timer.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
static void destroy_pit_timer(struct kvm_timer *pt)
{
pr_debug("execute del timer!\n");
hrtimer_cancel(&pt->timer);
}
static bool kpit_is_periodic(struct kvm_timer *ktimer)
{
struct kvm_kpit_state *ps = container_of(ktimer, struct kvm_kpit_state,
pit_timer);
return ps->is_periodic;
}
static struct kvm_timer_ops kpit_ops = {
.is_periodic = kpit_is_periodic,
};
static void create_pit_timer(struct kvm_kpit_state *ps, u32 val, int is_period)
{
struct kvm_timer *pt = &ps->pit_timer;
s64 interval;
interval = muldiv64(val, NSEC_PER_SEC, KVM_PIT_FREQ);
pr_debug("create pit timer, interval is %llu nsec\n", interval);
/* TODO The new value only affected after the retriggered */
hrtimer_cancel(&pt->timer);
pt->period = interval;
ps->is_periodic = is_period;
pt->timer.function = kvm_timer_fn;
pt->t_ops = &kpit_ops;
pt->kvm = ps->pit->kvm;
pt->vcpu = pt->kvm->bsp_vcpu;
atomic_set(&pt->pending, 0);
ps->irq_ack = 1;
hrtimer_start(&pt->timer, ktime_add_ns(ktime_get(), interval),
HRTIMER_MODE_ABS);
}
static void pit_load_count(struct kvm *kvm, int channel, u32 val)
{
struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
WARN_ON(!mutex_is_locked(&ps->lock));
pr_debug("load_count val is %d, channel is %d\n", val, channel);
/*
* The largest possible initial count is 0; this is equivalent
* to 216 for binary counting and 104 for BCD counting.
*/
if (val == 0)
val = 0x10000;
ps->channels[channel].count = val;
if (channel != 0) {
ps->channels[channel].count_load_time = ktime_get();
return;
}
/* Two types of timer
* mode 1 is one shot, mode 2 is period, otherwise del timer */
switch (ps->channels[0].mode) {
case 0:
case 1:
/* FIXME: enhance mode 4 precision */
case 4:
if (!(ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)) {
create_pit_timer(ps, val, 0);
}
break;
case 2:
case 3:
if (!(ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)){
create_pit_timer(ps, val, 1);
}
break;
default:
destroy_pit_timer(&ps->pit_timer);
}
}
void kvm_pit_load_count(struct kvm *kvm, int channel, u32 val, int hpet_legacy_start)
{
u8 saved_mode;
if (hpet_legacy_start) {
/* save existing mode for later reenablement */
saved_mode = kvm->arch.vpit->pit_state.channels[0].mode;
kvm->arch.vpit->pit_state.channels[0].mode = 0xff; /* disable timer */
pit_load_count(kvm, channel, val);
kvm->arch.vpit->pit_state.channels[0].mode = saved_mode;
} else {
pit_load_count(kvm, channel, val);
}
}
static inline struct kvm_pit *dev_to_pit(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_pit, dev);
}
static inline struct kvm_pit *speaker_to_pit(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_pit, speaker_dev);
}
static inline int pit_in_range(gpa_t addr)
{
return ((addr >= KVM_PIT_BASE_ADDRESS) &&
(addr < KVM_PIT_BASE_ADDRESS + KVM_PIT_MEM_LENGTH));
}
static int pit_ioport_write(struct kvm_io_device *this,
gpa_t addr, int len, const void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int channel, access;
struct kvm_kpit_channel_state *s;
u32 val = *(u32 *) data;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
val &= 0xff;
addr &= KVM_PIT_CHANNEL_MASK;
mutex_lock(&pit_state->lock);
if (val != 0)
pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n",
(unsigned int)addr, len, val);
if (addr == 3) {
channel = val >> 6;
if (channel == 3) {
/* Read-Back Command. */
for (channel = 0; channel < 3; channel++) {
s = &pit_state->channels[channel];
if (val & (2 << channel)) {
if (!(val & 0x20))
pit_latch_count(kvm, channel);
if (!(val & 0x10))
pit_latch_status(kvm, channel);
}
}
} else {
/* Select Counter <channel>. */
s = &pit_state->channels[channel];
access = (val >> 4) & KVM_PIT_CHANNEL_MASK;
if (access == 0) {
pit_latch_count(kvm, channel);
} else {
s->rw_mode = access;
s->read_state = access;
s->write_state = access;
s->mode = (val >> 1) & 7;
if (s->mode > 5)
s->mode -= 4;
s->bcd = val & 1;
}
}
} else {
/* Write Count. */
s = &pit_state->channels[addr];
switch (s->write_state) {
default:
case RW_STATE_LSB:
pit_load_count(kvm, addr, val);
break;
case RW_STATE_MSB:
pit_load_count(kvm, addr, val << 8);
break;
case RW_STATE_WORD0:
s->write_latch = val;
s->write_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
pit_load_count(kvm, addr, s->write_latch | (val << 8));
s->write_state = RW_STATE_WORD0;
break;
}
}
mutex_unlock(&pit_state->lock);
return 0;
}
static int pit_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int ret, count;
struct kvm_kpit_channel_state *s;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
addr &= KVM_PIT_CHANNEL_MASK;
s = &pit_state->channels[addr];
mutex_lock(&pit_state->lock);
if (s->status_latched) {
s->status_latched = 0;
ret = s->status;
} else if (s->count_latched) {
switch (s->count_latched) {
default:
case RW_STATE_LSB:
ret = s->latched_count & 0xff;
s->count_latched = 0;
break;
case RW_STATE_MSB:
ret = s->latched_count >> 8;
s->count_latched = 0;
break;
case RW_STATE_WORD0:
ret = s->latched_count & 0xff;
s->count_latched = RW_STATE_MSB;
break;
}
} else {
switch (s->read_state) {
default:
case RW_STATE_LSB:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
break;
case RW_STATE_MSB:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
break;
case RW_STATE_WORD0:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
s->read_state = RW_STATE_WORD0;
break;
}
}
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
static int speaker_ioport_write(struct kvm_io_device *this,
gpa_t addr, int len, const void *data)
{
struct kvm_pit *pit = speaker_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
u32 val = *(u32 *) data;
if (addr != KVM_SPEAKER_BASE_ADDRESS)
return -EOPNOTSUPP;
mutex_lock(&pit_state->lock);
pit_state->speaker_data_on = (val >> 1) & 1;
pit_set_gate(kvm, 2, val & 1);
mutex_unlock(&pit_state->lock);
return 0;
}
static int speaker_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = speaker_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
unsigned int refresh_clock;
int ret;
if (addr != KVM_SPEAKER_BASE_ADDRESS)
return -EOPNOTSUPP;
/* Refresh clock toggles at about 15us. We approximate as 2^14ns. */
refresh_clock = ((unsigned int)ktime_to_ns(ktime_get()) >> 14) & 1;
mutex_lock(&pit_state->lock);
ret = ((pit_state->speaker_data_on << 1) | pit_get_gate(kvm, 2) |
(pit_get_out(kvm, 2) << 5) | (refresh_clock << 4));
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
void kvm_pit_reset(struct kvm_pit *pit)
{
int i;
struct kvm_kpit_channel_state *c;
mutex_lock(&pit->pit_state.lock);
pit->pit_state.flags = 0;
for (i = 0; i < 3; i++) {
c = &pit->pit_state.channels[i];
c->mode = 0xff;
c->gate = (i != 2);
pit_load_count(pit->kvm, i, 0);
}
mutex_unlock(&pit->pit_state.lock);
atomic_set(&pit->pit_state.pit_timer.pending, 0);
pit->pit_state.irq_ack = 1;
}
static void pit_mask_notifer(struct kvm_irq_mask_notifier *kimn, bool mask)
{
struct kvm_pit *pit = container_of(kimn, struct kvm_pit, mask_notifier);
if (!mask) {
atomic_set(&pit->pit_state.pit_timer.pending, 0);
pit->pit_state.irq_ack = 1;
}
}
static const struct kvm_io_device_ops pit_dev_ops = {
.read = pit_ioport_read,
.write = pit_ioport_write,
};
static const struct kvm_io_device_ops speaker_dev_ops = {
.read = speaker_ioport_read,
.write = speaker_ioport_write,
};
/* Caller must have writers lock on slots_lock */
struct kvm_pit *kvm_create_pit(struct kvm *kvm, u32 flags)
{
struct kvm_pit *pit;
struct kvm_kpit_state *pit_state;
int ret;
pit = kzalloc(sizeof(struct kvm_pit), GFP_KERNEL);
if (!pit)
return NULL;
pit->irq_source_id = kvm_request_irq_source_id(kvm);
if (pit->irq_source_id < 0) {
kfree(pit);
return NULL;
}
mutex_init(&pit->pit_state.lock);
mutex_lock(&pit->pit_state.lock);
spin_lock_init(&pit->pit_state.inject_lock);
kvm->arch.vpit = pit;
pit->kvm = kvm;
pit_state = &pit->pit_state;
pit_state->pit = pit;
hrtimer_init(&pit_state->pit_timer.timer,
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
pit_state->irq_ack_notifier.gsi = 0;
pit_state->irq_ack_notifier.irq_acked = kvm_pit_ack_irq;
kvm_register_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier);
pit_state->pit_timer.reinject = true;
mutex_unlock(&pit->pit_state.lock);
kvm_pit_reset(pit);
pit->mask_notifier.func = pit_mask_notifer;
kvm_register_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
kvm_iodevice_init(&pit->dev, &pit_dev_ops);
ret = __kvm_io_bus_register_dev(&kvm->pio_bus, &pit->dev);
if (ret < 0)
goto fail;
if (flags & KVM_PIT_SPEAKER_DUMMY) {
kvm_iodevice_init(&pit->speaker_dev, &speaker_dev_ops);
ret = __kvm_io_bus_register_dev(&kvm->pio_bus,
&pit->speaker_dev);
if (ret < 0)
goto fail_unregister;
}
return pit;
fail_unregister:
__kvm_io_bus_unregister_dev(&kvm->pio_bus, &pit->dev);
fail:
if (pit->irq_source_id >= 0)
kvm_free_irq_source_id(kvm, pit->irq_source_id);
kfree(pit);
return NULL;
}
void kvm_free_pit(struct kvm *kvm)
{
struct hrtimer *timer;
if (kvm->arch.vpit) {
kvm_unregister_irq_mask_notifier(kvm, 0,
&kvm->arch.vpit->mask_notifier);
kvm_unregister_irq_ack_notifier(kvm,
&kvm->arch.vpit->pit_state.irq_ack_notifier);
mutex_lock(&kvm->arch.vpit->pit_state.lock);
timer = &kvm->arch.vpit->pit_state.pit_timer.timer;
hrtimer_cancel(timer);
kvm_free_irq_source_id(kvm, kvm->arch.vpit->irq_source_id);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
kfree(kvm->arch.vpit);
}
}
static void __inject_pit_timer_intr(struct kvm *kvm)
{
struct kvm_vcpu *vcpu;
int i;
kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 1);
kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 0);
/*
* Provides NMI watchdog support via Virtual Wire mode.
* The route is: PIT -> PIC -> LVT0 in NMI mode.
*
* Note: Our Virtual Wire implementation is simplified, only
* propagating PIT interrupts to all VCPUs when they have set
* LVT0 to NMI delivery. Other PIC interrupts are just sent to
* VCPU0, and only if its LVT0 is in EXTINT mode.
*/
if (kvm->arch.vapics_in_nmi_mode > 0)
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_apic_nmi_wd_deliver(vcpu);
}
void kvm_inject_pit_timer_irqs(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct kvm *kvm = vcpu->kvm;
struct kvm_kpit_state *ps;
if (pit) {
int inject = 0;
ps = &pit->pit_state;
/* Try to inject pending interrupts when
* last one has been acked.
*/
spin_lock(&ps->inject_lock);
if (atomic_read(&ps->pit_timer.pending) && ps->irq_ack) {
ps->irq_ack = 0;
inject = 1;
}
spin_unlock(&ps->inject_lock);
if (inject)
__inject_pit_timer_intr(kvm);
}
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1579_0 |
crossvul-cpp_data_good_1359_3 | /**
* @file tree_schema.c
* @author Radek Krejci <rkrejci@cesnet.cz>
* @brief Manipulation with libyang schema data structures
*
* 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
#ifdef __APPLE__
# include <sys/param.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include "common.h"
#include "context.h"
#include "parser.h"
#include "resolve.h"
#include "xml.h"
#include "xpath.h"
#include "xml_internal.h"
#include "tree_internal.h"
#include "validation.h"
#include "parser_yang.h"
static int lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
int in_grp, int shallow, struct unres_schema *unres);
API const struct lys_node_list *
lys_is_key(const struct lys_node_leaf *node, uint8_t *index)
{
struct lys_node *parent = (struct lys_node *)node;
struct lys_node_list *list;
uint8_t i;
if (!node || node->nodetype != LYS_LEAF) {
return NULL;
}
do {
parent = lys_parent(parent);
} while (parent && parent->nodetype == LYS_USES);
if (!parent || parent->nodetype != LYS_LIST) {
return NULL;
}
list = (struct lys_node_list*)parent;
for (i = 0; i < list->keys_size; i++) {
if (list->keys[i] == node) {
if (index) {
(*index) = i;
}
return list;
}
}
return NULL;
}
API const struct lys_node *
lys_is_disabled(const struct lys_node *node, int recursive)
{
int i;
if (!node) {
return NULL;
}
check:
if (node->nodetype != LYS_INPUT && node->nodetype != LYS_OUTPUT) {
/* input/output does not have if-feature, so skip them */
/* check local if-features */
for (i = 0; i < node->iffeature_size; i++) {
if (!resolve_iffeature(&node->iffeature[i])) {
return node;
}
}
}
if (!recursive) {
return NULL;
}
/* go through parents */
if (node->nodetype == LYS_AUGMENT) {
/* go to parent actually means go to the target node */
node = ((struct lys_node_augment *)node)->target;
if (!node) {
/* unresolved augment, let's say it's enabled */
return NULL;
}
} else if (node->nodetype == LYS_EXT) {
return NULL;
} else if (node->parent) {
node = node->parent;
} else {
return NULL;
}
if (recursive == 2) {
/* continue only if the node cannot have a data instance */
if (node->nodetype & (LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST)) {
return NULL;
}
}
goto check;
}
API const struct lys_type *
lys_getnext_union_type(const struct lys_type *last, const struct lys_type *type)
{
int found = 0;
if (!type || (type->base != LY_TYPE_UNION)) {
return NULL;
}
return lyp_get_next_union_type((struct lys_type *)type, (struct lys_type *)last, &found);
}
int
lys_get_sibling(const struct lys_node *siblings, const char *mod_name, int mod_name_len, const char *name,
int nam_len, LYS_NODE type, const struct lys_node **ret)
{
const struct lys_node *node, *parent = NULL;
const struct lys_module *mod = NULL;
const char *node_mod_name;
assert(siblings && mod_name && name);
assert(!(type & (LYS_USES | LYS_GROUPING)));
/* fill the lengths in case the caller is so indifferent */
if (!mod_name_len) {
mod_name_len = strlen(mod_name);
}
if (!nam_len) {
nam_len = strlen(name);
}
while (siblings && (siblings->nodetype == LYS_USES)) {
siblings = siblings->child;
}
if (!siblings) {
/* unresolved uses */
return EXIT_FAILURE;
}
if (siblings->nodetype == LYS_GROUPING) {
for (node = siblings; (node->nodetype == LYS_GROUPING) && (node->prev != siblings); node = node->prev);
if (node->nodetype == LYS_GROUPING) {
/* we went through all the siblings, only groupings there - no valid sibling */
return EXIT_FAILURE;
}
/* update siblings to be valid */
siblings = node;
}
/* set parent correctly */
parent = lys_parent(siblings);
/* go up all uses */
while (parent && (parent->nodetype == LYS_USES)) {
parent = lys_parent(parent);
}
if (!parent) {
/* handle situation when there is a top-level uses referencing a foreign grouping */
for (node = siblings; lys_parent(node) && (node->nodetype == LYS_USES); node = lys_parent(node));
mod = lys_node_module(node);
}
/* try to find the node */
node = NULL;
while ((node = lys_getnext(node, parent, mod, LYS_GETNEXT_WITHCHOICE | LYS_GETNEXT_WITHCASE | LYS_GETNEXT_WITHINOUT))) {
if (!type || (node->nodetype & type)) {
/* module name comparison */
node_mod_name = lys_node_module(node)->name;
if (!ly_strequal(node_mod_name, mod_name, 1) && (strncmp(node_mod_name, mod_name, mod_name_len) || node_mod_name[mod_name_len])) {
continue;
}
/* direct name check */
if (ly_strequal(node->name, name, 1) || (!strncmp(node->name, name, nam_len) && !node->name[nam_len])) {
if (ret) {
*ret = node;
}
return EXIT_SUCCESS;
}
}
}
return EXIT_FAILURE;
}
int
lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len,
LYS_NODE type, int getnext_opts, const struct lys_node **ret)
{
const struct lys_node *node;
assert((mod || parent) && name);
assert(!(type & (LYS_AUGMENT | LYS_USES | LYS_GROUPING | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT)));
if (!mod) {
mod = lys_node_module(parent);
}
/* try to find the node */
node = NULL;
while ((node = lys_getnext(node, parent, mod, getnext_opts))) {
if (!type || (node->nodetype & type)) {
/* module check */
if (lys_node_module(node) != lys_main_module(mod)) {
continue;
}
/* direct name check */
if (!strncmp(node->name, name, nam_len) && !node->name[nam_len]) {
if (ret) {
*ret = node;
}
return EXIT_SUCCESS;
}
}
}
return EXIT_FAILURE;
}
API const struct lys_node *
lys_getnext(const struct lys_node *last, const struct lys_node *parent, const struct lys_module *module, int options)
{
const struct lys_node *next, *aug_parent;
struct lys_node **snode;
if ((!parent && !module) || (module && module->type) || (parent && (parent->nodetype == LYS_USES) && !(options & LYS_GETNEXT_PARENTUSES))) {
LOGARG;
return NULL;
}
if (!last) {
/* first call */
/* get know where to start */
if (parent) {
/* schema subtree */
snode = lys_child(parent, LYS_UNKNOWN);
/* do not return anything if the augment does not have any children */
if (!snode || !(*snode) || ((parent->nodetype == LYS_AUGMENT) && ((*snode)->parent != parent))) {
return NULL;
}
next = last = *snode;
} else {
/* top level data */
if (!(options & LYS_GETNEXT_NOSTATECHECK) && (module->disabled || !module->implemented)) {
/* nothing to return from a disabled/imported module */
return NULL;
}
next = last = module->data;
}
} else if ((last->nodetype == LYS_USES) && (options & LYS_GETNEXT_INTOUSES) && last->child) {
/* continue with uses content */
next = last->child;
} else {
/* continue after the last returned value */
next = last->next;
}
repeat:
if (parent && (parent->nodetype == LYS_AUGMENT) && next) {
/* do not return anything outside the parent augment */
aug_parent = next->parent;
do {
while (aug_parent && (aug_parent->nodetype != LYS_AUGMENT)) {
aug_parent = aug_parent->parent;
}
if (aug_parent) {
if (aug_parent == parent) {
break;
}
aug_parent = ((struct lys_node_augment *)aug_parent)->target;
}
} while (aug_parent);
if (!aug_parent) {
return NULL;
}
}
while (next && (next->nodetype == LYS_GROUPING)) {
if (options & LYS_GETNEXT_WITHGROUPING) {
return next;
}
next = next->next;
}
if (!next) { /* cover case when parent is augment */
if (!last || last->parent == parent || lys_parent(last) == parent) {
/* no next element */
return NULL;
}
last = lys_parent(last);
next = last->next;
goto repeat;
} else {
last = next;
}
if (!(options & LYS_GETNEXT_NOSTATECHECK) && lys_is_disabled(next, 0)) {
next = next->next;
goto repeat;
}
switch (next->nodetype) {
case LYS_INPUT:
case LYS_OUTPUT:
if (options & LYS_GETNEXT_WITHINOUT) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_CASE:
if (options & LYS_GETNEXT_WITHCASE) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_USES:
/* go into */
if (options & LYS_GETNEXT_WITHUSES) {
return next;
} else if (next->child) {
next = next->child;
} else {
next = next->next;
}
goto repeat;
case LYS_RPC:
case LYS_ACTION:
case LYS_NOTIF:
case LYS_LEAF:
case LYS_ANYXML:
case LYS_ANYDATA:
case LYS_LIST:
case LYS_LEAFLIST:
return next;
case LYS_CONTAINER:
if (!((struct lys_node_container *)next)->presence && (options & LYS_GETNEXT_INTONPCONT)) {
if (next->child) {
/* go into */
next = next->child;
} else {
next = next->next;
}
goto repeat;
} else {
return next;
}
case LYS_CHOICE:
if (options & LYS_GETNEXT_WITHCHOICE) {
return next;
} else if (next->child) {
/* go into */
next = next->child;
} else {
next = next->next;
}
goto repeat;
default:
/* we should not be here */
return NULL;
}
}
void
lys_node_unlink(struct lys_node *node)
{
struct lys_node *parent, *first, **pp = NULL;
struct lys_module *main_module;
if (!node) {
return;
}
/* unlink from data model if necessary */
if (node->module) {
/* get main module with data tree */
main_module = lys_node_module(node);
if (main_module->data == node) {
main_module->data = node->next;
}
}
/* store pointers to important nodes */
parent = node->parent;
if (parent && (parent->nodetype == LYS_AUGMENT)) {
/* handle augments - first, unlink it from the augment parent ... */
if (parent->child == node) {
parent->child = (node->next && node->next->parent == parent) ? node->next : NULL;
}
if (parent->flags & LYS_NOTAPPLIED) {
/* data are not connected in the target, so we cannot continue with the target as a parent */
parent = NULL;
} else {
/* data are connected in target, so we will continue with the target as a parent */
parent = ((struct lys_node_augment *)parent)->target;
}
}
/* unlink from parent */
if (parent) {
if (parent->nodetype == LYS_EXT) {
pp = (struct lys_node **)lys_ext_complex_get_substmt(lys_snode2stmt(node->nodetype),
(struct lys_ext_instance_complex*)parent, NULL);
if (*pp == node) {
*pp = node->next;
}
} else if (parent->child == node) {
parent->child = node->next;
}
node->parent = NULL;
}
/* unlink from siblings */
if (node->prev == node) {
/* there are no more siblings */
return;
}
if (node->next) {
node->next->prev = node->prev;
} else {
/* unlinking the last element */
if (parent) {
if (parent->nodetype == LYS_EXT) {
first = *(struct lys_node **)pp;
} else {
first = parent->child;
}
} else {
first = node;
while (first->prev->next) {
first = first->prev;
}
}
first->prev = node->prev;
}
if (node->prev->next) {
node->prev->next = node->next;
}
/* clean up the unlinked element */
node->next = NULL;
node->prev = node;
}
struct lys_node_grp *
lys_find_grouping_up(const char *name, struct lys_node *start)
{
struct lys_node *par_iter, *iter, *stop;
for (par_iter = start; par_iter; par_iter = par_iter->parent) {
/* top-level augment, look into module (uses augment is handled correctly below) */
if (par_iter->parent && !par_iter->parent->parent && (par_iter->parent->nodetype == LYS_AUGMENT)) {
par_iter = lys_main_module(par_iter->parent->module)->data;
if (!par_iter) {
break;
}
}
if (par_iter->nodetype == LYS_EXT) {
/* we are in a top-level extension, search grouping in top-level groupings */
par_iter = lys_main_module(par_iter->module)->data;
if (!par_iter) {
/* not connected yet, wait */
return NULL;
}
} else if (par_iter->parent && (par_iter->parent->nodetype & (LYS_CHOICE | LYS_CASE | LYS_AUGMENT | LYS_USES))) {
continue;
}
for (iter = par_iter, stop = NULL; iter; iter = iter->prev) {
if (!stop) {
stop = par_iter;
} else if (iter == stop) {
break;
}
if (iter->nodetype != LYS_GROUPING) {
continue;
}
if (!strcmp(name, iter->name)) {
return (struct lys_node_grp *)iter;
}
}
}
return NULL;
}
/*
* get next grouping in the root's subtree, in the
* first call, tha last is NULL
*/
static struct lys_node_grp *
lys_get_next_grouping(struct lys_node_grp *lastgrp, struct lys_node *root)
{
struct lys_node *last = (struct lys_node *)lastgrp;
struct lys_node *next;
assert(root);
if (!last) {
last = root;
}
while (1) {
if ((last->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) {
next = last->child;
} else {
next = NULL;
}
if (!next) {
if (last == root) {
/* we are done */
return NULL;
}
/* no children, go to siblings */
next = last->next;
}
while (!next) {
/* go back through parents */
if (lys_parent(last) == root) {
/* we are done */
return NULL;
}
next = last->next;
last = lys_parent(last);
}
if (next->nodetype == LYS_GROUPING) {
return (struct lys_node_grp *)next;
}
last = next;
}
}
/* logs directly */
int
lys_check_id(struct lys_node *node, struct lys_node *parent, struct lys_module *module)
{
struct lys_node *start, *stop, *iter;
struct lys_node_grp *grp;
int down, up;
assert(node);
if (!parent) {
assert(module);
} else {
module = parent->module;
}
module = lys_main_module(module);
switch (node->nodetype) {
case LYS_GROUPING:
/* 6.2.1, rule 6 */
if (parent) {
start = *lys_child(parent, LYS_GROUPING);
if (!start) {
down = 0;
start = parent;
} else {
down = 1;
}
if (parent->nodetype == LYS_EXT) {
up = 0;
} else {
up = 1;
}
} else {
down = up = 1;
start = module->data;
}
/* go up */
if (up && lys_find_grouping_up(node->name, start)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "grouping", node->name);
return EXIT_FAILURE;
}
/* go down, because grouping can be defined after e.g. container in which is collision */
if (down) {
for (iter = start, stop = NULL; iter; iter = iter->prev) {
if (!stop) {
stop = start;
} else if (iter == stop) {
break;
}
if (!(iter->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LIST | LYS_GROUPING | LYS_INPUT | LYS_OUTPUT))) {
continue;
}
grp = NULL;
while ((grp = lys_get_next_grouping(grp, iter))) {
if (ly_strequal(node->name, grp->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID,LY_VLOG_LYS, node, "grouping", node->name);
return EXIT_FAILURE;
}
}
}
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_LIST:
case LYS_CONTAINER:
case LYS_CHOICE:
case LYS_ANYDATA:
/* 6.2.1, rule 7 */
if (parent) {
iter = parent;
while (iter && (iter->nodetype & (LYS_USES | LYS_CASE | LYS_CHOICE | LYS_AUGMENT))) {
if (iter->nodetype == LYS_AUGMENT) {
if (((struct lys_node_augment *)iter)->target) {
/* augment is resolved, go up */
iter = ((struct lys_node_augment *)iter)->target;
continue;
}
/* augment is not resolved, this is the final parent */
break;
}
iter = iter->parent;
}
if (!iter) {
stop = NULL;
iter = module->data;
} else if (iter->nodetype == LYS_EXT) {
stop = iter;
iter = (struct lys_node *)lys_child(iter, node->nodetype);
if (iter) {
iter = *(struct lys_node **)iter;
}
} else {
stop = iter;
iter = iter->child;
}
} else {
stop = NULL;
iter = module->data;
}
while (iter) {
if (iter->nodetype & (LYS_USES | LYS_CASE)) {
iter = iter->child;
continue;
}
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CONTAINER | LYS_CHOICE | LYS_ANYDATA)) {
if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, strnodetype(node->nodetype), node->name);
return EXIT_FAILURE;
}
}
/* special case for choice - we must check the choice's name as
* well as the names of nodes under the choice
*/
if (iter->nodetype == LYS_CHOICE) {
iter = iter->child;
continue;
}
/* go to siblings */
if (!iter->next) {
/* no sibling, go to parent's sibling */
do {
/* for parent LYS_AUGMENT */
if (iter->parent == stop) {
iter = stop;
break;
}
iter = lys_parent(iter);
if (iter && iter->next) {
break;
}
} while (iter != stop);
if (iter == stop) {
break;
}
}
iter = iter->next;
}
break;
case LYS_CASE:
/* 6.2.1, rule 8 */
if (parent) {
start = *lys_child(parent, LYS_CASE);
} else {
start = module->data;
}
LY_TREE_FOR(start, iter) {
if (!(iter->nodetype & (LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST))) {
continue;
}
if (iter->module == node->module && ly_strequal(iter->name, node->name, 1)) {
LOGVAL(module->ctx, LYE_DUPID, LY_VLOG_LYS, node, "case", node->name);
return EXIT_FAILURE;
}
}
break;
default:
/* no check needed */
break;
}
return EXIT_SUCCESS;
}
/* logs directly */
int
lys_node_addchild(struct lys_node *parent, struct lys_module *module, struct lys_node *child, int options)
{
struct ly_ctx *ctx = child->module->ctx;
struct lys_node *iter, **pchild, *log_parent;
struct lys_node_inout *in, *out;
struct lys_node_case *c;
int type, shortcase = 0;
void *p;
struct lyext_substmt *info = NULL;
assert(child);
if (parent) {
type = parent->nodetype;
module = parent->module;
log_parent = parent;
if (type == LYS_USES) {
/* we are adding children to uses -> we must be copying grouping contents into it, so properly check the parent */
log_parent = lys_parent(log_parent);
while (log_parent && (log_parent->nodetype == LYS_USES)) {
log_parent = lys_parent(log_parent);
}
if (log_parent) {
type = log_parent->nodetype;
} else {
type = 0;
}
}
} else {
assert(module);
assert(!(child->nodetype & (LYS_INPUT | LYS_OUTPUT)));
type = 0;
log_parent = NULL;
}
/* checks */
switch (type) {
case LYS_CONTAINER:
case LYS_LIST:
case LYS_GROUPING:
case LYS_USES:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF |
LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_INPUT:
case LYS_OUTPUT:
case LYS_NOTIF:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_GROUPING | LYS_LEAF |
LYS_LEAFLIST | LYS_LIST | LYS_USES))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_CHOICE:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_CHOICE))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "choice");
return EXIT_FAILURE;
}
if (child->nodetype != LYS_CASE) {
shortcase = 1;
}
break;
case LYS_CASE:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_USES))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "case");
return EXIT_FAILURE;
}
break;
case LYS_RPC:
case LYS_ACTION:
if (!(child->nodetype & (LYS_INPUT | LYS_OUTPUT | LYS_GROUPING))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "rpc");
return EXIT_FAILURE;
}
break;
case LYS_LEAF:
case LYS_LEAFLIST:
case LYS_ANYXML:
case LYS_ANYDATA:
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "The \"%s\" statement cannot have any data substatement.",
strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
case LYS_AUGMENT:
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CASE | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF
| LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_ACTION | LYS_NOTIF))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), strnodetype(log_parent->nodetype));
return EXIT_FAILURE;
}
break;
case LYS_UNKNOWN:
/* top level */
if (!(child->nodetype &
(LYS_ANYDATA | LYS_CHOICE | LYS_CONTAINER | LYS_LEAF | LYS_GROUPING
| LYS_LEAFLIST | LYS_LIST | LYS_USES | LYS_RPC | LYS_NOTIF | LYS_AUGMENT))) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype), "(sub)module");
return EXIT_FAILURE;
}
break;
case LYS_EXT:
/* plugin-defined */
p = lys_ext_complex_get_substmt(lys_snode2stmt(child->nodetype), (struct lys_ext_instance_complex*)log_parent, &info);
if (!p) {
LOGVAL(ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, log_parent, strnodetype(child->nodetype),
((struct lys_ext_instance_complex*)log_parent)->def->name);
return EXIT_FAILURE;
}
/* TODO check cardinality */
break;
}
/* check identifier uniqueness */
if (!(module->ctx->models.flags & LY_CTX_TRUSTED) && lys_check_id(child, parent, module)) {
return EXIT_FAILURE;
}
if (child->parent) {
lys_node_unlink(child);
}
if ((child->nodetype & (LYS_INPUT | LYS_OUTPUT)) && parent->nodetype != LYS_EXT) {
/* find the implicit input/output node */
LY_TREE_FOR(parent->child, iter) {
if (iter->nodetype == child->nodetype) {
break;
}
}
assert(iter);
/* switch the old implicit node (iter) with the new one (child) */
if (parent->child == iter) {
/* first child */
parent->child = child;
} else {
iter->prev->next = child;
}
child->prev = iter->prev;
child->next = iter->next;
if (iter->next) {
iter->next->prev = child;
} else {
/* last child */
parent->child->prev = child;
}
child->parent = parent;
/* isolate the node and free it */
iter->next = NULL;
iter->prev = iter;
iter->parent = NULL;
lys_node_free(iter, NULL, 0);
} else {
if (shortcase) {
/* create the implicit case to allow it to serve as a target of the augments,
* it won't be printed, but it will be present in the tree */
c = calloc(1, sizeof *c);
LY_CHECK_ERR_RETURN(!c, LOGMEM(ctx), EXIT_FAILURE);
c->name = lydict_insert(module->ctx, child->name, 0);
c->flags = LYS_IMPLICIT;
if (!(options & (LYS_PARSE_OPT_CFG_IGNORE | LYS_PARSE_OPT_CFG_NOINHERIT))) {
/* get config flag from parent */
c->flags |= parent->flags & LYS_CONFIG_MASK;
}
c->module = module;
c->nodetype = LYS_CASE;
c->prev = (struct lys_node*)c;
lys_node_addchild(parent, module, (struct lys_node*)c, options);
parent = (struct lys_node*)c;
}
/* connect the child correctly */
if (!parent) {
if (module->data) {
module->data->prev->next = child;
child->prev = module->data->prev;
module->data->prev = child;
} else {
module->data = child;
}
} else {
pchild = lys_child(parent, child->nodetype);
assert(pchild);
child->parent = parent;
if (!(*pchild)) {
/* the only/first child of the parent */
*pchild = child;
iter = child;
} else {
/* add a new child at the end of parent's child list */
iter = (*pchild)->prev;
iter->next = child;
child->prev = iter;
}
while (iter->next) {
iter = iter->next;
iter->parent = parent;
}
(*pchild)->prev = iter;
}
}
/* check config value (but ignore them in groupings and augments) */
for (iter = parent; iter && !(iter->nodetype & (LYS_GROUPING | LYS_AUGMENT | LYS_EXT)); iter = iter->parent);
if (parent && !iter) {
for (iter = child; iter && !(iter->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); iter = iter->parent);
if (!iter && (parent->flags & LYS_CONFIG_R) && (child->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, child, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
return EXIT_FAILURE;
}
}
/* propagate information about status data presence */
if ((child->nodetype & (LYS_CONTAINER | LYS_CHOICE | LYS_LEAF | LYS_LEAFLIST | LYS_LIST | LYS_ANYDATA)) &&
(child->flags & LYS_INCL_STATUS)) {
for(iter = parent; iter; iter = lys_parent(iter)) {
/* store it only into container or list - the only data inner nodes */
if (iter->nodetype & (LYS_CONTAINER | LYS_LIST)) {
if (iter->flags & LYS_INCL_STATUS) {
/* done, someone else set it already from here */
break;
}
/* set flag about including status data */
iter->flags |= LYS_INCL_STATUS;
}
}
}
/* create implicit input/output nodes to have available them as possible target for augment */
if ((child->nodetype & (LYS_RPC | LYS_ACTION)) && !child->child) {
in = calloc(1, sizeof *in);
out = calloc(1, sizeof *out);
if (!in || !out) {
LOGMEM(ctx);
free(in);
free(out);
return EXIT_FAILURE;
}
in->nodetype = LYS_INPUT;
in->name = lydict_insert(child->module->ctx, "input", 5);
out->nodetype = LYS_OUTPUT;
out->name = lydict_insert(child->module->ctx, "output", 6);
in->module = out->module = child->module;
in->parent = out->parent = child;
in->flags = out->flags = LYS_IMPLICIT;
in->next = (struct lys_node *)out;
in->prev = (struct lys_node *)out;
out->prev = (struct lys_node *)in;
child->child = (struct lys_node *)in;
}
return EXIT_SUCCESS;
}
const struct lys_module *
lys_parse_mem_(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format, const char *revision, int internal, int implement)
{
char *enlarged_data = NULL;
struct lys_module *mod = NULL;
unsigned int len;
if (!ctx || !data) {
LOGARG;
return NULL;
}
if (!internal && format == LYS_IN_YANG) {
/* enlarge data by 2 bytes for flex */
len = strlen(data);
enlarged_data = malloc((len + 2) * sizeof *enlarged_data);
LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(ctx), NULL);
memcpy(enlarged_data, data, len);
enlarged_data[len] = enlarged_data[len + 1] = '\0';
data = enlarged_data;
}
switch (format) {
case LYS_IN_YIN:
mod = yin_read_module(ctx, data, revision, implement);
break;
case LYS_IN_YANG:
mod = yang_read_module(ctx, data, 0, revision, implement);
break;
default:
LOGERR(ctx, LY_EINVAL, "Invalid schema input format.");
break;
}
free(enlarged_data);
/* hack for NETCONF's edit-config's operation attribute. It is not defined in the schema, but since libyang
* implements YANG metadata (annotations), we need its definition. Because the ietf-netconf schema is not the
* internal part of libyang, we cannot add the annotation into the schema source, but we do it here to have
* the anotation definitions available in the internal schema structure. There is another hack in schema
* printers to do not print this internally added annotation. */
if (mod && ly_strequal(mod->name, "ietf-netconf", 0)) {
if (lyp_add_ietf_netconf_annotations_config(mod)) {
lys_free(mod, NULL, 1, 1);
return NULL;
}
}
return mod;
}
API const struct lys_module *
lys_parse_mem(struct ly_ctx *ctx, const char *data, LYS_INFORMAT format)
{
return lys_parse_mem_(ctx, data, format, NULL, 0, 1);
}
struct lys_submodule *
lys_sub_parse_mem(struct lys_module *module, const char *data, LYS_INFORMAT format, struct unres_schema *unres)
{
char *enlarged_data = NULL;
struct lys_submodule *submod = NULL;
unsigned int len;
assert(module);
assert(data);
if (format == LYS_IN_YANG) {
/* enlarge data by 2 bytes for flex */
len = strlen(data);
enlarged_data = malloc((len + 2) * sizeof *enlarged_data);
LY_CHECK_ERR_RETURN(!enlarged_data, LOGMEM(module->ctx), NULL);
memcpy(enlarged_data, data, len);
enlarged_data[len] = enlarged_data[len + 1] = '\0';
data = enlarged_data;
}
/* get the main module */
module = lys_main_module(module);
switch (format) {
case LYS_IN_YIN:
submod = yin_read_submodule(module, data, unres);
break;
case LYS_IN_YANG:
submod = yang_read_submodule(module, data, 0, unres);
break;
default:
assert(0);
break;
}
free(enlarged_data);
return submod;
}
API const struct lys_module *
lys_parse_path(struct ly_ctx *ctx, const char *path, LYS_INFORMAT format)
{
int fd;
const struct lys_module *ret;
const char *rev, *dot, *filename;
size_t len;
if (!ctx || !path) {
LOGARG;
return NULL;
}
fd = open(path, O_RDONLY);
if (fd == -1) {
LOGERR(ctx, LY_ESYS, "Opening file \"%s\" failed (%s).", path, strerror(errno));
return NULL;
}
ret = lys_parse_fd(ctx, fd, format);
close(fd);
if (!ret) {
/* error */
return NULL;
}
/* check that name and revision match filename */
filename = strrchr(path, '/');
if (!filename) {
filename = path;
} else {
filename++;
}
rev = strchr(filename, '@');
dot = strrchr(filename, '.');
/* name */
len = strlen(ret->name);
if (strncmp(filename, ret->name, len) ||
((rev && rev != &filename[len]) || (!rev && dot != &filename[len]))) {
LOGWRN(ctx, "File name \"%s\" does not match module name \"%s\".", filename, ret->name);
}
if (rev) {
len = dot - ++rev;
if (!ret->rev_size || len != 10 || strncmp(ret->rev[0].date, rev, len)) {
LOGWRN(ctx, "File name \"%s\" does not match module revision \"%s\".", filename,
ret->rev_size ? ret->rev[0].date : "none");
}
}
if (!ret->filepath) {
/* store URI */
char rpath[PATH_MAX];
if (realpath(path, rpath) != NULL) {
((struct lys_module *)ret)->filepath = lydict_insert(ctx, rpath, 0);
} else {
((struct lys_module *)ret)->filepath = lydict_insert(ctx, path, 0);
}
}
return ret;
}
API const struct lys_module *
lys_parse_fd(struct ly_ctx *ctx, int fd, LYS_INFORMAT format)
{
return lys_parse_fd_(ctx, fd, format, NULL, 1);
}
static void
lys_parse_set_filename(struct ly_ctx *ctx, const char **filename, int fd)
{
#ifdef __APPLE__
char path[MAXPATHLEN];
#else
int len;
char path[PATH_MAX], proc_path[32];
#endif
#ifdef __APPLE__
if (fcntl(fd, F_GETPATH, path) != -1) {
*filename = lydict_insert(ctx, path, 0);
}
#else
/* get URI if there is /proc */
sprintf(proc_path, "/proc/self/fd/%d", fd);
if ((len = readlink(proc_path, path, PATH_MAX - 1)) > 0) {
*filename = lydict_insert(ctx, path, len);
}
#endif
}
const struct lys_module *
lys_parse_fd_(struct ly_ctx *ctx, int fd, LYS_INFORMAT format, const char *revision, int implement)
{
const struct lys_module *module;
size_t length;
char *addr;
if (!ctx || fd < 0) {
LOGARG;
return NULL;
}
if (lyp_mmap(ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) {
LOGERR(ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__);
return NULL;
} else if (!addr) {
LOGERR(ctx, LY_EINVAL, "Empty schema file.");
return NULL;
}
module = lys_parse_mem_(ctx, addr, format, revision, 1, implement);
lyp_munmap(addr, length);
if (module && !module->filepath) {
lys_parse_set_filename(ctx, (const char **)&module->filepath, fd);
}
return module;
}
struct lys_submodule *
lys_sub_parse_fd(struct lys_module *module, int fd, LYS_INFORMAT format, struct unres_schema *unres)
{
struct lys_submodule *submodule;
size_t length;
char *addr;
assert(module);
assert(fd >= 0);
if (lyp_mmap(module->ctx, fd, format == LYS_IN_YANG ? 1 : 0, &length, (void **)&addr)) {
LOGERR(module->ctx, LY_ESYS, "Mapping file descriptor into memory failed (%s()).", __func__);
return NULL;
} else if (!addr) {
LOGERR(module->ctx, LY_EINVAL, "Empty submodule schema file.");
return NULL;
}
/* get the main module */
module = lys_main_module(module);
switch (format) {
case LYS_IN_YIN:
submodule = yin_read_submodule(module, addr, unres);
break;
case LYS_IN_YANG:
submodule = yang_read_submodule(module, addr, 0, unres);
break;
default:
LOGINT(module->ctx);
return NULL;
}
lyp_munmap(addr, length);
if (submodule && !submodule->filepath) {
lys_parse_set_filename(module->ctx, (const char **)&submodule->filepath, fd);
}
return submodule;
}
API int
lys_search_localfile(const char * const *searchpaths, int cwd, const char *name, const char *revision, char **localfile, LYS_INFORMAT *format)
{
size_t len, flen, match_len = 0, dir_len;
int i, implicit_cwd = 0, ret = EXIT_FAILURE;
char *wd, *wn = NULL;
DIR *dir = NULL;
struct dirent *file;
char *match_name = NULL;
LYS_INFORMAT format_aux, match_format = 0;
unsigned int u;
struct ly_set *dirs;
struct stat st;
if (!localfile) {
LOGARG;
return EXIT_FAILURE;
}
/* start to fill the dir fifo with the context's search path (if set)
* and the current working directory */
dirs = ly_set_new();
if (!dirs) {
LOGMEM(NULL);
return EXIT_FAILURE;
}
len = strlen(name);
if (cwd) {
wd = get_current_dir_name();
if (!wd) {
LOGMEM(NULL);
goto cleanup;
} else {
/* add implicit current working directory (./) to be searched,
* this directory is not searched recursively */
if (ly_set_add(dirs, wd, 0) == -1) {
goto cleanup;
}
implicit_cwd = 1;
}
}
if (searchpaths) {
for (i = 0; searchpaths[i]; i++) {
/* check for duplicities with the implicit current working directory */
if (implicit_cwd && !strcmp(dirs->set.g[0], searchpaths[i])) {
implicit_cwd = 0;
continue;
}
wd = strdup(searchpaths[i]);
if (!wd) {
LOGMEM(NULL);
goto cleanup;
} else if (ly_set_add(dirs, wd, 0) == -1) {
goto cleanup;
}
}
}
wd = NULL;
/* start searching */
while (dirs->number) {
free(wd);
free(wn); wn = NULL;
dirs->number--;
wd = (char *)dirs->set.g[dirs->number];
dirs->set.g[dirs->number] = NULL;
LOGVRB("Searching for \"%s\" in %s.", name, wd);
if (dir) {
closedir(dir);
}
dir = opendir(wd);
dir_len = strlen(wd);
if (!dir) {
LOGWRN(NULL, "Unable to open directory \"%s\" for searching (sub)modules (%s).", wd, strerror(errno));
} else {
while ((file = readdir(dir))) {
if (!strcmp(".", file->d_name) || !strcmp("..", file->d_name)) {
/* skip . and .. */
continue;
}
free(wn);
if (asprintf(&wn, "%s/%s", wd, file->d_name) == -1) {
LOGMEM(NULL);
goto cleanup;
}
if (stat(wn, &st) == -1) {
LOGWRN(NULL, "Unable to get information about \"%s\" file in \"%s\" when searching for (sub)modules (%s)",
file->d_name, wd, strerror(errno));
continue;
}
if (S_ISDIR(st.st_mode) && (dirs->number || !implicit_cwd)) {
/* we have another subdirectory in searchpath to explore,
* subdirectories are not taken into account in current working dir (dirs->set.g[0]) */
if (ly_set_add(dirs, wn, 0) == -1) {
goto cleanup;
}
/* continue with the next item in current directory */
wn = NULL;
continue;
} else if (!S_ISREG(st.st_mode)) {
/* not a regular file (note that we see the target of symlinks instead of symlinks */
continue;
}
/* here we know that the item is a file which can contain a module */
if (strncmp(name, file->d_name, len) ||
(file->d_name[len] != '.' && file->d_name[len] != '@')) {
/* different filename than the module we search for */
continue;
}
/* get type according to filename suffix */
flen = strlen(file->d_name);
if (!strcmp(&file->d_name[flen - 4], ".yin")) {
format_aux = LYS_IN_YIN;
} else if (!strcmp(&file->d_name[flen - 5], ".yang")) {
format_aux = LYS_IN_YANG;
} else {
/* not supportde suffix/file format */
continue;
}
if (revision) {
/* we look for the specific revision, try to get it from the filename */
if (file->d_name[len] == '@') {
/* check revision from the filename */
if (strncmp(revision, &file->d_name[len + 1], strlen(revision))) {
/* another revision */
continue;
} else {
/* exact revision */
free(match_name);
match_name = wn;
wn = NULL;
match_len = dir_len + 1 + len;
match_format = format_aux;
goto success;
}
} else {
/* continue trying to find exact revision match, use this only if not found */
free(match_name);
match_name = wn;
wn = NULL;
match_len = dir_len + 1 +len;
match_format = format_aux;
continue;
}
} else {
/* remember the revision and try to find the newest one */
if (match_name) {
if (file->d_name[len] != '@' || lyp_check_date(NULL, &file->d_name[len + 1])) {
continue;
} else if (match_name[match_len] == '@' &&
(strncmp(&match_name[match_len + 1], &file->d_name[len + 1], LY_REV_SIZE - 1) >= 0)) {
continue;
}
free(match_name);
}
match_name = wn;
wn = NULL;
match_len = dir_len + 1 + len;
match_format = format_aux;
continue;
}
}
}
}
success:
(*localfile) = match_name;
match_name = NULL;
if (format) {
(*format) = match_format;
}
ret = EXIT_SUCCESS;
cleanup:
free(wn);
free(wd);
if (dir) {
closedir(dir);
}
free(match_name);
for (u = 0; u < dirs->number; u++) {
free(dirs->set.g[u]);
}
ly_set_free(dirs);
return ret;
}
int
lys_ext_iter(struct lys_ext_instance **ext, uint8_t ext_size, uint8_t start, LYEXT_SUBSTMT substmt)
{
unsigned int u;
for (u = start; u < ext_size; u++) {
if (ext[u]->insubstmt == substmt) {
return u;
}
}
return -1;
}
/*
* duplicate extension instance
*/
int
lys_ext_dup(struct ly_ctx *ctx, struct lys_module *mod, struct lys_ext_instance **orig, uint8_t size, void *parent,
LYEXT_PAR parent_type, struct lys_ext_instance ***new, int shallow, struct unres_schema *unres)
{
int i;
uint8_t u = 0;
struct lys_ext_instance **result;
struct unres_ext *info, *info_orig;
size_t len;
assert(new);
if (!size) {
if (orig) {
LOGINT(ctx);
return EXIT_FAILURE;
}
(*new) = NULL;
return EXIT_SUCCESS;
}
(*new) = result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(ctx), EXIT_FAILURE);
for (u = 0; u < size; u++) {
if (orig[u]) {
/* resolved extension instance, just duplicate it */
switch(orig[u]->ext_type) {
case LYEXT_FLAG:
result[u] = malloc(sizeof(struct lys_ext_instance));
LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error);
break;
case LYEXT_COMPLEX:
len = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->instance_size;
result[u] = calloc(1, len);
LY_CHECK_ERR_GOTO(!result[u], LOGMEM(ctx), error);
((struct lys_ext_instance_complex*)result[u])->substmt = ((struct lyext_plugin_complex*)orig[u]->def->plugin)->substmt;
/* TODO duplicate data in extension instance content */
memcpy((void*)result[u] + sizeof(**orig), (void*)orig[u] + sizeof(**orig), len - sizeof(**orig));
break;
}
/* generic part */
result[u]->def = orig[u]->def;
result[u]->flags = LYEXT_OPT_CONTENT;
result[u]->arg_value = lydict_insert(ctx, orig[u]->arg_value, 0);
result[u]->parent = parent;
result[u]->parent_type = parent_type;
result[u]->insubstmt = orig[u]->insubstmt;
result[u]->insubstmt_index = orig[u]->insubstmt_index;
result[u]->ext_type = orig[u]->ext_type;
result[u]->priv = NULL;
result[u]->nodetype = LYS_EXT;
result[u]->module = mod;
/* extensions */
result[u]->ext_size = orig[u]->ext_size;
if (lys_ext_dup(ctx, mod, orig[u]->ext, orig[u]->ext_size, result[u],
LYEXT_PAR_EXTINST, &result[u]->ext, shallow, unres)) {
goto error;
}
/* in case of shallow copy (duplication for deviation), duplicate only the link to private data
* in a new copy, otherwise (grouping instantiation) do not duplicate the private data */
if (shallow) {
result[u]->priv = orig[u]->priv;
}
} else {
/* original extension is not yet resolved, so duplicate it in unres */
i = unres_schema_find(unres, -1, &orig, UNRES_EXT);
if (i == -1) {
/* extension not found in unres */
LOGINT(ctx);
goto error;
}
info_orig = unres->str_snode[i];
info = malloc(sizeof *info);
LY_CHECK_ERR_GOTO(!info, LOGMEM(ctx), error);
info->datatype = info_orig->datatype;
if (info->datatype == LYS_IN_YIN) {
info->data.yin = lyxml_dup_elem(ctx, info_orig->data.yin, NULL, 1);
} /* else TODO YANG */
info->parent = parent;
info->mod = mod;
info->parent_type = parent_type;
info->ext_index = u;
if (unres_schema_add_node(info->mod, unres, new, UNRES_EXT, (struct lys_node *)info) == -1) {
goto error;
}
}
}
return EXIT_SUCCESS;
error:
(*new) = NULL;
lys_extension_instances_free(ctx, result, u, NULL);
return EXIT_FAILURE;
}
static struct lys_restr *
lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)
{
struct lys_restr *result;
int i;
if (!size) {
return NULL;
}
result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);
for (i = 0; i < size; i++) {
result[i].ext_size = old[i].ext_size;
lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);
result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);
result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);
result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);
result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);
result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);
}
return result;
}
void
lys_restr_free(struct ly_ctx *ctx, struct lys_restr *restr,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!restr) {
return;
}
lys_extension_instances_free(ctx, restr->ext, restr->ext_size, private_destructor);
lydict_remove(ctx, restr->expr);
lydict_remove(ctx, restr->dsc);
lydict_remove(ctx, restr->ref);
lydict_remove(ctx, restr->eapptag);
lydict_remove(ctx, restr->emsg);
}
API void
lys_iffeature_free(struct ly_ctx *ctx, struct lys_iffeature *iffeature, uint8_t iffeature_size,
int shallow, void (*private_destructor)(const struct lys_node *node, void *priv))
{
uint8_t i;
for (i = 0; i < iffeature_size; ++i) {
lys_extension_instances_free(ctx, iffeature[i].ext, iffeature[i].ext_size, private_destructor);
if (!shallow) {
free(iffeature[i].expr);
free(iffeature[i].features);
}
}
free(iffeature);
}
static int
type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
LY_DATA_TYPE base, int in_grp, int shallow, struct unres_schema *unres)
{
int i;
unsigned int u;
switch (base) {
case LY_TYPE_BINARY:
if (old->info.binary.length) {
new->info.binary.length = lys_restr_dup(mod, old->info.binary.length, 1, shallow, unres);
}
break;
case LY_TYPE_BITS:
new->info.bits.count = old->info.bits.count;
if (new->info.bits.count) {
new->info.bits.bit = calloc(new->info.bits.count, sizeof *new->info.bits.bit);
LY_CHECK_ERR_RETURN(!new->info.bits.bit, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.bits.count; u++) {
new->info.bits.bit[u].name = lydict_insert(mod->ctx, old->info.bits.bit[u].name, 0);
new->info.bits.bit[u].dsc = lydict_insert(mod->ctx, old->info.bits.bit[u].dsc, 0);
new->info.bits.bit[u].ref = lydict_insert(mod->ctx, old->info.bits.bit[u].ref, 0);
new->info.bits.bit[u].flags = old->info.bits.bit[u].flags;
new->info.bits.bit[u].pos = old->info.bits.bit[u].pos;
new->info.bits.bit[u].ext_size = old->info.bits.bit[u].ext_size;
if (lys_ext_dup(mod->ctx, mod, old->info.bits.bit[u].ext, old->info.bits.bit[u].ext_size,
&new->info.bits.bit[u], LYEXT_PAR_TYPE_BIT,
&new->info.bits.bit[u].ext, shallow, unres)) {
return -1;
}
}
}
break;
case LY_TYPE_DEC64:
new->info.dec64.dig = old->info.dec64.dig;
new->info.dec64.div = old->info.dec64.div;
if (old->info.dec64.range) {
new->info.dec64.range = lys_restr_dup(mod, old->info.dec64.range, 1, shallow, unres);
}
break;
case LY_TYPE_ENUM:
new->info.enums.count = old->info.enums.count;
if (new->info.enums.count) {
new->info.enums.enm = calloc(new->info.enums.count, sizeof *new->info.enums.enm);
LY_CHECK_ERR_RETURN(!new->info.enums.enm, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.enums.count; u++) {
new->info.enums.enm[u].name = lydict_insert(mod->ctx, old->info.enums.enm[u].name, 0);
new->info.enums.enm[u].dsc = lydict_insert(mod->ctx, old->info.enums.enm[u].dsc, 0);
new->info.enums.enm[u].ref = lydict_insert(mod->ctx, old->info.enums.enm[u].ref, 0);
new->info.enums.enm[u].flags = old->info.enums.enm[u].flags;
new->info.enums.enm[u].value = old->info.enums.enm[u].value;
new->info.enums.enm[u].ext_size = old->info.enums.enm[u].ext_size;
if (lys_ext_dup(mod->ctx, mod, old->info.enums.enm[u].ext, old->info.enums.enm[u].ext_size,
&new->info.enums.enm[u], LYEXT_PAR_TYPE_ENUM,
&new->info.enums.enm[u].ext, shallow, unres)) {
return -1;
}
}
}
break;
case LY_TYPE_IDENT:
new->info.ident.count = old->info.ident.count;
if (old->info.ident.count) {
new->info.ident.ref = malloc(old->info.ident.count * sizeof *new->info.ident.ref);
LY_CHECK_ERR_RETURN(!new->info.ident.ref, LOGMEM(mod->ctx), -1);
memcpy(new->info.ident.ref, old->info.ident.ref, old->info.ident.count * sizeof *new->info.ident.ref);
} else {
/* there can be several unresolved base identities, duplicate them all */
i = -1;
do {
i = unres_schema_find(unres, i, old, UNRES_TYPE_IDENTREF);
if (i != -1) {
if (unres_schema_add_str(mod, unres, new, UNRES_TYPE_IDENTREF, unres->str_snode[i]) == -1) {
return -1;
}
}
--i;
} while (i > -1);
}
break;
case LY_TYPE_INST:
new->info.inst.req = old->info.inst.req;
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
if (old->info.num.range) {
new->info.num.range = lys_restr_dup(mod, old->info.num.range, 1, shallow, unres);
}
break;
case LY_TYPE_LEAFREF:
if (old->info.lref.path) {
new->info.lref.path = lydict_insert(mod->ctx, old->info.lref.path, 0);
new->info.lref.req = old->info.lref.req;
if (!in_grp && unres_schema_add_node(mod, unres, new, UNRES_TYPE_LEAFREF, parent) == -1) {
return -1;
}
}
break;
case LY_TYPE_STRING:
if (old->info.str.length) {
new->info.str.length = lys_restr_dup(mod, old->info.str.length, 1, shallow, unres);
}
if (old->info.str.pat_count) {
new->info.str.patterns = lys_restr_dup(mod, old->info.str.patterns, old->info.str.pat_count, shallow, unres);
new->info.str.pat_count = old->info.str.pat_count;
#ifdef LY_ENABLED_CACHE
if (!in_grp) {
new->info.str.patterns_pcre = malloc(new->info.str.pat_count * 2 * sizeof *new->info.str.patterns_pcre);
LY_CHECK_ERR_RETURN(!new->info.str.patterns_pcre, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.str.pat_count; u++) {
if (lyp_precompile_pattern(mod->ctx, &new->info.str.patterns[u].expr[1],
(pcre**)&new->info.str.patterns_pcre[2 * u],
(pcre_extra**)&new->info.str.patterns_pcre[2 * u + 1])) {
free(new->info.str.patterns_pcre);
new->info.str.patterns_pcre = NULL;
return -1;
}
}
}
#endif
}
break;
case LY_TYPE_UNION:
new->info.uni.has_ptr_type = old->info.uni.has_ptr_type;
new->info.uni.count = old->info.uni.count;
if (new->info.uni.count) {
new->info.uni.types = calloc(new->info.uni.count, sizeof *new->info.uni.types);
LY_CHECK_ERR_RETURN(!new->info.uni.types, LOGMEM(mod->ctx), -1);
for (u = 0; u < new->info.uni.count; u++) {
if (lys_type_dup(mod, parent, &(new->info.uni.types[u]), &(old->info.uni.types[u]), in_grp,
shallow, unres)) {
return -1;
}
}
}
break;
default:
/* nothing to do for LY_TYPE_BOOL, LY_TYPE_EMPTY */
break;
}
return EXIT_SUCCESS;
}
struct yang_type *
lys_yang_type_dup(struct lys_module *module, struct lys_node *parent, struct yang_type *old, struct lys_type *type,
int in_grp, int shallow, struct unres_schema *unres)
{
struct yang_type *new;
new = calloc(1, sizeof *new);
LY_CHECK_ERR_RETURN(!new, LOGMEM(module->ctx), NULL);
new->flags = old->flags;
new->base = old->base;
new->name = lydict_insert(module->ctx, old->name, 0);
new->type = type;
if (!new->name) {
LOGMEM(module->ctx);
goto error;
}
if (type_dup(module, parent, type, old->type, new->base, in_grp, shallow, unres)) {
new->type->base = new->base;
lys_type_free(module->ctx, new->type, NULL);
memset(&new->type->info, 0, sizeof new->type->info);
goto error;
}
return new;
error:
free(new);
return NULL;
}
int
lys_copy_union_leafrefs(struct lys_module *mod, struct lys_node *parent, struct lys_type *type, struct lys_type *prev_new,
struct unres_schema *unres)
{
struct lys_type new;
unsigned int i, top_type;
struct lys_ext_instance **ext;
uint8_t ext_size;
void *reloc;
if (!prev_new) {
/* this is the "top-level" type, meaning it is a real type and no typedef directly above */
top_type = 1;
memset(&new, 0, sizeof new);
new.base = type->base;
new.parent = (struct lys_tpdf *)parent;
prev_new = &new;
} else {
/* this is not top-level type, just a type of a typedef */
top_type = 0;
}
assert(type->der);
if (type->der->module) {
/* typedef, skip it, but keep the extensions */
ext_size = type->ext_size;
if (lys_ext_dup(mod->ctx, mod, type->ext, type->ext_size, prev_new, LYEXT_PAR_TYPE, &ext, 0, unres)) {
return -1;
}
if (prev_new->ext) {
reloc = realloc(prev_new->ext, (prev_new->ext_size + ext_size) * sizeof *prev_new->ext);
LY_CHECK_ERR_RETURN(!reloc, LOGMEM(mod->ctx), -1);
prev_new->ext = reloc;
memcpy(prev_new->ext + prev_new->ext_size, ext, ext_size * sizeof *ext);
free(ext);
prev_new->ext_size += ext_size;
} else {
prev_new->ext = ext;
prev_new->ext_size = ext_size;
}
if (lys_copy_union_leafrefs(mod, parent, &type->der->type, prev_new, unres)) {
return -1;
}
} else {
/* type, just make a deep copy */
switch (type->base) {
case LY_TYPE_UNION:
prev_new->info.uni.has_ptr_type = type->info.uni.has_ptr_type;
prev_new->info.uni.count = type->info.uni.count;
/* this cannot be a typedef anymore */
assert(prev_new->info.uni.count);
prev_new->info.uni.types = calloc(prev_new->info.uni.count, sizeof *prev_new->info.uni.types);
LY_CHECK_ERR_RETURN(!prev_new->info.uni.types, LOGMEM(mod->ctx), -1);
for (i = 0; i < prev_new->info.uni.count; i++) {
if (lys_copy_union_leafrefs(mod, parent, &(type->info.uni.types[i]), &(prev_new->info.uni.types[i]), unres)) {
return -1;
}
}
prev_new->der = type->der;
break;
default:
if (lys_type_dup(mod, parent, prev_new, type, 0, 0, unres)) {
return -1;
}
break;
}
}
if (top_type) {
memcpy(type, prev_new, sizeof *type);
}
return EXIT_SUCCESS;
}
API const void *
lys_ext_instance_substmt(const struct lys_ext_instance *ext)
{
if (!ext) {
return NULL;
}
switch (ext->insubstmt) {
case LYEXT_SUBSTMT_SELF:
case LYEXT_SUBSTMT_MODIFIER:
case LYEXT_SUBSTMT_VERSION:
return NULL;
case LYEXT_SUBSTMT_ARGUMENT:
if (ext->parent_type == LYEXT_PAR_EXT) {
return ((struct lys_ext_instance*)ext->parent)->arg_value;
}
break;
case LYEXT_SUBSTMT_BASE:
if (ext->parent_type == LYEXT_PAR_TYPE) {
return ((struct lys_type*)ext->parent)->info.ident.ref[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_IDENT) {
return ((struct lys_ident*)ext->parent)->base[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_BELONGSTO:
if (ext->parent_type == LYEXT_PAR_MODULE && ((struct lys_module*)ext->parent)->type) {
return ((struct lys_submodule*)ext->parent)->belongsto;
}
break;
case LYEXT_SUBSTMT_CONFIG:
case LYEXT_SUBSTMT_MANDATORY:
if (ext->parent_type == LYEXT_PAR_NODE) {
return &((struct lys_node*)ext->parent)->flags;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return &((struct lys_deviate*)ext->parent)->flags;
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->flags;
}
break;
case LYEXT_SUBSTMT_CONTACT:
if (ext->parent_type == LYEXT_PAR_MODULE) {
return ((struct lys_module*)ext->parent)->contact;
}
break;
case LYEXT_SUBSTMT_DEFAULT:
if (ext->parent_type == LYEXT_PAR_NODE) {
switch (((struct lys_node*)ext->parent)->nodetype) {
case LYS_LEAF:
case LYS_LEAFLIST:
/* in case of leaf, the index is supposed to be 0, so it will return the
* correct pointer despite the leaf structure does not have dflt as array */
return ((struct lys_node_leaflist*)ext->parent)->dflt[ext->insubstmt_index];
case LYS_CHOICE:
return ((struct lys_node_choice*)ext->parent)->dflt;
default:
/* internal error */
break;
}
} else if (ext->parent_type == LYEXT_PAR_TPDF) {
return ((struct lys_tpdf*)ext->parent)->dflt;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return ((struct lys_deviate*)ext->parent)->dflt[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->dflt[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_DESCRIPTION:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
return ((struct lys_node*)ext->parent)->dsc;
case LYEXT_PAR_MODULE:
return ((struct lys_module*)ext->parent)->dsc;
case LYEXT_PAR_IMPORT:
return ((struct lys_import*)ext->parent)->dsc;
case LYEXT_PAR_INCLUDE:
return ((struct lys_include*)ext->parent)->dsc;
case LYEXT_PAR_EXT:
return ((struct lys_ext*)ext->parent)->dsc;
case LYEXT_PAR_FEATURE:
return ((struct lys_feature*)ext->parent)->dsc;
case LYEXT_PAR_TPDF:
return ((struct lys_tpdf*)ext->parent)->dsc;
case LYEXT_PAR_TYPE_BIT:
return ((struct lys_type_bit*)ext->parent)->dsc;
case LYEXT_PAR_TYPE_ENUM:
return ((struct lys_type_enum*)ext->parent)->dsc;
case LYEXT_PAR_RESTR:
return ((struct lys_restr*)ext->parent)->dsc;
case LYEXT_PAR_WHEN:
return ((struct lys_when*)ext->parent)->dsc;
case LYEXT_PAR_IDENT:
return ((struct lys_ident*)ext->parent)->dsc;
case LYEXT_PAR_DEVIATION:
return ((struct lys_deviation*)ext->parent)->dsc;
case LYEXT_PAR_REVISION:
return ((struct lys_revision*)ext->parent)->dsc;
case LYEXT_PAR_REFINE:
return ((struct lys_refine*)ext->parent)->dsc;
default:
break;
}
break;
case LYEXT_SUBSTMT_ERRTAG:
if (ext->parent_type == LYEXT_PAR_RESTR) {
return ((struct lys_restr*)ext->parent)->eapptag;
}
break;
case LYEXT_SUBSTMT_ERRMSG:
if (ext->parent_type == LYEXT_PAR_RESTR) {
return ((struct lys_restr*)ext->parent)->emsg;
}
break;
case LYEXT_SUBSTMT_DIGITS:
if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_DEC64) {
return &((struct lys_type*)ext->parent)->info.dec64.dig;
}
break;
case LYEXT_SUBSTMT_KEY:
if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return ((struct lys_node_list*)ext->parent)->keys;
}
break;
case LYEXT_SUBSTMT_MAX:
if (ext->parent_type == LYEXT_PAR_NODE) {
if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->max;
} else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) {
return &((struct lys_node_leaflist*)ext->parent)->max;
}
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->mod.list.max;
}
break;
case LYEXT_SUBSTMT_MIN:
if (ext->parent_type == LYEXT_PAR_NODE) {
if (((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->min;
} else if (((struct lys_node*)ext->parent)->nodetype == LYS_LEAFLIST) {
return &((struct lys_node_leaflist*)ext->parent)->min;
}
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return &((struct lys_refine*)ext->parent)->mod.list.min;
}
break;
case LYEXT_SUBSTMT_NAMESPACE:
if (ext->parent_type == LYEXT_PAR_MODULE && !((struct lys_module*)ext->parent)->type) {
return ((struct lys_module*)ext->parent)->ns;
}
break;
case LYEXT_SUBSTMT_ORDEREDBY:
if (ext->parent_type == LYEXT_PAR_NODE &&
(((struct lys_node*)ext->parent)->nodetype & (LYS_LIST | LYS_LEAFLIST))) {
return &((struct lys_node_list*)ext->parent)->flags;
}
break;
case LYEXT_SUBSTMT_ORGANIZATION:
if (ext->parent_type == LYEXT_PAR_MODULE) {
return ((struct lys_module*)ext->parent)->org;
}
break;
case LYEXT_SUBSTMT_PATH:
if (ext->parent_type == LYEXT_PAR_TYPE && ((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) {
return ((struct lys_type*)ext->parent)->info.lref.path;
}
break;
case LYEXT_SUBSTMT_POSITION:
if (ext->parent_type == LYEXT_PAR_TYPE_BIT) {
return &((struct lys_type_bit*)ext->parent)->pos;
}
break;
case LYEXT_SUBSTMT_PREFIX:
if (ext->parent_type == LYEXT_PAR_MODULE) {
/* covers also lys_submodule */
return ((struct lys_module*)ext->parent)->prefix;
} else if (ext->parent_type == LYEXT_PAR_IMPORT) {
return ((struct lys_import*)ext->parent)->prefix;
}
break;
case LYEXT_SUBSTMT_PRESENCE:
if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_CONTAINER) {
return ((struct lys_node_container*)ext->parent)->presence;
} else if (ext->parent_type == LYEXT_PAR_REFINE) {
return ((struct lys_refine*)ext->parent)->mod.presence;
}
break;
case LYEXT_SUBSTMT_REFERENCE:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
return ((struct lys_node*)ext->parent)->ref;
case LYEXT_PAR_MODULE:
return ((struct lys_module*)ext->parent)->ref;
case LYEXT_PAR_IMPORT:
return ((struct lys_import*)ext->parent)->ref;
case LYEXT_PAR_INCLUDE:
return ((struct lys_include*)ext->parent)->ref;
case LYEXT_PAR_EXT:
return ((struct lys_ext*)ext->parent)->ref;
case LYEXT_PAR_FEATURE:
return ((struct lys_feature*)ext->parent)->ref;
case LYEXT_PAR_TPDF:
return ((struct lys_tpdf*)ext->parent)->ref;
case LYEXT_PAR_TYPE_BIT:
return ((struct lys_type_bit*)ext->parent)->ref;
case LYEXT_PAR_TYPE_ENUM:
return ((struct lys_type_enum*)ext->parent)->ref;
case LYEXT_PAR_RESTR:
return ((struct lys_restr*)ext->parent)->ref;
case LYEXT_PAR_WHEN:
return ((struct lys_when*)ext->parent)->ref;
case LYEXT_PAR_IDENT:
return ((struct lys_ident*)ext->parent)->ref;
case LYEXT_PAR_DEVIATION:
return ((struct lys_deviation*)ext->parent)->ref;
case LYEXT_PAR_REVISION:
return ((struct lys_revision*)ext->parent)->ref;
case LYEXT_PAR_REFINE:
return ((struct lys_refine*)ext->parent)->ref;
default:
break;
}
break;
case LYEXT_SUBSTMT_REQINSTANCE:
if (ext->parent_type == LYEXT_PAR_TYPE) {
if (((struct lys_type*)ext->parent)->base == LY_TYPE_LEAFREF) {
return &((struct lys_type*)ext->parent)->info.lref.req;
} else if (((struct lys_type*)ext->parent)->base == LY_TYPE_INST) {
return &((struct lys_type*)ext->parent)->info.inst.req;
}
}
break;
case LYEXT_SUBSTMT_REVISIONDATE:
if (ext->parent_type == LYEXT_PAR_IMPORT) {
return ((struct lys_import*)ext->parent)->rev;
} else if (ext->parent_type == LYEXT_PAR_INCLUDE) {
return ((struct lys_include*)ext->parent)->rev;
}
break;
case LYEXT_SUBSTMT_STATUS:
switch (ext->parent_type) {
case LYEXT_PAR_NODE:
case LYEXT_PAR_IDENT:
case LYEXT_PAR_TPDF:
case LYEXT_PAR_EXT:
case LYEXT_PAR_FEATURE:
case LYEXT_PAR_TYPE_ENUM:
case LYEXT_PAR_TYPE_BIT:
/* in all structures the flags member is at the same offset */
return &((struct lys_node*)ext->parent)->flags;
default:
break;
}
break;
case LYEXT_SUBSTMT_UNIQUE:
if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return &((struct lys_deviate*)ext->parent)->unique[ext->insubstmt_index];
} else if (ext->parent_type == LYEXT_PAR_NODE && ((struct lys_node*)ext->parent)->nodetype == LYS_LIST) {
return &((struct lys_node_list*)ext->parent)->unique[ext->insubstmt_index];
}
break;
case LYEXT_SUBSTMT_UNITS:
if (ext->parent_type == LYEXT_PAR_NODE &&
(((struct lys_node*)ext->parent)->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
/* units is at the same offset in both lys_node_leaf and lys_node_leaflist */
return ((struct lys_node_leaf*)ext->parent)->units;
} else if (ext->parent_type == LYEXT_PAR_TPDF) {
return ((struct lys_tpdf*)ext->parent)->units;
} else if (ext->parent_type == LYEXT_PAR_DEVIATE) {
return ((struct lys_deviate*)ext->parent)->units;
}
break;
case LYEXT_SUBSTMT_VALUE:
if (ext->parent_type == LYEXT_PAR_TYPE_ENUM) {
return &((struct lys_type_enum*)ext->parent)->value;
}
break;
case LYEXT_SUBSTMT_YINELEM:
if (ext->parent_type == LYEXT_PAR_EXT) {
return &((struct lys_ext*)ext->parent)->flags;
}
break;
}
LOGINT(ext->module->ctx);
return NULL;
}
static int
lys_type_dup(struct lys_module *mod, struct lys_node *parent, struct lys_type *new, struct lys_type *old,
int in_grp, int shallow, struct unres_schema *unres)
{
int i;
new->base = old->base;
new->der = old->der;
new->parent = (struct lys_tpdf *)parent;
new->ext_size = old->ext_size;
if (lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_TYPE, &new->ext, shallow, unres)) {
return -1;
}
i = unres_schema_find(unres, -1, old, UNRES_TYPE_DER);
if (i != -1) {
/* HACK (serious one) for unres */
/* nothing else we can do but duplicate it immediately */
if (((struct lyxml_elem *)old->der)->flags & LY_YANG_STRUCTURE_FLAG) {
new->der = (struct lys_tpdf *)lys_yang_type_dup(mod, parent, (struct yang_type *)old->der, new, in_grp,
shallow, unres);
} else {
new->der = (struct lys_tpdf *)lyxml_dup_elem(mod->ctx, (struct lyxml_elem *)old->der, NULL, 1);
}
/* all these unres additions can fail even though they did not before */
if (!new->der || (unres_schema_add_node(mod, unres, new, UNRES_TYPE_DER, parent) == -1)) {
return -1;
}
return EXIT_SUCCESS;
}
return type_dup(mod, parent, new, old, new->base, in_grp, shallow, unres);
}
void
lys_type_free(struct ly_ctx *ctx, struct lys_type *type,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
unsigned int i;
assert(ctx);
if (!type) {
return;
}
lys_extension_instances_free(ctx, type->ext, type->ext_size, private_destructor);
switch (type->base) {
case LY_TYPE_BINARY:
lys_restr_free(ctx, type->info.binary.length, private_destructor);
free(type->info.binary.length);
break;
case LY_TYPE_BITS:
for (i = 0; i < type->info.bits.count; i++) {
lydict_remove(ctx, type->info.bits.bit[i].name);
lydict_remove(ctx, type->info.bits.bit[i].dsc);
lydict_remove(ctx, type->info.bits.bit[i].ref);
lys_iffeature_free(ctx, type->info.bits.bit[i].iffeature, type->info.bits.bit[i].iffeature_size, 0,
private_destructor);
lys_extension_instances_free(ctx, type->info.bits.bit[i].ext, type->info.bits.bit[i].ext_size,
private_destructor);
}
free(type->info.bits.bit);
break;
case LY_TYPE_DEC64:
lys_restr_free(ctx, type->info.dec64.range, private_destructor);
free(type->info.dec64.range);
break;
case LY_TYPE_ENUM:
for (i = 0; i < type->info.enums.count; i++) {
lydict_remove(ctx, type->info.enums.enm[i].name);
lydict_remove(ctx, type->info.enums.enm[i].dsc);
lydict_remove(ctx, type->info.enums.enm[i].ref);
lys_iffeature_free(ctx, type->info.enums.enm[i].iffeature, type->info.enums.enm[i].iffeature_size, 0,
private_destructor);
lys_extension_instances_free(ctx, type->info.enums.enm[i].ext, type->info.enums.enm[i].ext_size,
private_destructor);
}
free(type->info.enums.enm);
break;
case LY_TYPE_INT8:
case LY_TYPE_INT16:
case LY_TYPE_INT32:
case LY_TYPE_INT64:
case LY_TYPE_UINT8:
case LY_TYPE_UINT16:
case LY_TYPE_UINT32:
case LY_TYPE_UINT64:
lys_restr_free(ctx, type->info.num.range, private_destructor);
free(type->info.num.range);
break;
case LY_TYPE_LEAFREF:
lydict_remove(ctx, type->info.lref.path);
break;
case LY_TYPE_STRING:
lys_restr_free(ctx, type->info.str.length, private_destructor);
free(type->info.str.length);
for (i = 0; i < type->info.str.pat_count; i++) {
lys_restr_free(ctx, &type->info.str.patterns[i], private_destructor);
#ifdef LY_ENABLED_CACHE
if (type->info.str.patterns_pcre) {
pcre_free((pcre*)type->info.str.patterns_pcre[2 * i]);
pcre_free_study((pcre_extra*)type->info.str.patterns_pcre[2 * i + 1]);
}
#endif
}
free(type->info.str.patterns);
#ifdef LY_ENABLED_CACHE
free(type->info.str.patterns_pcre);
#endif
break;
case LY_TYPE_UNION:
for (i = 0; i < type->info.uni.count; i++) {
lys_type_free(ctx, &type->info.uni.types[i], private_destructor);
}
free(type->info.uni.types);
break;
case LY_TYPE_IDENT:
free(type->info.ident.ref);
break;
default:
/* nothing to do for LY_TYPE_INST, LY_TYPE_BOOL, LY_TYPE_EMPTY */
break;
}
}
static void
lys_tpdf_free(struct ly_ctx *ctx, struct lys_tpdf *tpdf,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!tpdf) {
return;
}
lydict_remove(ctx, tpdf->name);
lydict_remove(ctx, tpdf->dsc);
lydict_remove(ctx, tpdf->ref);
lys_type_free(ctx, &tpdf->type, private_destructor);
lydict_remove(ctx, tpdf->units);
lydict_remove(ctx, tpdf->dflt);
lys_extension_instances_free(ctx, tpdf->ext, tpdf->ext_size, private_destructor);
}
static struct lys_when *
lys_when_dup(struct lys_module *mod, struct lys_when *old, int shallow, struct unres_schema *unres)
{
struct lys_when *new;
if (!old) {
return NULL;
}
new = calloc(1, sizeof *new);
LY_CHECK_ERR_RETURN(!new, LOGMEM(mod->ctx), NULL);
new->cond = lydict_insert(mod->ctx, old->cond, 0);
new->dsc = lydict_insert(mod->ctx, old->dsc, 0);
new->ref = lydict_insert(mod->ctx, old->ref, 0);
new->ext_size = old->ext_size;
lys_ext_dup(mod->ctx, mod, old->ext, old->ext_size, new, LYEXT_PAR_WHEN, &new->ext, shallow, unres);
return new;
}
void
lys_when_free(struct ly_ctx *ctx, struct lys_when *w,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
if (!w) {
return;
}
lys_extension_instances_free(ctx, w->ext, w->ext_size, private_destructor);
lydict_remove(ctx, w->cond);
lydict_remove(ctx, w->dsc);
lydict_remove(ctx, w->ref);
free(w);
}
static void
lys_augment_free(struct ly_ctx *ctx, struct lys_node_augment *aug,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
struct lys_node *next, *sub;
/* children from a resolved augment are freed under the target node */
if (!aug->target || (aug->flags & LYS_NOTAPPLIED)) {
LY_TREE_FOR_SAFE(aug->child, next, sub) {
lys_node_free(sub, private_destructor, 0);
}
}
lydict_remove(ctx, aug->target_name);
lydict_remove(ctx, aug->dsc);
lydict_remove(ctx, aug->ref);
lys_iffeature_free(ctx, aug->iffeature, aug->iffeature_size, 0, private_destructor);
lys_extension_instances_free(ctx, aug->ext, aug->ext_size, private_destructor);
lys_when_free(ctx, aug->when, private_destructor);
}
static void
lys_ident_free(struct ly_ctx *ctx, struct lys_ident *ident,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
assert(ctx);
if (!ident) {
return;
}
free(ident->base);
ly_set_free(ident->der);
lydict_remove(ctx, ident->name);
lydict_remove(ctx, ident->dsc);
lydict_remove(ctx, ident->ref);
lys_iffeature_free(ctx, ident->iffeature, ident->iffeature_size, 0, private_destructor);
lys_extension_instances_free(ctx, ident->ext, ident->ext_size, private_destructor);
}
static void
lys_grp_free(struct ly_ctx *ctx, struct lys_node_grp *grp,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_GROUPING */
for (i = 0; i < grp->tpdf_size; i++) {
lys_tpdf_free(ctx, &grp->tpdf[i], private_destructor);
}
free(grp->tpdf);
}
static void
lys_rpc_action_free(struct ly_ctx *ctx, struct lys_node_rpc_action *rpc_act,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_GROUPING */
for (i = 0; i < rpc_act->tpdf_size; i++) {
lys_tpdf_free(ctx, &rpc_act->tpdf[i], private_destructor);
}
free(rpc_act->tpdf);
}
static void
lys_inout_free(struct ly_ctx *ctx, struct lys_node_inout *io,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LYS_INPUT and LYS_OUTPUT */
for (i = 0; i < io->tpdf_size; i++) {
lys_tpdf_free(ctx, &io->tpdf[i], private_destructor);
}
free(io->tpdf);
for (i = 0; i < io->must_size; i++) {
lys_restr_free(ctx, &io->must[i], private_destructor);
}
free(io->must);
}
static void
lys_notif_free(struct ly_ctx *ctx, struct lys_node_notif *notif,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
for (i = 0; i < notif->must_size; i++) {
lys_restr_free(ctx, ¬if->must[i], private_destructor);
}
free(notif->must);
for (i = 0; i < notif->tpdf_size; i++) {
lys_tpdf_free(ctx, ¬if->tpdf[i], private_destructor);
}
free(notif->tpdf);
}
static void
lys_anydata_free(struct ly_ctx *ctx, struct lys_node_anydata *anyxml,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
for (i = 0; i < anyxml->must_size; i++) {
lys_restr_free(ctx, &anyxml->must[i], private_destructor);
}
free(anyxml->must);
lys_when_free(ctx, anyxml->when, private_destructor);
}
static void
lys_leaf_free(struct ly_ctx *ctx, struct lys_node_leaf *leaf,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* leafref backlinks */
ly_set_free((struct ly_set *)leaf->backlinks);
for (i = 0; i < leaf->must_size; i++) {
lys_restr_free(ctx, &leaf->must[i], private_destructor);
}
free(leaf->must);
lys_when_free(ctx, leaf->when, private_destructor);
lys_type_free(ctx, &leaf->type, private_destructor);
lydict_remove(ctx, leaf->units);
lydict_remove(ctx, leaf->dflt);
}
static void
lys_leaflist_free(struct ly_ctx *ctx, struct lys_node_leaflist *llist,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
if (llist->backlinks) {
/* leafref backlinks */
ly_set_free(llist->backlinks);
}
for (i = 0; i < llist->must_size; i++) {
lys_restr_free(ctx, &llist->must[i], private_destructor);
}
free(llist->must);
for (i = 0; i < llist->dflt_size; i++) {
lydict_remove(ctx, llist->dflt[i]);
}
free(llist->dflt);
lys_when_free(ctx, llist->when, private_destructor);
lys_type_free(ctx, &llist->type, private_destructor);
lydict_remove(ctx, llist->units);
}
static void
lys_list_free(struct ly_ctx *ctx, struct lys_node_list *list,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j;
/* handle only specific parts for LY_NODE_LIST */
lys_when_free(ctx, list->when, private_destructor);
for (i = 0; i < list->must_size; i++) {
lys_restr_free(ctx, &list->must[i], private_destructor);
}
free(list->must);
for (i = 0; i < list->tpdf_size; i++) {
lys_tpdf_free(ctx, &list->tpdf[i], private_destructor);
}
free(list->tpdf);
free(list->keys);
for (i = 0; i < list->unique_size; i++) {
for (j = 0; j < list->unique[i].expr_size; j++) {
lydict_remove(ctx, list->unique[i].expr[j]);
}
free(list->unique[i].expr);
}
free(list->unique);
lydict_remove(ctx, list->keys_str);
}
static void
lys_container_free(struct ly_ctx *ctx, struct lys_node_container *cont,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
/* handle only specific parts for LY_NODE_CONTAINER */
lydict_remove(ctx, cont->presence);
for (i = 0; i < cont->tpdf_size; i++) {
lys_tpdf_free(ctx, &cont->tpdf[i], private_destructor);
}
free(cont->tpdf);
for (i = 0; i < cont->must_size; i++) {
lys_restr_free(ctx, &cont->must[i], private_destructor);
}
free(cont->must);
lys_when_free(ctx, cont->when, private_destructor);
}
static void
lys_feature_free(struct ly_ctx *ctx, struct lys_feature *f,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
lydict_remove(ctx, f->name);
lydict_remove(ctx, f->dsc);
lydict_remove(ctx, f->ref);
lys_iffeature_free(ctx, f->iffeature, f->iffeature_size, 0, private_destructor);
ly_set_free(f->depfeatures);
lys_extension_instances_free(ctx, f->ext, f->ext_size, private_destructor);
}
static void
lys_extension_free(struct ly_ctx *ctx, struct lys_ext *e,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
lydict_remove(ctx, e->name);
lydict_remove(ctx, e->dsc);
lydict_remove(ctx, e->ref);
lydict_remove(ctx, e->argument);
lys_extension_instances_free(ctx, e->ext, e->ext_size, private_destructor);
}
static void
lys_deviation_free(struct lys_module *module, struct lys_deviation *dev,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j, k;
struct ly_ctx *ctx;
struct lys_node *next, *elem;
ctx = module->ctx;
lydict_remove(ctx, dev->target_name);
lydict_remove(ctx, dev->dsc);
lydict_remove(ctx, dev->ref);
lys_extension_instances_free(ctx, dev->ext, dev->ext_size, private_destructor);
if (!dev->deviate) {
return;
}
/* it could not be applied because it failed to be applied */
if (dev->orig_node) {
/* the module was freed, but we only need the context from orig_node, use ours */
if (dev->deviate[0].mod == LY_DEVIATE_NO) {
/* it's actually a node subtree, we need to update modules on all the nodes :-/ */
LY_TREE_DFS_BEGIN(dev->orig_node, next, elem) {
elem->module = module;
LY_TREE_DFS_END(dev->orig_node, next, elem);
}
lys_node_free(dev->orig_node, NULL, 0);
} else {
/* it's just a shallow copy, freeing one node */
dev->orig_node->module = module;
lys_node_free(dev->orig_node, NULL, 1);
}
}
for (i = 0; i < dev->deviate_size; i++) {
lys_extension_instances_free(ctx, dev->deviate[i].ext, dev->deviate[i].ext_size, private_destructor);
for (j = 0; j < dev->deviate[i].dflt_size; j++) {
lydict_remove(ctx, dev->deviate[i].dflt[j]);
}
free(dev->deviate[i].dflt);
lydict_remove(ctx, dev->deviate[i].units);
if (dev->deviate[i].mod == LY_DEVIATE_DEL) {
for (j = 0; j < dev->deviate[i].must_size; j++) {
lys_restr_free(ctx, &dev->deviate[i].must[j], private_destructor);
}
free(dev->deviate[i].must);
for (j = 0; j < dev->deviate[i].unique_size; j++) {
for (k = 0; k < dev->deviate[i].unique[j].expr_size; k++) {
lydict_remove(ctx, dev->deviate[i].unique[j].expr[k]);
}
free(dev->deviate[i].unique[j].expr);
}
free(dev->deviate[i].unique);
}
}
free(dev->deviate);
}
static void
lys_uses_free(struct ly_ctx *ctx, struct lys_node_uses *uses,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i, j;
for (i = 0; i < uses->refine_size; i++) {
lydict_remove(ctx, uses->refine[i].target_name);
lydict_remove(ctx, uses->refine[i].dsc);
lydict_remove(ctx, uses->refine[i].ref);
lys_iffeature_free(ctx, uses->refine[i].iffeature, uses->refine[i].iffeature_size, 0, private_destructor);
for (j = 0; j < uses->refine[i].must_size; j++) {
lys_restr_free(ctx, &uses->refine[i].must[j], private_destructor);
}
free(uses->refine[i].must);
for (j = 0; j < uses->refine[i].dflt_size; j++) {
lydict_remove(ctx, uses->refine[i].dflt[j]);
}
free(uses->refine[i].dflt);
lys_extension_instances_free(ctx, uses->refine[i].ext, uses->refine[i].ext_size, private_destructor);
if (uses->refine[i].target_type & LYS_CONTAINER) {
lydict_remove(ctx, uses->refine[i].mod.presence);
}
}
free(uses->refine);
for (i = 0; i < uses->augment_size; i++) {
lys_augment_free(ctx, &uses->augment[i], private_destructor);
}
free(uses->augment);
lys_when_free(ctx, uses->when, private_destructor);
}
void
lys_node_free(struct lys_node *node, void (*private_destructor)(const struct lys_node *node, void *priv), int shallow)
{
struct ly_ctx *ctx;
struct lys_node *sub, *next;
if (!node) {
return;
}
assert(node->module);
assert(node->module->ctx);
ctx = node->module->ctx;
/* remove private object */
if (node->priv && private_destructor) {
private_destructor(node, node->priv);
}
/* common part */
lydict_remove(ctx, node->name);
if (!(node->nodetype & (LYS_INPUT | LYS_OUTPUT))) {
lys_iffeature_free(ctx, node->iffeature, node->iffeature_size, shallow, private_destructor);
lydict_remove(ctx, node->dsc);
lydict_remove(ctx, node->ref);
}
if (!shallow && !(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LY_TREE_FOR_SAFE(node->child, next, sub) {
lys_node_free(sub, private_destructor, 0);
}
}
lys_extension_instances_free(ctx, node->ext, node->ext_size, private_destructor);
/* specific part */
switch (node->nodetype) {
case LYS_CONTAINER:
lys_container_free(ctx, (struct lys_node_container *)node, private_destructor);
break;
case LYS_CHOICE:
lys_when_free(ctx, ((struct lys_node_choice *)node)->when, private_destructor);
break;
case LYS_LEAF:
lys_leaf_free(ctx, (struct lys_node_leaf *)node, private_destructor);
break;
case LYS_LEAFLIST:
lys_leaflist_free(ctx, (struct lys_node_leaflist *)node, private_destructor);
break;
case LYS_LIST:
lys_list_free(ctx, (struct lys_node_list *)node, private_destructor);
break;
case LYS_ANYXML:
case LYS_ANYDATA:
lys_anydata_free(ctx, (struct lys_node_anydata *)node, private_destructor);
break;
case LYS_USES:
lys_uses_free(ctx, (struct lys_node_uses *)node, private_destructor);
break;
case LYS_CASE:
lys_when_free(ctx, ((struct lys_node_case *)node)->when, private_destructor);
break;
case LYS_AUGMENT:
/* do nothing */
break;
case LYS_GROUPING:
lys_grp_free(ctx, (struct lys_node_grp *)node, private_destructor);
break;
case LYS_RPC:
case LYS_ACTION:
lys_rpc_action_free(ctx, (struct lys_node_rpc_action *)node, private_destructor);
break;
case LYS_NOTIF:
lys_notif_free(ctx, (struct lys_node_notif *)node, private_destructor);
break;
case LYS_INPUT:
case LYS_OUTPUT:
lys_inout_free(ctx, (struct lys_node_inout *)node, private_destructor);
break;
case LYS_EXT:
case LYS_UNKNOWN:
LOGINT(ctx);
break;
}
/* again common part */
lys_node_unlink(node);
free(node);
}
API struct lys_module *
lys_implemented_module(const struct lys_module *mod)
{
struct ly_ctx *ctx;
int i;
if (!mod || mod->implemented) {
/* invalid argument or the module itself is implemented */
return (struct lys_module *)mod;
}
ctx = mod->ctx;
for (i = 0; i < ctx->models.used; i++) {
if (!ctx->models.list[i]->implemented) {
continue;
}
if (ly_strequal(mod->name, ctx->models.list[i]->name, 1)) {
/* we have some revision of the module implemented */
return ctx->models.list[i];
}
}
/* we have no revision of the module implemented, return the module itself,
* it is up to the caller to set the module implemented when needed */
return (struct lys_module *)mod;
}
/* free_int_mods - flag whether to free the internal modules as well */
static void
module_free_common(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv))
{
struct ly_ctx *ctx;
struct lys_node *next, *iter;
unsigned int i;
assert(module->ctx);
ctx = module->ctx;
/* just free the import array, imported modules will stay in the context */
for (i = 0; i < module->imp_size; i++) {
lydict_remove(ctx, module->imp[i].prefix);
lydict_remove(ctx, module->imp[i].dsc);
lydict_remove(ctx, module->imp[i].ref);
lys_extension_instances_free(ctx, module->imp[i].ext, module->imp[i].ext_size, private_destructor);
}
free(module->imp);
/* submodules don't have data tree, the data nodes
* are placed in the main module altogether */
if (!module->type) {
LY_TREE_FOR_SAFE(module->data, next, iter) {
lys_node_free(iter, private_destructor, 0);
}
}
lydict_remove(ctx, module->dsc);
lydict_remove(ctx, module->ref);
lydict_remove(ctx, module->org);
lydict_remove(ctx, module->contact);
lydict_remove(ctx, module->filepath);
/* revisions */
for (i = 0; i < module->rev_size; i++) {
lys_extension_instances_free(ctx, module->rev[i].ext, module->rev[i].ext_size, private_destructor);
lydict_remove(ctx, module->rev[i].dsc);
lydict_remove(ctx, module->rev[i].ref);
}
free(module->rev);
/* identities */
for (i = 0; i < module->ident_size; i++) {
lys_ident_free(ctx, &module->ident[i], private_destructor);
}
module->ident_size = 0;
free(module->ident);
/* typedefs */
for (i = 0; i < module->tpdf_size; i++) {
lys_tpdf_free(ctx, &module->tpdf[i], private_destructor);
}
free(module->tpdf);
/* extension instances */
lys_extension_instances_free(ctx, module->ext, module->ext_size, private_destructor);
/* augment */
for (i = 0; i < module->augment_size; i++) {
lys_augment_free(ctx, &module->augment[i], private_destructor);
}
free(module->augment);
/* features */
for (i = 0; i < module->features_size; i++) {
lys_feature_free(ctx, &module->features[i], private_destructor);
}
free(module->features);
/* deviations */
for (i = 0; i < module->deviation_size; i++) {
lys_deviation_free(module, &module->deviation[i], private_destructor);
}
free(module->deviation);
/* extensions */
for (i = 0; i < module->extensions_size; i++) {
lys_extension_free(ctx, &module->extensions[i], private_destructor);
}
free(module->extensions);
lydict_remove(ctx, module->name);
lydict_remove(ctx, module->prefix);
}
void
lys_submodule_free(struct lys_submodule *submodule, void (*private_destructor)(const struct lys_node *node, void *priv))
{
int i;
if (!submodule) {
return;
}
/* common part with struct ly_module */
module_free_common((struct lys_module *)submodule, private_destructor);
/* include */
for (i = 0; i < submodule->inc_size; i++) {
lydict_remove(submodule->ctx, submodule->inc[i].dsc);
lydict_remove(submodule->ctx, submodule->inc[i].ref);
lys_extension_instances_free(submodule->ctx, submodule->inc[i].ext, submodule->inc[i].ext_size, private_destructor);
/* complete submodule free is done only from main module since
* submodules propagate their includes to the main module */
}
free(submodule->inc);
free(submodule);
}
int
lys_ingrouping(const struct lys_node *node)
{
const struct lys_node *iter = node;
assert(node);
for(iter = node; iter && iter->nodetype != LYS_GROUPING; iter = lys_parent(iter));
if (!iter) {
return 0;
} else {
return 1;
}
}
/*
* final: 0 - do not change config flags; 1 - inherit config flags from the parent; 2 - remove config flags
*/
static struct lys_node *
lys_node_dup_recursion(struct lys_module *module, struct lys_node *parent, const struct lys_node *node,
struct unres_schema *unres, int shallow, int finalize)
{
struct lys_node *retval = NULL, *iter, *p;
struct ly_ctx *ctx = module->ctx;
int i, j, rc;
unsigned int size, size1, size2;
struct unres_list_uniq *unique_info;
uint16_t flags;
struct lys_node_container *cont = NULL;
struct lys_node_container *cont_orig = (struct lys_node_container *)node;
struct lys_node_choice *choice = NULL;
struct lys_node_choice *choice_orig = (struct lys_node_choice *)node;
struct lys_node_leaf *leaf = NULL;
struct lys_node_leaf *leaf_orig = (struct lys_node_leaf *)node;
struct lys_node_leaflist *llist = NULL;
struct lys_node_leaflist *llist_orig = (struct lys_node_leaflist *)node;
struct lys_node_list *list = NULL;
struct lys_node_list *list_orig = (struct lys_node_list *)node;
struct lys_node_anydata *any = NULL;
struct lys_node_anydata *any_orig = (struct lys_node_anydata *)node;
struct lys_node_uses *uses = NULL;
struct lys_node_uses *uses_orig = (struct lys_node_uses *)node;
struct lys_node_rpc_action *rpc = NULL;
struct lys_node_inout *io = NULL;
struct lys_node_notif *ntf = NULL;
struct lys_node_case *cs = NULL;
struct lys_node_case *cs_orig = (struct lys_node_case *)node;
/* we cannot just duplicate memory since the strings are stored in
* dictionary and we need to update dictionary counters.
*/
switch (node->nodetype) {
case LYS_CONTAINER:
cont = calloc(1, sizeof *cont);
retval = (struct lys_node *)cont;
break;
case LYS_CHOICE:
choice = calloc(1, sizeof *choice);
retval = (struct lys_node *)choice;
break;
case LYS_LEAF:
leaf = calloc(1, sizeof *leaf);
retval = (struct lys_node *)leaf;
break;
case LYS_LEAFLIST:
llist = calloc(1, sizeof *llist);
retval = (struct lys_node *)llist;
break;
case LYS_LIST:
list = calloc(1, sizeof *list);
retval = (struct lys_node *)list;
break;
case LYS_ANYXML:
case LYS_ANYDATA:
any = calloc(1, sizeof *any);
retval = (struct lys_node *)any;
break;
case LYS_USES:
uses = calloc(1, sizeof *uses);
retval = (struct lys_node *)uses;
break;
case LYS_CASE:
cs = calloc(1, sizeof *cs);
retval = (struct lys_node *)cs;
break;
case LYS_RPC:
case LYS_ACTION:
rpc = calloc(1, sizeof *rpc);
retval = (struct lys_node *)rpc;
break;
case LYS_INPUT:
case LYS_OUTPUT:
io = calloc(1, sizeof *io);
retval = (struct lys_node *)io;
break;
case LYS_NOTIF:
ntf = calloc(1, sizeof *ntf);
retval = (struct lys_node *)ntf;
break;
default:
LOGINT(ctx);
goto error;
}
LY_CHECK_ERR_RETURN(!retval, LOGMEM(ctx), NULL);
/*
* duplicate generic part of the structure
*/
retval->name = lydict_insert(ctx, node->name, 0);
retval->dsc = lydict_insert(ctx, node->dsc, 0);
retval->ref = lydict_insert(ctx, node->ref, 0);
retval->flags = node->flags;
retval->module = module;
retval->nodetype = node->nodetype;
retval->prev = retval;
retval->ext_size = node->ext_size;
if (lys_ext_dup(ctx, module, node->ext, node->ext_size, retval, LYEXT_PAR_NODE, &retval->ext, shallow, unres)) {
goto error;
}
if (node->iffeature_size) {
retval->iffeature_size = node->iffeature_size;
retval->iffeature = calloc(retval->iffeature_size, sizeof *retval->iffeature);
LY_CHECK_ERR_GOTO(!retval->iffeature, LOGMEM(ctx), error);
}
if (!shallow) {
for (i = 0; i < node->iffeature_size; ++i) {
resolve_iffeature_getsizes(&node->iffeature[i], &size1, &size2);
if (size1) {
/* there is something to duplicate */
/* duplicate compiled expression */
size = (size1 / 4) + (size1 % 4) ? 1 : 0;
retval->iffeature[i].expr = malloc(size * sizeof *retval->iffeature[i].expr);
LY_CHECK_ERR_GOTO(!retval->iffeature[i].expr, LOGMEM(ctx), error);
memcpy(retval->iffeature[i].expr, node->iffeature[i].expr, size * sizeof *retval->iffeature[i].expr);
/* list of feature pointer must be updated to point to the resulting tree */
retval->iffeature[i].features = calloc(size2, sizeof *retval->iffeature[i].features);
LY_CHECK_ERR_GOTO(!retval->iffeature[i].features, LOGMEM(ctx); free(retval->iffeature[i].expr), error);
for (j = 0; (unsigned int)j < size2; j++) {
rc = unres_schema_dup(module, unres, &node->iffeature[i].features[j], UNRES_IFFEAT,
&retval->iffeature[i].features[j]);
if (rc == EXIT_FAILURE) {
/* feature is resolved in origin, so copy it
* - duplication is used for instantiating groupings
* and if-feature inside grouping is supposed to be
* resolved inside the original grouping, so we want
* to keep pointers to features from the grouping
* context */
retval->iffeature[i].features[j] = node->iffeature[i].features[j];
} else if (rc == -1) {
goto error;
} /* else unres was duplicated */
}
}
/* duplicate if-feature's extensions */
retval->iffeature[i].ext_size = node->iffeature[i].ext_size;
if (lys_ext_dup(ctx, module, node->iffeature[i].ext, node->iffeature[i].ext_size,
&retval->iffeature[i], LYEXT_PAR_IFFEATURE, &retval->iffeature[i].ext, shallow, unres)) {
goto error;
}
}
/* inherit config flags */
p = parent;
do {
for (iter = p; iter && (iter->nodetype == LYS_USES); iter = iter->parent);
} while (iter && iter->nodetype == LYS_AUGMENT && (p = lys_parent(iter)));
if (iter) {
flags = iter->flags & LYS_CONFIG_MASK;
} else {
/* default */
flags = LYS_CONFIG_W;
}
switch (finalize) {
case 1:
/* inherit config flags */
if (retval->flags & LYS_CONFIG_SET) {
/* skip nodes with an explicit config value */
if ((flags & LYS_CONFIG_R) && (retval->flags & LYS_CONFIG_W)) {
LOGVAL(ctx, LYE_INARG, LY_VLOG_LYS, retval, "true", "config");
LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "State nodes cannot have configuration nodes as children.");
goto error;
}
break;
}
if (retval->nodetype != LYS_USES) {
retval->flags = (retval->flags & ~LYS_CONFIG_MASK) | flags;
}
/* inherit status */
if ((parent->flags & LYS_STATUS_MASK) > (retval->flags & LYS_STATUS_MASK)) {
/* but do it only in case the parent has a stonger status */
retval->flags &= ~LYS_STATUS_MASK;
retval->flags |= (parent->flags & LYS_STATUS_MASK);
}
break;
case 2:
/* erase config flags */
retval->flags &= ~LYS_CONFIG_MASK;
retval->flags &= ~LYS_CONFIG_SET;
break;
}
/* connect it to the parent */
if (lys_node_addchild(parent, retval->module, retval, 0)) {
goto error;
}
/* go recursively */
if (!(node->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LY_TREE_FOR(node->child, iter) {
if (iter->nodetype & LYS_GROUPING) {
/* do not instantiate groupings */
continue;
}
if (!lys_node_dup_recursion(module, retval, iter, unres, 0, finalize)) {
goto error;
}
}
}
if (finalize == 1) {
/* check that configuration lists have keys
* - we really want to check keys_size in original node, because the keys are
* not yet resolved here, it is done below in nodetype specific part */
if ((retval->nodetype == LYS_LIST) && (retval->flags & LYS_CONFIG_W)
&& !((struct lys_node_list *)node)->keys_size) {
LOGVAL(ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, retval, "key", "list");
goto error;
}
}
} else {
memcpy(retval->iffeature, node->iffeature, retval->iffeature_size * sizeof *retval->iffeature);
}
/*
* duplicate specific part of the structure
*/
switch (node->nodetype) {
case LYS_CONTAINER:
if (cont_orig->when) {
cont->when = lys_when_dup(module, cont_orig->when, shallow, unres);
LY_CHECK_GOTO(!cont->when, error);
}
cont->presence = lydict_insert(ctx, cont_orig->presence, 0);
if (cont_orig->must) {
cont->must = lys_restr_dup(module, cont_orig->must, cont_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!cont->must, error);
cont->must_size = cont_orig->must_size;
}
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
break;
case LYS_CHOICE:
if (choice_orig->when) {
choice->when = lys_when_dup(module, choice_orig->when, shallow, unres);
LY_CHECK_GOTO(!choice->when, error);
}
if (!shallow) {
if (choice_orig->dflt) {
rc = lys_get_sibling(choice->child, lys_node_module(retval)->name, 0, choice_orig->dflt->name, 0,
LYS_ANYDATA | LYS_CASE | LYS_CONTAINER | LYS_LEAF | LYS_LEAFLIST | LYS_LIST,
(const struct lys_node **)&choice->dflt);
if (rc) {
if (rc == EXIT_FAILURE) {
LOGINT(ctx);
}
goto error;
}
} else {
/* useless to check return value, we don't know whether
* there really wasn't any default defined or it just hasn't
* been resolved, we just hope for the best :)
*/
unres_schema_dup(module, unres, choice_orig, UNRES_CHOICE_DFLT, choice);
}
} else {
choice->dflt = choice_orig->dflt;
}
break;
case LYS_LEAF:
if (lys_type_dup(module, retval, &(leaf->type), &(leaf_orig->type), lys_ingrouping(retval), shallow, unres)) {
goto error;
}
leaf->units = lydict_insert(module->ctx, leaf_orig->units, 0);
if (leaf_orig->dflt) {
leaf->dflt = lydict_insert(ctx, leaf_orig->dflt, 0);
}
if (leaf_orig->must) {
leaf->must = lys_restr_dup(module, leaf_orig->must, leaf_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!leaf->must, error);
leaf->must_size = leaf_orig->must_size;
}
if (leaf_orig->when) {
leaf->when = lys_when_dup(module, leaf_orig->when, shallow, unres);
LY_CHECK_GOTO(!leaf->when, error);
}
break;
case LYS_LEAFLIST:
if (lys_type_dup(module, retval, &(llist->type), &(llist_orig->type), lys_ingrouping(retval), shallow, unres)) {
goto error;
}
llist->units = lydict_insert(module->ctx, llist_orig->units, 0);
llist->min = llist_orig->min;
llist->max = llist_orig->max;
if (llist_orig->must) {
llist->must = lys_restr_dup(module, llist_orig->must, llist_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!llist->must, error);
llist->must_size = llist_orig->must_size;
}
if (llist_orig->dflt) {
llist->dflt = malloc(llist_orig->dflt_size * sizeof *llist->dflt);
LY_CHECK_ERR_GOTO(!llist->dflt, LOGMEM(ctx), error);
llist->dflt_size = llist_orig->dflt_size;
for (i = 0; i < llist->dflt_size; i++) {
llist->dflt[i] = lydict_insert(ctx, llist_orig->dflt[i], 0);
}
}
if (llist_orig->when) {
llist->when = lys_when_dup(module, llist_orig->when, shallow, unres);
}
break;
case LYS_LIST:
list->min = list_orig->min;
list->max = list_orig->max;
if (list_orig->must) {
list->must = lys_restr_dup(module, list_orig->must, list_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!list->must, error);
list->must_size = list_orig->must_size;
}
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
if (list_orig->keys_size) {
list->keys = calloc(list_orig->keys_size, sizeof *list->keys);
LY_CHECK_ERR_GOTO(!list->keys, LOGMEM(ctx), error);
list->keys_str = lydict_insert(ctx, list_orig->keys_str, 0);
list->keys_size = list_orig->keys_size;
if (!shallow) {
if (unres_schema_add_node(module, unres, list, UNRES_LIST_KEYS, NULL) == -1) {
goto error;
}
} else {
memcpy(list->keys, list_orig->keys, list_orig->keys_size * sizeof *list->keys);
}
}
if (list_orig->unique) {
list->unique = malloc(list_orig->unique_size * sizeof *list->unique);
LY_CHECK_ERR_GOTO(!list->unique, LOGMEM(ctx), error);
list->unique_size = list_orig->unique_size;
for (i = 0; i < list->unique_size; ++i) {
list->unique[i].expr = malloc(list_orig->unique[i].expr_size * sizeof *list->unique[i].expr);
LY_CHECK_ERR_GOTO(!list->unique[i].expr, LOGMEM(ctx), error);
list->unique[i].expr_size = list_orig->unique[i].expr_size;
for (j = 0; j < list->unique[i].expr_size; j++) {
list->unique[i].expr[j] = lydict_insert(ctx, list_orig->unique[i].expr[j], 0);
/* if it stays in unres list, duplicate it also there */
unique_info = malloc(sizeof *unique_info);
LY_CHECK_ERR_GOTO(!unique_info, LOGMEM(ctx), error);
unique_info->list = (struct lys_node *)list;
unique_info->expr = list->unique[i].expr[j];
unique_info->trg_type = &list->unique[i].trg_type;
unres_schema_dup(module, unres, &list_orig, UNRES_LIST_UNIQ, unique_info);
}
}
}
if (list_orig->when) {
list->when = lys_when_dup(module, list_orig->when, shallow, unres);
LY_CHECK_GOTO(!list->when, error);
}
break;
case LYS_ANYXML:
case LYS_ANYDATA:
if (any_orig->must) {
any->must = lys_restr_dup(module, any_orig->must, any_orig->must_size, shallow, unres);
LY_CHECK_GOTO(!any->must, error);
any->must_size = any_orig->must_size;
}
if (any_orig->when) {
any->when = lys_when_dup(module, any_orig->when, shallow, unres);
LY_CHECK_GOTO(!any->when, error);
}
break;
case LYS_USES:
uses->grp = uses_orig->grp;
if (uses_orig->when) {
uses->when = lys_when_dup(module, uses_orig->when, shallow, unres);
LY_CHECK_GOTO(!uses->when, error);
}
/* it is not needed to duplicate refine, nor augment. They are already applied to the uses children */
break;
case LYS_CASE:
if (cs_orig->when) {
cs->when = lys_when_dup(module, cs_orig->when, shallow, unres);
LY_CHECK_GOTO(!cs->when, error);
}
break;
case LYS_ACTION:
case LYS_RPC:
case LYS_INPUT:
case LYS_OUTPUT:
case LYS_NOTIF:
/* typedefs are not needed in instantiated grouping, nor the deviation's shallow copy */
break;
default:
/* LY_NODE_AUGMENT */
LOGINT(ctx);
goto error;
}
return retval;
error:
lys_node_free(retval, NULL, 0);
return NULL;
}
int
lys_has_xpath(const struct lys_node *node)
{
assert(node);
switch (node->nodetype) {
case LYS_AUGMENT:
if (((struct lys_node_augment *)node)->when) {
return 1;
}
break;
case LYS_CASE:
if (((struct lys_node_case *)node)->when) {
return 1;
}
break;
case LYS_CHOICE:
if (((struct lys_node_choice *)node)->when) {
return 1;
}
break;
case LYS_ANYDATA:
if (((struct lys_node_anydata *)node)->when || ((struct lys_node_anydata *)node)->must_size) {
return 1;
}
break;
case LYS_LEAF:
if (((struct lys_node_leaf *)node)->when || ((struct lys_node_leaf *)node)->must_size) {
return 1;
}
break;
case LYS_LEAFLIST:
if (((struct lys_node_leaflist *)node)->when || ((struct lys_node_leaflist *)node)->must_size) {
return 1;
}
break;
case LYS_LIST:
if (((struct lys_node_list *)node)->when || ((struct lys_node_list *)node)->must_size) {
return 1;
}
break;
case LYS_CONTAINER:
if (((struct lys_node_container *)node)->when || ((struct lys_node_container *)node)->must_size) {
return 1;
}
break;
case LYS_INPUT:
case LYS_OUTPUT:
if (((struct lys_node_inout *)node)->must_size) {
return 1;
}
break;
case LYS_NOTIF:
if (((struct lys_node_notif *)node)->must_size) {
return 1;
}
break;
case LYS_USES:
if (((struct lys_node_uses *)node)->when) {
return 1;
}
break;
default:
/* does not have XPath */
break;
}
return 0;
}
int
lys_type_is_local(const struct lys_type *type)
{
if (!type->der->module) {
/* build-in type */
return 1;
}
/* type->parent can be either a typedef or leaf/leaf-list, but module pointers are compatible */
return (lys_main_module(type->der->module) == lys_main_module(((struct lys_tpdf *)type->parent)->module));
}
/*
* shallow -
* - do not inherit status from the parent
*/
struct lys_node *
lys_node_dup(struct lys_module *module, struct lys_node *parent, const struct lys_node *node,
struct unres_schema *unres, int shallow)
{
struct lys_node *p = NULL;
int finalize = 0;
struct lys_node *result, *iter, *next;
if (!shallow) {
/* get know where in schema tree we are to know what should be done during instantiation of the grouping */
for (p = parent;
p && !(p->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC | LYS_ACTION | LYS_GROUPING));
p = lys_parent(p));
finalize = p ? ((p->nodetype == LYS_GROUPING) ? 0 : 2) : 1;
}
result = lys_node_dup_recursion(module, parent, node, unres, shallow, finalize);
if (finalize) {
/* check xpath expressions in the instantiated tree */
for (iter = next = result; iter; iter = next) {
if (lys_has_xpath(iter) && unres_schema_add_node(module, unres, iter, UNRES_XPATH, NULL) == -1) {
/* invalid xpath */
return NULL;
}
/* select next item */
if (iter->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA | LYS_GROUPING)) {
/* child exception for leafs, leaflists and anyxml without children, ignore groupings */
next = NULL;
} else {
next = iter->child;
}
if (!next) {
/* no children, try siblings */
if (iter == result) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
iter = lys_parent(iter);
if (lys_parent(iter) == lys_parent(result)) {
/* we are done, no next element to process */
break;
}
next = iter->next;
}
}
}
return result;
}
/**
* @brief Switch contents of two same schema nodes. One of the nodes
* is expected to be ashallow copy of the other.
*
* @param[in] node1 Node whose contents will be switched with \p node2.
* @param[in] node2 Node whose contents will be switched with \p node1.
*/
static void
lys_node_switch(struct lys_node *node1, struct lys_node *node2)
{
const size_t mem_size = 104;
uint8_t mem[mem_size];
size_t offset, size;
assert((node1->module == node2->module) && ly_strequal(node1->name, node2->name, 1) && (node1->nodetype == node2->nodetype));
/*
* Initially, the nodes were really switched in the tree which
* caused problems for some other nodes with pointers (augments, leafrefs, ...)
* because their pointers were not being updated. Code kept in case there is
* a use of it in future (it took some debugging to cover all the cases).
* sibling next *
if (node1->prev->next) {
node1->prev->next = node2;
}
* sibling prev *
if (node1->next) {
node1->next->prev = node2;
} else {
for (child = node1->prev; child->prev->next; child = child->prev);
child->prev = node2;
}
* next *
node2->next = node1->next;
node1->next = NULL;
* prev *
if (node1->prev != node1) {
node2->prev = node1->prev;
}
node1->prev = node1;
* parent child *
if (node1->parent) {
if (node1->parent->child == node1) {
node1->parent->child = node2;
}
} else if (lys_main_module(node1->module)->data == node1) {
lys_main_module(node1->module)->data = node2;
}
* parent *
node2->parent = node1->parent;
node1->parent = NULL;
* child parent *
LY_TREE_FOR(node1->child, child) {
if (child->parent == node1) {
child->parent = node2;
}
}
* child *
node2->child = node1->child;
node1->child = NULL;
*/
/* switch common node part */
offset = 3 * sizeof(char *);
size = sizeof(uint16_t) + 6 * sizeof(uint8_t) + sizeof(struct lys_ext_instance **) + sizeof(struct lys_iffeature *);
memcpy(mem, ((uint8_t *)node1) + offset, size);
memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size);
memcpy(((uint8_t *)node2) + offset, mem, size);
/* switch node-specific data */
offset = sizeof(struct lys_node);
switch (node1->nodetype) {
case LYS_CONTAINER:
size = sizeof(struct lys_node_container) - offset;
break;
case LYS_CHOICE:
size = sizeof(struct lys_node_choice) - offset;
break;
case LYS_LEAF:
size = sizeof(struct lys_node_leaf) - offset;
break;
case LYS_LEAFLIST:
size = sizeof(struct lys_node_leaflist) - offset;
break;
case LYS_LIST:
size = sizeof(struct lys_node_list) - offset;
break;
case LYS_ANYDATA:
case LYS_ANYXML:
size = sizeof(struct lys_node_anydata) - offset;
break;
case LYS_CASE:
size = sizeof(struct lys_node_case) - offset;
break;
case LYS_INPUT:
case LYS_OUTPUT:
size = sizeof(struct lys_node_inout) - offset;
break;
case LYS_NOTIF:
size = sizeof(struct lys_node_notif) - offset;
break;
case LYS_RPC:
case LYS_ACTION:
size = sizeof(struct lys_node_rpc_action) - offset;
break;
default:
assert(0);
LOGINT(node1->module->ctx);
return;
}
assert(size <= mem_size);
memcpy(mem, ((uint8_t *)node1) + offset, size);
memcpy(((uint8_t *)node1) + offset, ((uint8_t *)node2) + offset, size);
memcpy(((uint8_t *)node2) + offset, mem, size);
/* typedefs were not copied to the backup node, so always reuse them,
* in leaves/leaf-lists we must correct the type parent pointer */
switch (node1->nodetype) {
case LYS_CONTAINER:
((struct lys_node_container *)node1)->tpdf_size = ((struct lys_node_container *)node2)->tpdf_size;
((struct lys_node_container *)node1)->tpdf = ((struct lys_node_container *)node2)->tpdf;
((struct lys_node_container *)node2)->tpdf_size = 0;
((struct lys_node_container *)node2)->tpdf = NULL;
break;
case LYS_LIST:
((struct lys_node_list *)node1)->tpdf_size = ((struct lys_node_list *)node2)->tpdf_size;
((struct lys_node_list *)node1)->tpdf = ((struct lys_node_list *)node2)->tpdf;
((struct lys_node_list *)node2)->tpdf_size = 0;
((struct lys_node_list *)node2)->tpdf = NULL;
break;
case LYS_RPC:
case LYS_ACTION:
((struct lys_node_rpc_action *)node1)->tpdf_size = ((struct lys_node_rpc_action *)node2)->tpdf_size;
((struct lys_node_rpc_action *)node1)->tpdf = ((struct lys_node_rpc_action *)node2)->tpdf;
((struct lys_node_rpc_action *)node2)->tpdf_size = 0;
((struct lys_node_rpc_action *)node2)->tpdf = NULL;
break;
case LYS_NOTIF:
((struct lys_node_notif *)node1)->tpdf_size = ((struct lys_node_notif *)node2)->tpdf_size;
((struct lys_node_notif *)node1)->tpdf = ((struct lys_node_notif *)node2)->tpdf;
((struct lys_node_notif *)node2)->tpdf_size = 0;
((struct lys_node_notif *)node2)->tpdf = NULL;
break;
case LYS_INPUT:
case LYS_OUTPUT:
((struct lys_node_inout *)node1)->tpdf_size = ((struct lys_node_inout *)node2)->tpdf_size;
((struct lys_node_inout *)node1)->tpdf = ((struct lys_node_inout *)node2)->tpdf;
((struct lys_node_inout *)node2)->tpdf_size = 0;
((struct lys_node_inout *)node2)->tpdf = NULL;
break;
case LYS_LEAF:
case LYS_LEAFLIST:
((struct lys_node_leaf *)node1)->type.parent = (struct lys_tpdf *)node1;
((struct lys_node_leaf *)node2)->type.parent = (struct lys_tpdf *)node2;
default:
break;
}
}
void
lys_free(struct lys_module *module, void (*private_destructor)(const struct lys_node *node, void *priv), int free_subs, int remove_from_ctx)
{
struct ly_ctx *ctx;
int i;
if (!module) {
return;
}
/* remove schema from the context */
ctx = module->ctx;
if (remove_from_ctx && ctx->models.used) {
for (i = 0; i < ctx->models.used; i++) {
if (ctx->models.list[i] == module) {
/* move all the models to not change the order in the list */
ctx->models.used--;
memmove(&ctx->models.list[i], ctx->models.list[i + 1], (ctx->models.used - i) * sizeof *ctx->models.list);
ctx->models.list[ctx->models.used] = NULL;
/* we are done */
break;
}
}
}
/* common part with struct ly_submodule */
module_free_common(module, private_destructor);
/* include */
for (i = 0; i < module->inc_size; i++) {
lydict_remove(ctx, module->inc[i].dsc);
lydict_remove(ctx, module->inc[i].ref);
lys_extension_instances_free(ctx, module->inc[i].ext, module->inc[i].ext_size, private_destructor);
/* complete submodule free is done only from main module since
* submodules propagate their includes to the main module */
if (free_subs) {
lys_submodule_free(module->inc[i].submodule, private_destructor);
}
}
free(module->inc);
/* specific items to free */
lydict_remove(ctx, module->ns);
free(module);
}
static void
lys_features_disable_recursive(struct lys_feature *f)
{
unsigned int i;
struct lys_feature *depf;
/* disable the feature */
f->flags &= ~LYS_FENABLED;
/* by disabling feature we have to disable also all features that depends on this feature */
if (f->depfeatures) {
for (i = 0; i < f->depfeatures->number; i++) {
depf = (struct lys_feature *)f->depfeatures->set.g[i];
if (depf->flags & LYS_FENABLED) {
lys_features_disable_recursive(depf);
}
}
}
}
/*
* op: 1 - enable, 0 - disable
*/
static int
lys_features_change(const struct lys_module *module, const char *name, int op)
{
int all = 0;
int i, j, k;
int progress, faili, failj, failk;
uint8_t fsize;
struct lys_feature *f;
if (!module || !name || !strlen(name)) {
LOGARG;
return EXIT_FAILURE;
}
if (!strcmp(name, "*")) {
/* enable all */
all = 1;
}
progress = failk = 1;
while (progress && failk) {
for (i = -1, failk = progress = 0; i < module->inc_size; i++) {
if (i == -1) {
fsize = module->features_size;
f = module->features;
} else {
fsize = module->inc[i].submodule->features_size;
f = module->inc[i].submodule->features;
}
for (j = 0; j < fsize; j++) {
if (all || !strcmp(f[j].name, name)) {
if ((op && (f[j].flags & LYS_FENABLED)) || (!op && !(f[j].flags & LYS_FENABLED))) {
if (all) {
/* skip already set features */
continue;
} else {
/* feature already set correctly */
return EXIT_SUCCESS;
}
}
if (op) {
/* check referenced features if they are enabled */
for (k = 0; k < f[j].iffeature_size; k++) {
if (!resolve_iffeature(&f[j].iffeature[k])) {
if (all) {
faili = i;
failj = j;
failk = k + 1;
break;
} else {
LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.",
f[j].name, k + 1);
return EXIT_FAILURE;
}
}
}
if (k == f[j].iffeature_size) {
/* the last check passed, do the change */
f[j].flags |= LYS_FENABLED;
progress++;
}
} else {
lys_features_disable_recursive(&f[j]);
progress++;
}
if (!all) {
/* stop in case changing a single feature */
return EXIT_SUCCESS;
}
}
}
}
}
if (failk) {
/* print info about the last failing feature */
LOGERR(module->ctx, LY_EINVAL, "Feature \"%s\" is disabled by its %d. if-feature condition.",
faili == -1 ? module->features[failj].name : module->inc[faili].submodule->features[failj].name, failk);
return EXIT_FAILURE;
}
if (all) {
return EXIT_SUCCESS;
} else {
/* the specified feature not found */
return EXIT_FAILURE;
}
}
API int
lys_features_enable(const struct lys_module *module, const char *feature)
{
return lys_features_change(module, feature, 1);
}
API int
lys_features_disable(const struct lys_module *module, const char *feature)
{
return lys_features_change(module, feature, 0);
}
API int
lys_features_state(const struct lys_module *module, const char *feature)
{
int i, j;
if (!module || !feature) {
return -1;
}
/* search for the specified feature */
/* module itself */
for (i = 0; i < module->features_size; i++) {
if (!strcmp(feature, module->features[i].name)) {
if (module->features[i].flags & LYS_FENABLED) {
return 1;
} else {
return 0;
}
}
}
/* submodules */
for (j = 0; j < module->inc_size; j++) {
for (i = 0; i < module->inc[j].submodule->features_size; i++) {
if (!strcmp(feature, module->inc[j].submodule->features[i].name)) {
if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) {
return 1;
} else {
return 0;
}
}
}
}
/* feature definition not found */
return -1;
}
API const char **
lys_features_list(const struct lys_module *module, uint8_t **states)
{
const char **result = NULL;
int i, j;
unsigned int count;
if (!module) {
return NULL;
}
count = module->features_size;
for (i = 0; i < module->inc_size; i++) {
count += module->inc[i].submodule->features_size;
}
result = malloc((count + 1) * sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(module->ctx), NULL);
if (states) {
*states = malloc((count + 1) * sizeof **states);
LY_CHECK_ERR_RETURN(!(*states), LOGMEM(module->ctx); free(result), NULL);
}
count = 0;
/* module itself */
for (i = 0; i < module->features_size; i++) {
result[count] = module->features[i].name;
if (states) {
if (module->features[i].flags & LYS_FENABLED) {
(*states)[count] = 1;
} else {
(*states)[count] = 0;
}
}
count++;
}
/* submodules */
for (j = 0; j < module->inc_size; j++) {
for (i = 0; i < module->inc[j].submodule->features_size; i++) {
result[count] = module->inc[j].submodule->features[i].name;
if (states) {
if (module->inc[j].submodule->features[i].flags & LYS_FENABLED) {
(*states)[count] = 1;
} else {
(*states)[count] = 0;
}
}
count++;
}
}
/* terminating NULL byte */
result[count] = NULL;
return result;
}
API struct lys_module *
lys_node_module(const struct lys_node *node)
{
if (!node) {
return NULL;
}
return node->module->type ? ((struct lys_submodule *)node->module)->belongsto : node->module;
}
API struct lys_module *
lys_main_module(const struct lys_module *module)
{
if (!module) {
return NULL;
}
return (module->type ? ((struct lys_submodule *)module)->belongsto : (struct lys_module *)module);
}
API struct lys_node *
lys_parent(const struct lys_node *node)
{
struct lys_node *parent;
if (!node) {
return NULL;
}
if (node->nodetype == LYS_EXT) {
if (((struct lys_ext_instance_complex*)node)->parent_type != LYEXT_PAR_NODE) {
return NULL;
}
parent = (struct lys_node*)((struct lys_ext_instance_complex*)node)->parent;
} else if (!node->parent) {
return NULL;
} else {
parent = node->parent;
}
if (parent->nodetype == LYS_AUGMENT) {
return ((struct lys_node_augment *)parent)->target;
} else {
return parent;
}
}
struct lys_node **
lys_child(const struct lys_node *node, LYS_NODE nodetype)
{
void *pp;
assert(node);
if (node->nodetype == LYS_EXT) {
pp = lys_ext_complex_get_substmt(lys_snode2stmt(nodetype), (struct lys_ext_instance_complex*)node, NULL);
if (!pp) {
return NULL;
}
return (struct lys_node **)pp;
} else if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
return NULL;
} else {
return (struct lys_node **)&node->child;
}
}
API void *
lys_set_private(const struct lys_node *node, void *priv)
{
void *prev;
if (!node) {
LOGARG;
return NULL;
}
prev = node->priv;
((struct lys_node *)node)->priv = priv;
return prev;
}
int
lys_leaf_add_leafref_target(struct lys_node_leaf *leafref_target, struct lys_node *leafref)
{
struct lys_node_leaf *iter;
struct ly_ctx *ctx = leafref_target->module->ctx;
if (!(leafref_target->nodetype & (LYS_LEAF | LYS_LEAFLIST))) {
LOGINT(ctx);
return -1;
}
/* check for config flag */
if (((struct lys_node_leaf*)leafref)->type.info.lref.req != -1 &&
(leafref->flags & LYS_CONFIG_W) && (leafref_target->flags & LYS_CONFIG_R)) {
LOGVAL(ctx, LYE_SPEC, LY_VLOG_LYS, leafref,
"The leafref %s is config but refers to a non-config %s.",
strnodetype(leafref->nodetype), strnodetype(leafref_target->nodetype));
return -1;
}
/* check for cycles */
for (iter = leafref_target; iter && iter->type.base == LY_TYPE_LEAFREF; iter = iter->type.info.lref.target) {
if ((void *)iter == (void *)leafref) {
/* cycle detected */
LOGVAL(ctx, LYE_CIRC_LEAFREFS, LY_VLOG_LYS, leafref);
return -1;
}
}
/* create fake child - the ly_set structure to hold the list of
* leafrefs referencing the leaf(-list) */
if (!leafref_target->backlinks) {
leafref_target->backlinks = (void *)ly_set_new();
if (!leafref_target->backlinks) {
LOGMEM(ctx);
return -1;
}
}
ly_set_add(leafref_target->backlinks, leafref, 0);
return 0;
}
/* not needed currently */
#if 0
static const char *
lys_data_path_reverse(const struct lys_node *node, char * const buf, uint32_t buf_len)
{
struct lys_module *prev_mod;
uint32_t str_len, mod_len, buf_idx;
if (!(node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA))) {
LOGINT;
return NULL;
}
buf_idx = buf_len - 1;
buf[buf_idx] = '\0';
while (node) {
if (lys_parent(node)) {
prev_mod = lys_node_module(lys_parent(node));
} else {
prev_mod = NULL;
}
if (node->nodetype & (LYS_CONTAINER | LYS_LIST | LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
str_len = strlen(node->name);
if (prev_mod != node->module) {
mod_len = strlen(node->module->name);
} else {
mod_len = 0;
}
if (buf_idx < 1 + (mod_len ? mod_len + 1 : 0) + str_len) {
LOGINT;
return NULL;
}
buf_idx -= 1 + (mod_len ? mod_len + 1 : 0) + str_len;
buf[buf_idx] = '/';
if (mod_len) {
memcpy(buf + buf_idx + 1, node->module->name, mod_len);
buf[buf_idx + 1 + mod_len] = ':';
}
memcpy(buf + buf_idx + 1 + (mod_len ? mod_len + 1 : 0), node->name, str_len);
}
node = lys_parent(node);
}
return buf + buf_idx;
}
#endif
API struct ly_set *
lys_xpath_atomize(const struct lys_node *ctx_node, enum lyxp_node_type ctx_node_type, const char *expr, int options)
{
struct lyxp_set set;
struct ly_set *ret_set;
uint32_t i;
if (!ctx_node || !expr) {
LOGARG;
return NULL;
}
/* adjust the root */
if ((ctx_node_type == LYXP_NODE_ROOT) || (ctx_node_type == LYXP_NODE_ROOT_CONFIG)) {
do {
ctx_node = lys_getnext(NULL, NULL, lys_node_module(ctx_node), LYS_GETNEXT_NOSTATECHECK);
} while ((ctx_node_type == LYXP_NODE_ROOT_CONFIG) && (ctx_node->flags & LYS_CONFIG_R));
}
memset(&set, 0, sizeof set);
if (options & LYXP_MUST) {
options &= ~LYXP_MUST;
options |= LYXP_SNODE_MUST;
} else if (options & LYXP_WHEN) {
options &= ~LYXP_WHEN;
options |= LYXP_SNODE_WHEN;
} else {
options |= LYXP_SNODE;
}
if (lyxp_atomize(expr, ctx_node, ctx_node_type, &set, options, NULL)) {
free(set.val.snodes);
LOGVAL(ctx_node->module->ctx, LYE_SPEC, LY_VLOG_LYS, ctx_node, "Resolving XPath expression \"%s\" failed.", expr);
return NULL;
}
ret_set = ly_set_new();
for (i = 0; i < set.used; ++i) {
switch (set.val.snodes[i].type) {
case LYXP_NODE_ELEM:
if (ly_set_add(ret_set, set.val.snodes[i].snode, LY_SET_OPT_USEASLIST) == -1) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
break;
default:
/* ignore roots, text and attr should not ever appear */
break;
}
}
free(set.val.snodes);
return ret_set;
}
API struct ly_set *
lys_node_xpath_atomize(const struct lys_node *node, int options)
{
const struct lys_node *next, *elem, *parent, *tmp;
struct lyxp_set set;
struct ly_set *ret_set;
uint16_t i;
if (!node) {
LOGARG;
return NULL;
}
for (parent = node; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT)); parent = lys_parent(parent));
if (!parent) {
/* not in input, output, or notification */
return NULL;
}
ret_set = ly_set_new();
if (!ret_set) {
return NULL;
}
LY_TREE_DFS_BEGIN(node, next, elem) {
if ((options & LYXP_NO_LOCAL) && !(elem->flags & (LYS_XPCONF_DEP | LYS_XPSTATE_DEP))) {
/* elem has no dependencies from other subtrees and local nodes get discarded */
goto next_iter;
}
if (lyxp_node_atomize(elem, &set, 0)) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
for (i = 0; i < set.used; ++i) {
switch (set.val.snodes[i].type) {
case LYXP_NODE_ELEM:
if (options & LYXP_NO_LOCAL) {
for (tmp = set.val.snodes[i].snode; tmp && (tmp != parent); tmp = lys_parent(tmp));
if (tmp) {
/* in local subtree, discard */
break;
}
}
if (ly_set_add(ret_set, set.val.snodes[i].snode, 0) == -1) {
ly_set_free(ret_set);
free(set.val.snodes);
return NULL;
}
break;
default:
/* ignore roots, text and attr should not ever appear */
break;
}
}
free(set.val.snodes);
if (!(options & LYXP_RECURSIVE)) {
break;
}
next_iter:
LY_TREE_DFS_END(node, next, elem);
}
return ret_set;
}
/* logs */
int
apply_aug(struct lys_node_augment *augment, struct unres_schema *unres)
{
struct lys_node *child, *parent;
int clear_config;
unsigned int u;
uint8_t *v;
struct lys_ext_instance *ext;
assert(augment->target && (augment->flags & LYS_NOTAPPLIED));
if (!augment->child) {
/* nothing to apply */
goto success;
}
/* inherit config information from actual parent */
for (parent = augment->target; parent && !(parent->nodetype & (LYS_NOTIF | LYS_INPUT | LYS_OUTPUT | LYS_RPC)); parent = lys_parent(parent));
clear_config = (parent) ? 1 : 0;
LY_TREE_FOR(augment->child, child) {
if (inherit_config_flag(child, augment->target->flags & LYS_CONFIG_MASK, clear_config)) {
return -1;
}
}
/* inherit extensions if any */
for (u = 0; u < augment->target->ext_size; u++) {
ext = augment->target->ext[u]; /* shortcut */
if (ext && ext->def->plugin && (ext->def->plugin->flags & LYEXT_OPT_INHERIT)) {
v = malloc(sizeof *v);
LY_CHECK_ERR_RETURN(!v, LOGMEM(augment->module->ctx), -1);
*v = u;
if (unres_schema_add_node(lys_main_module(augment->module), unres, &augment->target->ext,
UNRES_EXT_FINALIZE, (struct lys_node *)v) == -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;
}
}
}
/* reconnect augmenting data into the target - add them to the target child list */
if (augment->target->child) {
child = augment->target->child->prev;
child->next = augment->child;
augment->target->child->prev = augment->child->prev;
augment->child->prev = child;
} else {
augment->target->child = augment->child;
}
success:
/* remove the flag about not applicability */
augment->flags &= ~LYS_NOTAPPLIED;
return EXIT_SUCCESS;
}
static void
remove_aug(struct lys_node_augment *augment)
{
struct lys_node *last, *elem;
if ((augment->flags & LYS_NOTAPPLIED) || !augment->target) {
/* skip already not applied augment */
return;
}
elem = augment->child;
if (elem) {
LY_TREE_FOR(elem, last) {
if (!last->next || (last->next->parent != (struct lys_node *)augment)) {
break;
}
}
/* elem is first augment child, last is the last child */
/* parent child ptr */
if (augment->target->child == elem) {
augment->target->child = last->next;
}
/* parent child next ptr */
if (elem->prev->next) {
elem->prev->next = last->next;
}
/* parent child prev ptr */
if (last->next) {
last->next->prev = elem->prev;
} else if (augment->target->child) {
augment->target->child->prev = elem->prev;
}
/* update augment children themselves */
elem->prev = last;
last->next = NULL;
}
/* augment->target still keeps the resolved target, but for lys_augment_free()
* we have to keep information that this augment is not applied to free its data */
augment->flags |= LYS_NOTAPPLIED;
}
/*
* @param[in] module - the module where the deviation is defined
*/
static void
lys_switch_deviation(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
int ret, reapply = 0;
char *parent_path;
struct lys_node *target = NULL, *parent;
struct lys_node_inout *inout;
struct ly_set *set;
if (!dev->deviate) {
return;
}
if (dev->deviate[0].mod == LY_DEVIATE_NO) {
if (dev->orig_node) {
/* removing not-supported deviation ... */
if (strrchr(dev->target_name, '/') != dev->target_name) {
/* ... from a parent */
/* reconnect to its previous position */
parent = dev->orig_node->parent;
if (parent && (parent->nodetype == LYS_AUGMENT)) {
dev->orig_node->parent = NULL;
/* the original node was actually from augment, we have to get know if the augment is
* applied (its module is enabled and implemented). If yes, the node will be connected
* to the augment and the linkage with the target will be fixed if needed, otherwise
* it will be connected only to the augment */
if (!(parent->flags & LYS_NOTAPPLIED)) {
/* start with removing augment if applied before adding nodes, we have to make sure
* that everything will be connect correctly */
remove_aug((struct lys_node_augment *)parent);
reapply = 1;
}
/* connect the deviated node back into the augment */
lys_node_addchild(parent, NULL, dev->orig_node, 0);
if (reapply) {
/* augment is supposed to be applied, so fix pointers in target and the status of the original node */
assert(lys_node_module(parent)->implemented);
parent->flags |= LYS_NOTAPPLIED; /* allow apply_aug() */
apply_aug((struct lys_node_augment *)parent, unres);
}
} else if (parent && (parent->nodetype == LYS_USES)) {
/* uses child */
lys_node_addchild(parent, NULL, dev->orig_node, 0);
} else {
/* non-augment, non-toplevel */
parent_path = strndup(dev->target_name, strrchr(dev->target_name, '/') - dev->target_name);
ret = resolve_schema_nodeid(parent_path, NULL, module, &set, 0, 1);
free(parent_path);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
lys_node_addchild(target, NULL, dev->orig_node, 0);
}
} else {
/* ... from top-level data */
lys_node_addchild(NULL, (struct lys_module *)dev->orig_node->module, dev->orig_node, 0);
}
dev->orig_node = NULL;
} else {
/* adding not-supported deviation */
ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
/* unlink and store the original node */
parent = target->parent;
lys_node_unlink(target);
if (parent) {
if (parent->nodetype & (LYS_AUGMENT | LYS_USES)) {
/* hack for augment, because when the original will be sometime reconnected back, we actually need
* to reconnect it to both - the augment and its target (which is deduced from the deviations target
* path), so we need to remember the augment as an addition */
/* we also need to remember the parent uses so that we connect it back to it when switching deviation state */
target->parent = parent;
} else if (parent->nodetype & (LYS_RPC | LYS_ACTION)) {
/* re-create implicit node */
inout = calloc(1, sizeof *inout);
LY_CHECK_ERR_RETURN(!inout, LOGMEM(module->ctx), );
inout->nodetype = target->nodetype;
inout->name = lydict_insert(module->ctx, (inout->nodetype == LYS_INPUT) ? "input" : "output", 0);
inout->module = target->module;
inout->flags = LYS_IMPLICIT;
/* insert it manually */
assert(parent->child && !parent->child->next
&& (parent->child->nodetype == (inout->nodetype == LYS_INPUT ? LYS_OUTPUT : LYS_INPUT)));
parent->child->next = (struct lys_node *)inout;
inout->prev = parent->child;
parent->child->prev = (struct lys_node *)inout;
inout->parent = parent;
}
}
dev->orig_node = target;
}
} else {
ret = resolve_schema_nodeid(dev->target_name, NULL, module, &set, 0, 1);
if (ret == -1) {
LOGINT(module->ctx);
ly_set_free(set);
return;
}
target = set->set.s[0];
ly_set_free(set);
/* contents are switched */
lys_node_switch(target, dev->orig_node);
}
}
/* temporarily removes or applies deviations, updates module deviation flag accordingly */
void
lys_enable_deviations(struct lys_module *module)
{
uint32_t i = 0, j;
const struct lys_module *mod;
const char *ptr;
struct unres_schema *unres;
if (module->deviated) {
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
while ((mod = ly_ctx_get_module_iter(module->ctx, &i))) {
if (mod == module) {
continue;
}
for (j = 0; j < mod->deviation_size; ++j) {
ptr = strstr(mod->deviation[j].target_name, module->name);
if (ptr && ptr[strlen(module->name)] == ':') {
lys_switch_deviation(&mod->deviation[j], mod, unres);
}
}
}
assert(module->deviated == 2);
module->deviated = 1;
for (j = 0; j < module->inc_size; j++) {
if (module->inc[j].submodule->deviated) {
module->inc[j].submodule->deviated = module->deviated;
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
unres_schema_free(module, &unres, 1);
}
}
void
lys_disable_deviations(struct lys_module *module)
{
uint32_t i, j;
const struct lys_module *mod;
const char *ptr;
struct unres_schema *unres;
if (module->deviated) {
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
i = module->ctx->models.used;
while (i--) {
mod = module->ctx->models.list[i];
if (mod == module) {
continue;
}
j = mod->deviation_size;
while (j--) {
ptr = strstr(mod->deviation[j].target_name, module->name);
if (ptr && ptr[strlen(module->name)] == ':') {
lys_switch_deviation(&mod->deviation[j], mod, unres);
}
}
}
assert(module->deviated == 1);
module->deviated = 2;
for (j = 0; j < module->inc_size; j++) {
if (module->inc[j].submodule->deviated) {
module->inc[j].submodule->deviated = module->deviated;
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
unres_schema_free(module, &unres, 1);
}
}
static void
apply_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
lys_switch_deviation(dev, module, unres);
assert(dev->orig_node);
lys_node_module(dev->orig_node)->deviated = 1; /* main module */
dev->orig_node->module->deviated = 1; /* possible submodule */
}
static void
remove_dev(struct lys_deviation *dev, const struct lys_module *module, struct unres_schema *unres)
{
uint32_t idx = 0, j;
const struct lys_module *mod;
struct lys_module *target_mod, *target_submod;
const char *ptr;
if (dev->orig_node) {
target_mod = lys_node_module(dev->orig_node);
target_submod = dev->orig_node->module;
} else {
LOGINT(module->ctx);
return;
}
lys_switch_deviation(dev, module, unres);
/* clear the deviation flag if possible */
while ((mod = ly_ctx_get_module_iter(module->ctx, &idx))) {
if ((mod == module) || (mod == target_mod)) {
continue;
}
for (j = 0; j < mod->deviation_size; ++j) {
ptr = strstr(mod->deviation[j].target_name, target_mod->name);
if (ptr && (ptr[strlen(target_mod->name)] == ':')) {
/* some other module deviation targets the inspected module, flag remains */
break;
}
}
if (j < mod->deviation_size) {
break;
}
}
if (!mod) {
target_mod->deviated = 0; /* main module */
target_submod->deviated = 0; /* possible submodule */
}
}
void
lys_sub_module_apply_devs_augs(struct lys_module *module)
{
uint8_t u, v;
struct unres_schema *unres;
assert(module->implemented);
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
/* apply deviations */
for (u = 0; u < module->deviation_size; ++u) {
apply_dev(&module->deviation[u], module, unres);
}
/* apply augments */
for (u = 0; u < module->augment_size; ++u) {
apply_aug(&module->augment[u], unres);
}
/* apply deviations and augments defined in submodules */
for (v = 0; v < module->inc_size; ++v) {
for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) {
apply_dev(&module->inc[v].submodule->deviation[u], module, unres);
}
for (u = 0; u < module->inc[v].submodule->augment_size; ++u) {
apply_aug(&module->inc[v].submodule->augment[u], unres);
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
/* nothing else left to do even if something is not resolved */
unres_schema_free(module, &unres, 1);
}
void
lys_sub_module_remove_devs_augs(struct lys_module *module)
{
uint8_t u, v, w;
struct unres_schema *unres;
unres = calloc(1, sizeof *unres);
LY_CHECK_ERR_RETURN(!unres, LOGMEM(module->ctx), );
/* remove applied deviations */
for (u = 0; u < module->deviation_size; ++u) {
/* the deviation could not be applied because it failed to be applied in the first place*/
if (module->deviation[u].orig_node) {
remove_dev(&module->deviation[u], module, unres);
}
/* Free the deviation's must array(s). These are shallow copies of the arrays
on the target node(s), so a deep free is not needed. */
for (v = 0; v < module->deviation[u].deviate_size; ++v) {
if (module->deviation[u].deviate[v].mod == LY_DEVIATE_ADD) {
free(module->deviation[u].deviate[v].must);
}
}
}
/* remove applied augments */
for (u = 0; u < module->augment_size; ++u) {
remove_aug(&module->augment[u]);
}
/* remove deviation and augments defined in submodules */
for (v = 0; v < module->inc_size && module->inc[v].submodule; ++v) {
for (u = 0; u < module->inc[v].submodule->deviation_size; ++u) {
if (module->inc[v].submodule->deviation[u].orig_node) {
remove_dev(&module->inc[v].submodule->deviation[u], module, unres);
}
/* Free the deviation's must array(s). These are shallow copies of the arrays
on the target node(s), so a deep free is not needed. */
for (w = 0; w < module->inc[v].submodule->deviation[u].deviate_size; ++w) {
if (module->inc[v].submodule->deviation[u].deviate[w].mod == LY_DEVIATE_ADD) {
free(module->inc[v].submodule->deviation[u].deviate[w].must);
}
}
}
for (u = 0; u < module->inc[v].submodule->augment_size; ++u) {
remove_aug(&module->inc[v].submodule->augment[u]);
}
}
if (unres->count) {
resolve_unres_schema(module, unres);
}
/* nothing else left to do even if something is not resolved */
unres_schema_free(module, &unres, 1);
}
int
lys_make_implemented_r(struct lys_module *module, struct unres_schema *unres)
{
struct ly_ctx *ctx;
struct lys_node *root, *next, *node;
struct lys_module *target_module;
uint16_t i, j, k;
assert(module->implemented);
ctx = module->ctx;
for (i = 0; i < ctx->models.used; ++i) {
if (module == ctx->models.list[i]) {
continue;
}
if (!strcmp(module->name, ctx->models.list[i]->name) && ctx->models.list[i]->implemented) {
LOGERR(ctx, LY_EINVAL, "Module \"%s\" in another revision already implemented.", module->name);
return EXIT_FAILURE;
}
}
for (i = 0; i < module->augment_size; i++) {
/* make target module implemented if was not */
assert(module->augment[i].target);
target_module = lys_node_module(module->augment[i].target);
if (!target_module->implemented) {
target_module->implemented = 1;
if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* apply augment */
if ((module->augment[i].flags & LYS_NOTAPPLIED) && apply_aug(&module->augment[i], unres)) {
return -1;
}
}
/* identities */
for (i = 0; i < module->ident_size; i++) {
for (j = 0; j < module->ident[i].base_size; j++) {
resolve_identity_backlink_update(&module->ident[i], module->ident[i].base[j]);
}
}
/* process augments in submodules */
for (i = 0; i < module->inc_size && module->inc[i].submodule; ++i) {
module->inc[i].submodule->implemented = 1;
for (j = 0; j < module->inc[i].submodule->augment_size; j++) {
/* make target module implemented if it was not */
assert(module->inc[i].submodule->augment[j].target);
target_module = lys_node_module(module->inc[i].submodule->augment[j].target);
if (!target_module->implemented) {
target_module->implemented = 1;
if (unres_schema_add_node(target_module, unres, NULL, UNRES_MOD_IMPLEMENT, NULL) == -1) {
return -1;
}
}
/* apply augment */
if ((module->inc[i].submodule->augment[j].flags & LYS_NOTAPPLIED) && apply_aug(&module->inc[i].submodule->augment[j], unres)) {
return -1;
}
}
/* identities */
for (j = 0; j < module->inc[i].submodule->ident_size; j++) {
for (k = 0; k < module->inc[i].submodule->ident[j].base_size; k++) {
resolve_identity_backlink_update(&module->inc[i].submodule->ident[j],
module->inc[i].submodule->ident[j].base[k]);
}
}
}
LY_TREE_FOR(module->data, root) {
/* handle leafrefs and recursively change the implemented flags in the leafref targets */
LY_TREE_DFS_BEGIN(root, next, node) {
if (node->nodetype == LYS_GROUPING) {
goto nextsibling;
}
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST)) {
if (((struct lys_node_leaf *)node)->type.base == LY_TYPE_LEAFREF) {
if (unres_schema_add_node(module, unres, &((struct lys_node_leaf *)node)->type,
UNRES_TYPE_LEAFREF, node) == -1) {
return -1;
}
}
}
/* modified LY_TREE_DFS_END */
next = node->child;
/* child exception for leafs, leaflists and anyxml without children */
if (node->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) {
next = NULL;
}
if (!next) {
nextsibling:
/* no children */
if (node == root) {
/* we are done, root has no children */
break;
}
/* try siblings */
next = node->next;
}
while (!next) {
/* parent is already processed, go to its sibling */
node = lys_parent(node);
/* no siblings, go back through parents */
if (lys_parent(node) == lys_parent(root)) {
/* we are done, no next element to process */
break;
}
next = node->next;
}
}
}
return EXIT_SUCCESS;
}
API int
lys_set_implemented(const struct lys_module *module)
{
struct unres_schema *unres;
int disabled = 0;
if (!module) {
LOGARG;
return EXIT_FAILURE;
}
module = lys_main_module(module);
if (module->disabled) {
disabled = 1;
lys_set_enabled(module);
}
if (module->implemented) {
return EXIT_SUCCESS;
}
unres = calloc(1, sizeof *unres);
if (!unres) {
LOGMEM(module->ctx);
if (disabled) {
/* set it back disabled */
lys_set_disabled(module);
}
return EXIT_FAILURE;
}
/* recursively make the module implemented */
((struct lys_module *)module)->implemented = 1;
if (lys_make_implemented_r((struct lys_module *)module, unres)) {
goto error;
}
/* try again resolve augments in other modules possibly augmenting this one,
* since we have just enabled it
*/
/* resolve rest of unres items */
if (unres->count && resolve_unres_schema((struct lys_module *)module, unres)) {
goto error;
}
unres_schema_free(NULL, &unres, 0);
LOGVRB("Module \"%s%s%s\" now implemented.", module->name, (module->rev_size ? "@" : ""),
(module->rev_size ? module->rev[0].date : ""));
return EXIT_SUCCESS;
error:
if (disabled) {
/* set it back disabled */
lys_set_disabled(module);
}
((struct lys_module *)module)->implemented = 0;
unres_schema_free((struct lys_module *)module, &unres, 1);
return EXIT_FAILURE;
}
void
lys_submodule_module_data_free(struct lys_submodule *submodule)
{
struct lys_node *next, *elem;
/* remove parsed data */
LY_TREE_FOR_SAFE(submodule->belongsto->data, next, elem) {
if (elem->module == (struct lys_module *)submodule) {
lys_node_free(elem, NULL, 0);
}
}
}
API char *
lys_path(const struct lys_node *node, int options)
{
char *buf = NULL;
if (!node) {
LOGARG;
return NULL;
}
if (ly_vlog_build_path(LY_VLOG_LYS, node, &buf, (options & LYS_PATH_FIRST_PREFIX) ? 0 : 1, 0)) {
return NULL;
}
return buf;
}
API char *
lys_data_path(const struct lys_node *node)
{
char *result = NULL, buf[1024];
const char *separator, *name;
int i, used;
struct ly_set *set;
const struct lys_module *prev_mod;
if (!node) {
LOGARG;
return NULL;
}
buf[0] = '\0';
set = ly_set_new();
LY_CHECK_ERR_GOTO(!set, LOGMEM(node->module->ctx), cleanup);
while (node) {
ly_set_add(set, (void *)node, 0);
do {
node = lys_parent(node);
} while (node && (node->nodetype & (LYS_USES | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT)));
}
prev_mod = NULL;
used = 0;
for (i = set->number - 1; i > -1; --i) {
node = set->set.s[i];
if (node->nodetype == LYS_EXT) {
if (strcmp(((struct lys_ext_instance *)node)->def->name, "yang-data")) {
continue;
}
name = ((struct lys_ext_instance *)node)->arg_value;
separator = ":#";
} else {
name = node->name;
separator = ":";
}
used += sprintf(buf + used, "/%s%s%s", (lys_node_module(node) == prev_mod ? "" : lys_node_module(node)->name),
(lys_node_module(node) == prev_mod ? "" : separator), name);
prev_mod = lys_node_module(node);
}
result = strdup(buf);
LY_CHECK_ERR_GOTO(!result, LOGMEM(node->module->ctx), cleanup);
cleanup:
ly_set_free(set);
return result;
}
struct lys_node_augment *
lys_getnext_target_aug(struct lys_node_augment *last, const struct lys_module *mod, const struct lys_node *aug_target)
{
struct lys_node *child;
struct lys_node_augment *aug;
int i, j, last_found;
assert(mod && aug_target);
if (!last) {
last_found = 1;
} else {
last_found = 0;
}
/* search module augments */
for (i = 0; i < mod->augment_size; ++i) {
if (!mod->augment[i].target) {
/* still unresolved, skip */
continue;
}
if (mod->augment[i].target == aug_target) {
if (last_found) {
/* next match after last */
return &mod->augment[i];
}
if (&mod->augment[i] == last) {
last_found = 1;
}
}
}
/* search submodule augments */
for (i = 0; i < mod->inc_size; ++i) {
for (j = 0; j < mod->inc[i].submodule->augment_size; ++j) {
if (!mod->inc[i].submodule->augment[j].target) {
continue;
}
if (mod->inc[i].submodule->augment[j].target == aug_target) {
if (last_found) {
/* next match after last */
return &mod->inc[i].submodule->augment[j];
}
if (&mod->inc[i].submodule->augment[j] == last) {
last_found = 1;
}
}
}
}
/* we also need to check possible augments to choices */
LY_TREE_FOR(aug_target->child, child) {
if (child->nodetype == LYS_CHOICE) {
aug = lys_getnext_target_aug(last, mod, child);
if (aug) {
return aug;
}
}
}
return NULL;
}
API struct ly_set *
lys_find_path(const struct lys_module *cur_module, const struct lys_node *cur_node, const char *path)
{
struct ly_set *ret;
int rc;
if ((!cur_module && !cur_node) || !path) {
return NULL;
}
rc = resolve_schema_nodeid(path, cur_node, cur_module, &ret, 1, 1);
if (rc == -1) {
return NULL;
}
return ret;
}
static void
lys_extcomplex_free_str(struct ly_ctx *ctx, struct lys_ext_instance_complex *ext, LY_STMT stmt)
{
struct lyext_substmt *info;
const char **str, ***a;
int c;
str = lys_ext_complex_get_substmt(stmt, ext, &info);
if (!str || !(*str)) {
return;
}
if (info->cardinality >= LY_STMT_CARD_SOME) {
/* we have array */
a = (const char ***)str;
for (str = (*(const char ***)str), c = 0; str[c]; c++) {
lydict_remove(ctx, str[c]);
}
free(a[0]);
if (stmt == LY_STMT_BELONGSTO) {
for (str = a[1], c = 0; str[c]; c++) {
lydict_remove(ctx, str[c]);
}
free(a[1]);
} else if (stmt == LY_STMT_ARGUMENT) {
free(a[1]);
}
} else {
lydict_remove(ctx, str[0]);
if (stmt == LY_STMT_BELONGSTO) {
lydict_remove(ctx, str[1]);
}
}
}
void
lys_extension_instances_free(struct ly_ctx *ctx, struct lys_ext_instance **e, unsigned int size,
void (*private_destructor)(const struct lys_node *node, void *priv))
{
unsigned int i, j, k;
struct lyext_substmt *substmt;
void **pp, **start;
struct lys_node *siter, *snext;
#define EXTCOMPLEX_FREE_STRUCT(STMT, TYPE, FUNC, FREE, ARGS...) \
pp = lys_ext_complex_get_substmt(STMT, (struct lys_ext_instance_complex *)e[i], NULL); \
if (!pp || !(*pp)) { break; } \
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */ \
for (start = pp = *pp; *pp; pp++) { \
FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \
if (FREE) { free(*pp); } \
} \
free(start); \
} else { /* single item */ \
FUNC(ctx, (TYPE *)(*pp), ##ARGS, private_destructor); \
if (FREE) { free(*pp); } \
}
if (!size || !e) {
return;
}
for (i = 0; i < size; i++) {
if (!e[i]) {
continue;
}
if (e[i]->flags & (LYEXT_OPT_INHERIT)) {
/* no free, this is just a shadow copy of the original extension instance */
} else {
if (e[i]->flags & (LYEXT_OPT_YANG)) {
free(e[i]->def); /* remove name of instance extension */
e[i]->def = NULL;
yang_free_ext_data((struct yang_ext_substmt *)e[i]->parent); /* remove backup part of yang file */
}
/* remove private object */
if (e[i]->priv && private_destructor) {
private_destructor((struct lys_node*)e[i], e[i]->priv);
}
lys_extension_instances_free(ctx, e[i]->ext, e[i]->ext_size, private_destructor);
lydict_remove(ctx, e[i]->arg_value);
}
if (e[i]->def && e[i]->def->plugin && e[i]->def->plugin->type == LYEXT_COMPLEX
&& ((e[i]->flags & LYEXT_OPT_CONTENT) == 0)) {
substmt = ((struct lys_ext_instance_complex *)e[i])->substmt;
for (j = 0; substmt[j].stmt; j++) {
switch(substmt[j].stmt) {
case LY_STMT_DESCRIPTION:
case LY_STMT_REFERENCE:
case LY_STMT_UNITS:
case LY_STMT_ARGUMENT:
case LY_STMT_DEFAULT:
case LY_STMT_ERRTAG:
case LY_STMT_ERRMSG:
case LY_STMT_PREFIX:
case LY_STMT_NAMESPACE:
case LY_STMT_PRESENCE:
case LY_STMT_REVISIONDATE:
case LY_STMT_KEY:
case LY_STMT_BASE:
case LY_STMT_BELONGSTO:
case LY_STMT_CONTACT:
case LY_STMT_ORGANIZATION:
case LY_STMT_PATH:
lys_extcomplex_free_str(ctx, (struct lys_ext_instance_complex *)e[i], substmt[j].stmt);
break;
case LY_STMT_TYPE:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPE, struct lys_type, lys_type_free, 1);
break;
case LY_STMT_TYPEDEF:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_TYPEDEF, struct lys_tpdf, lys_tpdf_free, 1);
break;
case LY_STMT_IFFEATURE:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_IFFEATURE, struct lys_iffeature, lys_iffeature_free, 0, 1, 0);
break;
case LY_STMT_MAX:
case LY_STMT_MIN:
case LY_STMT_POSITION:
case LY_STMT_VALUE:
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
if (substmt[j].cardinality >= LY_STMT_CARD_SOME && *pp) {
for(k = 0; ((uint32_t**)(*pp))[k]; k++) {
free(((uint32_t**)(*pp))[k]);
}
}
free(*pp);
break;
case LY_STMT_DIGITS:
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) {
/* free the array */
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
free(*pp);
}
break;
case LY_STMT_MODULE:
/* modules are part of the context, so they will be freed there */
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) {
/* free the array */
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
free(*pp);
}
break;
case LY_STMT_ACTION:
case LY_STMT_ANYDATA:
case LY_STMT_ANYXML:
case LY_STMT_CASE:
case LY_STMT_CHOICE:
case LY_STMT_CONTAINER:
case LY_STMT_GROUPING:
case LY_STMT_INPUT:
case LY_STMT_LEAF:
case LY_STMT_LEAFLIST:
case LY_STMT_LIST:
case LY_STMT_NOTIFICATION:
case LY_STMT_OUTPUT:
case LY_STMT_RPC:
case LY_STMT_USES:
pp = (void**)&((struct lys_ext_instance_complex *)e[i])->content[substmt[j].offset];
LY_TREE_FOR_SAFE((struct lys_node *)(*pp), snext, siter) {
lys_node_free(siter, NULL, 0);
}
*pp = NULL;
break;
case LY_STMT_UNIQUE:
pp = lys_ext_complex_get_substmt(LY_STMT_UNIQUE, (struct lys_ext_instance_complex *)e[i], NULL);
if (!pp || !(*pp)) {
break;
}
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */
for (start = pp = *pp; *pp; pp++) {
for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) {
lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]);
}
free((*(struct lys_unique**)pp)->expr);
free(*pp);
}
free(start);
} else { /* single item */
for (k = 0; k < (*(struct lys_unique**)pp)->expr_size; k++) {
lydict_remove(ctx, (*(struct lys_unique**)pp)->expr[k]);
}
free((*(struct lys_unique**)pp)->expr);
free(*pp);
}
break;
case LY_STMT_LENGTH:
case LY_STMT_MUST:
case LY_STMT_PATTERN:
case LY_STMT_RANGE:
EXTCOMPLEX_FREE_STRUCT(substmt[j].stmt, struct lys_restr, lys_restr_free, 1);
break;
case LY_STMT_WHEN:
EXTCOMPLEX_FREE_STRUCT(LY_STMT_WHEN, struct lys_when, lys_when_free, 0);
break;
case LY_STMT_REVISION:
pp = lys_ext_complex_get_substmt(LY_STMT_REVISION, (struct lys_ext_instance_complex *)e[i], NULL);
if (!pp || !(*pp)) {
break;
}
if (substmt[j].cardinality >= LY_STMT_CARD_SOME) { /* process array */
for (start = pp = *pp; *pp; pp++) {
lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc);
lydict_remove(ctx, (*(struct lys_revision**)pp)->ref);
lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext,
(*(struct lys_revision**)pp)->ext_size, private_destructor);
free(*pp);
}
free(start);
} else { /* single item */
lydict_remove(ctx, (*(struct lys_revision**)pp)->dsc);
lydict_remove(ctx, (*(struct lys_revision**)pp)->ref);
lys_extension_instances_free(ctx, (*(struct lys_revision**)pp)->ext,
(*(struct lys_revision**)pp)->ext_size, private_destructor);
free(*pp);
}
break;
default:
/* nothing to free */
break;
}
}
}
free(e[i]);
}
free(e);
#undef EXTCOMPLEX_FREE_STRUCT
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_1359_3 |
crossvul-cpp_data_good_4946_7 | #include "cache.h"
#include "tag.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
#include "diff.h"
#include "refs.h"
#include "revision.h"
#include "graph.h"
#include "grep.h"
#include "reflog-walk.h"
#include "patch-ids.h"
#include "decorate.h"
#include "log-tree.h"
#include "string-list.h"
#include "line-log.h"
#include "mailmap.h"
#include "commit-slab.h"
#include "dir.h"
#include "cache-tree.h"
#include "bisect.h"
volatile show_early_output_fn_t show_early_output;
static const char *term_bad;
static const char *term_good;
void show_object_with_name(FILE *out, struct object *obj, const char *name)
{
const char *p;
fprintf(out, "%s ", oid_to_hex(&obj->oid));
for (p = name; *p && *p != '\n'; p++)
fputc(*p, out);
fputc('\n', out);
}
static void mark_blob_uninteresting(struct blob *blob)
{
if (!blob)
return;
if (blob->object.flags & UNINTERESTING)
return;
blob->object.flags |= UNINTERESTING;
}
static void mark_tree_contents_uninteresting(struct tree *tree)
{
struct tree_desc desc;
struct name_entry entry;
struct object *obj = &tree->object;
if (!has_object_file(&obj->oid))
return;
if (parse_tree(tree) < 0)
die("bad tree %s", oid_to_hex(&obj->oid));
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
switch (object_type(entry.mode)) {
case OBJ_TREE:
mark_tree_uninteresting(lookup_tree(entry.sha1));
break;
case OBJ_BLOB:
mark_blob_uninteresting(lookup_blob(entry.sha1));
break;
default:
/* Subproject commit - not in this repository */
break;
}
}
/*
* We don't care about the tree any more
* after it has been marked uninteresting.
*/
free_tree_buffer(tree);
}
void mark_tree_uninteresting(struct tree *tree)
{
struct object *obj;
if (!tree)
return;
obj = &tree->object;
if (obj->flags & UNINTERESTING)
return;
obj->flags |= UNINTERESTING;
mark_tree_contents_uninteresting(tree);
}
void mark_parents_uninteresting(struct commit *commit)
{
struct commit_list *parents = NULL, *l;
for (l = commit->parents; l; l = l->next)
commit_list_insert(l->item, &parents);
while (parents) {
struct commit *commit = pop_commit(&parents);
while (commit) {
/*
* A missing commit is ok iff its parent is marked
* uninteresting.
*
* We just mark such a thing parsed, so that when
* it is popped next time around, we won't be trying
* to parse it and get an error.
*/
if (!has_object_file(&commit->object.oid))
commit->object.parsed = 1;
if (commit->object.flags & UNINTERESTING)
break;
commit->object.flags |= UNINTERESTING;
/*
* Normally we haven't parsed the parent
* yet, so we won't have a parent of a parent
* here. However, it may turn out that we've
* reached this commit some other way (where it
* wasn't uninteresting), in which case we need
* to mark its parents recursively too..
*/
if (!commit->parents)
break;
for (l = commit->parents->next; l; l = l->next)
commit_list_insert(l->item, &parents);
commit = commit->parents->item;
}
}
}
static void add_pending_object_with_path(struct rev_info *revs,
struct object *obj,
const char *name, unsigned mode,
const char *path)
{
if (!obj)
return;
if (revs->no_walk && (obj->flags & UNINTERESTING))
revs->no_walk = 0;
if (revs->reflog_info && obj->type == OBJ_COMMIT) {
struct strbuf buf = STRBUF_INIT;
int len = interpret_branch_name(name, 0, &buf);
int st;
if (0 < len && name[len] && buf.len)
strbuf_addstr(&buf, name + len);
st = add_reflog_for_walk(revs->reflog_info,
(struct commit *)obj,
buf.buf[0] ? buf.buf: name);
strbuf_release(&buf);
if (st)
return;
}
add_object_array_with_path(obj, name, &revs->pending, mode, path);
}
static void add_pending_object_with_mode(struct rev_info *revs,
struct object *obj,
const char *name, unsigned mode)
{
add_pending_object_with_path(revs, obj, name, mode, NULL);
}
void add_pending_object(struct rev_info *revs,
struct object *obj, const char *name)
{
add_pending_object_with_mode(revs, obj, name, S_IFINVALID);
}
void add_head_to_pending(struct rev_info *revs)
{
unsigned char sha1[20];
struct object *obj;
if (get_sha1("HEAD", sha1))
return;
obj = parse_object(sha1);
if (!obj)
return;
add_pending_object(revs, obj, "HEAD");
}
static struct object *get_reference(struct rev_info *revs, const char *name,
const unsigned char *sha1,
unsigned int flags)
{
struct object *object;
object = parse_object(sha1);
if (!object) {
if (revs->ignore_missing)
return object;
die("bad object %s", name);
}
object->flags |= flags;
return object;
}
void add_pending_sha1(struct rev_info *revs, const char *name,
const unsigned char *sha1, unsigned int flags)
{
struct object *object = get_reference(revs, name, sha1, flags);
add_pending_object(revs, object, name);
}
static struct commit *handle_commit(struct rev_info *revs,
struct object_array_entry *entry)
{
struct object *object = entry->item;
const char *name = entry->name;
const char *path = entry->path;
unsigned int mode = entry->mode;
unsigned long flags = object->flags;
/*
* Tag object? Look what it points to..
*/
while (object->type == OBJ_TAG) {
struct tag *tag = (struct tag *) object;
if (revs->tag_objects && !(flags & UNINTERESTING))
add_pending_object(revs, object, tag->tag);
if (!tag->tagged)
die("bad tag");
object = parse_object(tag->tagged->oid.hash);
if (!object) {
if (flags & UNINTERESTING)
return NULL;
die("bad object %s", oid_to_hex(&tag->tagged->oid));
}
object->flags |= flags;
/*
* We'll handle the tagged object by looping or dropping
* through to the non-tag handlers below. Do not
* propagate path data from the tag's pending entry.
*/
path = NULL;
mode = 0;
}
/*
* Commit object? Just return it, we'll do all the complex
* reachability crud.
*/
if (object->type == OBJ_COMMIT) {
struct commit *commit = (struct commit *)object;
if (parse_commit(commit) < 0)
die("unable to parse commit %s", name);
if (flags & UNINTERESTING) {
mark_parents_uninteresting(commit);
revs->limited = 1;
}
if (revs->show_source && !commit->util)
commit->util = xstrdup(name);
return commit;
}
/*
* Tree object? Either mark it uninteresting, or add it
* to the list of objects to look at later..
*/
if (object->type == OBJ_TREE) {
struct tree *tree = (struct tree *)object;
if (!revs->tree_objects)
return NULL;
if (flags & UNINTERESTING) {
mark_tree_contents_uninteresting(tree);
return NULL;
}
add_pending_object_with_path(revs, object, name, mode, path);
return NULL;
}
/*
* Blob object? You know the drill by now..
*/
if (object->type == OBJ_BLOB) {
if (!revs->blob_objects)
return NULL;
if (flags & UNINTERESTING)
return NULL;
add_pending_object_with_path(revs, object, name, mode, path);
return NULL;
}
die("%s is unknown object", name);
}
static int everybody_uninteresting(struct commit_list *orig,
struct commit **interesting_cache)
{
struct commit_list *list = orig;
if (*interesting_cache) {
struct commit *commit = *interesting_cache;
if (!(commit->object.flags & UNINTERESTING))
return 0;
}
while (list) {
struct commit *commit = list->item;
list = list->next;
if (commit->object.flags & UNINTERESTING)
continue;
*interesting_cache = commit;
return 0;
}
return 1;
}
/*
* A definition of "relevant" commit that we can use to simplify limited graphs
* by eliminating side branches.
*
* A "relevant" commit is one that is !UNINTERESTING (ie we are including it
* in our list), or that is a specified BOTTOM commit. Then after computing
* a limited list, during processing we can generally ignore boundary merges
* coming from outside the graph, (ie from irrelevant parents), and treat
* those merges as if they were single-parent. TREESAME is defined to consider
* only relevant parents, if any. If we are TREESAME to our on-graph parents,
* we don't care if we were !TREESAME to non-graph parents.
*
* Treating bottom commits as relevant ensures that a limited graph's
* connection to the actual bottom commit is not viewed as a side branch, but
* treated as part of the graph. For example:
*
* ....Z...A---X---o---o---B
* . /
* W---Y
*
* When computing "A..B", the A-X connection is at least as important as
* Y-X, despite A being flagged UNINTERESTING.
*
* And when computing --ancestry-path "A..B", the A-X connection is more
* important than Y-X, despite both A and Y being flagged UNINTERESTING.
*/
static inline int relevant_commit(struct commit *commit)
{
return (commit->object.flags & (UNINTERESTING | BOTTOM)) != UNINTERESTING;
}
/*
* Return a single relevant commit from a parent list. If we are a TREESAME
* commit, and this selects one of our parents, then we can safely simplify to
* that parent.
*/
static struct commit *one_relevant_parent(const struct rev_info *revs,
struct commit_list *orig)
{
struct commit_list *list = orig;
struct commit *relevant = NULL;
if (!orig)
return NULL;
/*
* For 1-parent commits, or if first-parent-only, then return that
* first parent (even if not "relevant" by the above definition).
* TREESAME will have been set purely on that parent.
*/
if (revs->first_parent_only || !orig->next)
return orig->item;
/*
* For multi-parent commits, identify a sole relevant parent, if any.
* If we have only one relevant parent, then TREESAME will be set purely
* with regard to that parent, and we can simplify accordingly.
*
* If we have more than one relevant parent, or no relevant parents
* (and multiple irrelevant ones), then we can't select a parent here
* and return NULL.
*/
while (list) {
struct commit *commit = list->item;
list = list->next;
if (relevant_commit(commit)) {
if (relevant)
return NULL;
relevant = commit;
}
}
return relevant;
}
/*
* The goal is to get REV_TREE_NEW as the result only if the
* diff consists of all '+' (and no other changes), REV_TREE_OLD
* if the whole diff is removal of old data, and otherwise
* REV_TREE_DIFFERENT (of course if the trees are the same we
* want REV_TREE_SAME).
* That means that once we get to REV_TREE_DIFFERENT, we do not
* have to look any further.
*/
static int tree_difference = REV_TREE_SAME;
static void file_add_remove(struct diff_options *options,
int addremove, unsigned mode,
const unsigned char *sha1,
int sha1_valid,
const char *fullpath, unsigned dirty_submodule)
{
int diff = addremove == '+' ? REV_TREE_NEW : REV_TREE_OLD;
tree_difference |= diff;
if (tree_difference == REV_TREE_DIFFERENT)
DIFF_OPT_SET(options, HAS_CHANGES);
}
static void file_change(struct diff_options *options,
unsigned old_mode, unsigned new_mode,
const unsigned char *old_sha1,
const unsigned char *new_sha1,
int old_sha1_valid, int new_sha1_valid,
const char *fullpath,
unsigned old_dirty_submodule, unsigned new_dirty_submodule)
{
tree_difference = REV_TREE_DIFFERENT;
DIFF_OPT_SET(options, HAS_CHANGES);
}
static int rev_compare_tree(struct rev_info *revs,
struct commit *parent, struct commit *commit)
{
struct tree *t1 = parent->tree;
struct tree *t2 = commit->tree;
if (!t1)
return REV_TREE_NEW;
if (!t2)
return REV_TREE_OLD;
if (revs->simplify_by_decoration) {
/*
* If we are simplifying by decoration, then the commit
* is worth showing if it has a tag pointing at it.
*/
if (get_name_decoration(&commit->object))
return REV_TREE_DIFFERENT;
/*
* A commit that is not pointed by a tag is uninteresting
* if we are not limited by path. This means that you will
* see the usual "commits that touch the paths" plus any
* tagged commit by specifying both --simplify-by-decoration
* and pathspec.
*/
if (!revs->prune_data.nr)
return REV_TREE_SAME;
}
tree_difference = REV_TREE_SAME;
DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
if (diff_tree_sha1(t1->object.oid.hash, t2->object.oid.hash, "",
&revs->pruning) < 0)
return REV_TREE_DIFFERENT;
return tree_difference;
}
static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
{
int retval;
struct tree *t1 = commit->tree;
if (!t1)
return 0;
tree_difference = REV_TREE_SAME;
DIFF_OPT_CLR(&revs->pruning, HAS_CHANGES);
retval = diff_tree_sha1(NULL, t1->object.oid.hash, "", &revs->pruning);
return retval >= 0 && (tree_difference == REV_TREE_SAME);
}
struct treesame_state {
unsigned int nparents;
unsigned char treesame[FLEX_ARRAY];
};
static struct treesame_state *initialise_treesame(struct rev_info *revs, struct commit *commit)
{
unsigned n = commit_list_count(commit->parents);
struct treesame_state *st = xcalloc(1, sizeof(*st) + n);
st->nparents = n;
add_decoration(&revs->treesame, &commit->object, st);
return st;
}
/*
* Must be called immediately after removing the nth_parent from a commit's
* parent list, if we are maintaining the per-parent treesame[] decoration.
* This does not recalculate the master TREESAME flag - update_treesame()
* should be called to update it after a sequence of treesame[] modifications
* that may have affected it.
*/
static int compact_treesame(struct rev_info *revs, struct commit *commit, unsigned nth_parent)
{
struct treesame_state *st;
int old_same;
if (!commit->parents) {
/*
* Have just removed the only parent from a non-merge.
* Different handling, as we lack decoration.
*/
if (nth_parent != 0)
die("compact_treesame %u", nth_parent);
old_same = !!(commit->object.flags & TREESAME);
if (rev_same_tree_as_empty(revs, commit))
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
return old_same;
}
st = lookup_decoration(&revs->treesame, &commit->object);
if (!st || nth_parent >= st->nparents)
die("compact_treesame %u", nth_parent);
old_same = st->treesame[nth_parent];
memmove(st->treesame + nth_parent,
st->treesame + nth_parent + 1,
st->nparents - nth_parent - 1);
/*
* If we've just become a non-merge commit, update TREESAME
* immediately, and remove the no-longer-needed decoration.
* If still a merge, defer update until update_treesame().
*/
if (--st->nparents == 1) {
if (commit->parents->next)
die("compact_treesame parents mismatch");
if (st->treesame[0] && revs->dense)
commit->object.flags |= TREESAME;
else
commit->object.flags &= ~TREESAME;
free(add_decoration(&revs->treesame, &commit->object, NULL));
}
return old_same;
}
static unsigned update_treesame(struct rev_info *revs, struct commit *commit)
{
if (commit->parents && commit->parents->next) {
unsigned n;
struct treesame_state *st;
struct commit_list *p;
unsigned relevant_parents;
unsigned relevant_change, irrelevant_change;
st = lookup_decoration(&revs->treesame, &commit->object);
if (!st)
die("update_treesame %s", oid_to_hex(&commit->object.oid));
relevant_parents = 0;
relevant_change = irrelevant_change = 0;
for (p = commit->parents, n = 0; p; n++, p = p->next) {
if (relevant_commit(p->item)) {
relevant_change |= !st->treesame[n];
relevant_parents++;
} else
irrelevant_change |= !st->treesame[n];
}
if (relevant_parents ? relevant_change : irrelevant_change)
commit->object.flags &= ~TREESAME;
else
commit->object.flags |= TREESAME;
}
return commit->object.flags & TREESAME;
}
static inline int limiting_can_increase_treesame(const struct rev_info *revs)
{
/*
* TREESAME is irrelevant unless prune && dense;
* if simplify_history is set, we can't have a mixture of TREESAME and
* !TREESAME INTERESTING parents (and we don't have treesame[]
* decoration anyway);
* if first_parent_only is set, then the TREESAME flag is locked
* against the first parent (and again we lack treesame[] decoration).
*/
return revs->prune && revs->dense &&
!revs->simplify_history &&
!revs->first_parent_only;
}
static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp, *parent;
struct treesame_state *ts = NULL;
int relevant_change = 0, irrelevant_change = 0;
int relevant_parents, nth_parent;
/*
* If we don't do pruning, everything is interesting
*/
if (!revs->prune)
return;
if (!commit->tree)
return;
if (!commit->parents) {
if (rev_same_tree_as_empty(revs, commit))
commit->object.flags |= TREESAME;
return;
}
/*
* Normal non-merge commit? If we don't want to make the
* history dense, we consider it always to be a change..
*/
if (!revs->dense && !commit->parents->next)
return;
for (pp = &commit->parents, nth_parent = 0, relevant_parents = 0;
(parent = *pp) != NULL;
pp = &parent->next, nth_parent++) {
struct commit *p = parent->item;
if (relevant_commit(p))
relevant_parents++;
if (nth_parent == 1) {
/*
* This our second loop iteration - so we now know
* we're dealing with a merge.
*
* Do not compare with later parents when we care only about
* the first parent chain, in order to avoid derailing the
* traversal to follow a side branch that brought everything
* in the path we are limited to by the pathspec.
*/
if (revs->first_parent_only)
break;
/*
* If this will remain a potentially-simplifiable
* merge, remember per-parent treesame if needed.
* Initialise the array with the comparison from our
* first iteration.
*/
if (revs->treesame.name &&
!revs->simplify_history &&
!(commit->object.flags & UNINTERESTING)) {
ts = initialise_treesame(revs, commit);
if (!(irrelevant_change || relevant_change))
ts->treesame[0] = 1;
}
}
if (parse_commit(p) < 0)
die("cannot simplify commit %s (because of %s)",
oid_to_hex(&commit->object.oid),
oid_to_hex(&p->object.oid));
switch (rev_compare_tree(revs, p, commit)) {
case REV_TREE_SAME:
if (!revs->simplify_history || !relevant_commit(p)) {
/* Even if a merge with an uninteresting
* side branch brought the entire change
* we are interested in, we do not want
* to lose the other branches of this
* merge, so we just keep going.
*/
if (ts)
ts->treesame[nth_parent] = 1;
continue;
}
parent->next = NULL;
commit->parents = parent;
commit->object.flags |= TREESAME;
return;
case REV_TREE_NEW:
if (revs->remove_empty_trees &&
rev_same_tree_as_empty(revs, p)) {
/* We are adding all the specified
* paths from this parent, so the
* history beyond this parent is not
* interesting. Remove its parents
* (they are grandparents for us).
* IOW, we pretend this parent is a
* "root" commit.
*/
if (parse_commit(p) < 0)
die("cannot simplify commit %s (invalid %s)",
oid_to_hex(&commit->object.oid),
oid_to_hex(&p->object.oid));
p->parents = NULL;
}
/* fallthrough */
case REV_TREE_OLD:
case REV_TREE_DIFFERENT:
if (relevant_commit(p))
relevant_change = 1;
else
irrelevant_change = 1;
continue;
}
die("bad tree compare for commit %s", oid_to_hex(&commit->object.oid));
}
/*
* TREESAME is straightforward for single-parent commits. For merge
* commits, it is most useful to define it so that "irrelevant"
* parents cannot make us !TREESAME - if we have any relevant
* parents, then we only consider TREESAMEness with respect to them,
* allowing irrelevant merges from uninteresting branches to be
* simplified away. Only if we have only irrelevant parents do we
* base TREESAME on them. Note that this logic is replicated in
* update_treesame, which should be kept in sync.
*/
if (relevant_parents ? !relevant_change : !irrelevant_change)
commit->object.flags |= TREESAME;
}
static void commit_list_insert_by_date_cached(struct commit *p, struct commit_list **head,
struct commit_list *cached_base, struct commit_list **cache)
{
struct commit_list *new_entry;
if (cached_base && p->date < cached_base->item->date)
new_entry = commit_list_insert_by_date(p, &cached_base->next);
else
new_entry = commit_list_insert_by_date(p, head);
if (cache && (!*cache || p->date < (*cache)->item->date))
*cache = new_entry;
}
static int add_parents_to_list(struct rev_info *revs, struct commit *commit,
struct commit_list **list, struct commit_list **cache_ptr)
{
struct commit_list *parent = commit->parents;
unsigned left_flag;
struct commit_list *cached_base = cache_ptr ? *cache_ptr : NULL;
if (commit->object.flags & ADDED)
return 0;
commit->object.flags |= ADDED;
if (revs->include_check &&
!revs->include_check(commit, revs->include_check_data))
return 0;
/*
* If the commit is uninteresting, don't try to
* prune parents - we want the maximal uninteresting
* set.
*
* Normally we haven't parsed the parent
* yet, so we won't have a parent of a parent
* here. However, it may turn out that we've
* reached this commit some other way (where it
* wasn't uninteresting), in which case we need
* to mark its parents recursively too..
*/
if (commit->object.flags & UNINTERESTING) {
while (parent) {
struct commit *p = parent->item;
parent = parent->next;
if (p)
p->object.flags |= UNINTERESTING;
if (parse_commit_gently(p, 1) < 0)
continue;
if (p->parents)
mark_parents_uninteresting(p);
if (p->object.flags & SEEN)
continue;
p->object.flags |= SEEN;
commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
}
return 0;
}
/*
* Ok, the commit wasn't uninteresting. Try to
* simplify the commit history and find the parent
* that has no differences in the path set if one exists.
*/
try_to_simplify_commit(revs, commit);
if (revs->no_walk)
return 0;
left_flag = (commit->object.flags & SYMMETRIC_LEFT);
for (parent = commit->parents; parent; parent = parent->next) {
struct commit *p = parent->item;
if (parse_commit_gently(p, revs->ignore_missing_links) < 0)
return -1;
if (revs->show_source && !p->util)
p->util = commit->util;
p->object.flags |= left_flag;
if (!(p->object.flags & SEEN)) {
p->object.flags |= SEEN;
commit_list_insert_by_date_cached(p, list, cached_base, cache_ptr);
}
if (revs->first_parent_only)
break;
}
return 0;
}
static void cherry_pick_list(struct commit_list *list, struct rev_info *revs)
{
struct commit_list *p;
int left_count = 0, right_count = 0;
int left_first;
struct patch_ids ids;
unsigned cherry_flag;
/* First count the commits on the left and on the right */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
;
else if (flags & SYMMETRIC_LEFT)
left_count++;
else
right_count++;
}
if (!left_count || !right_count)
return;
left_first = left_count < right_count;
init_patch_ids(&ids);
ids.diffopts.pathspec = revs->diffopt.pathspec;
/* Compute patch-ids for one side */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
continue;
/*
* If we have fewer left, left_first is set and we omit
* commits on the right branch in this loop. If we have
* fewer right, we skip the left ones.
*/
if (left_first != !!(flags & SYMMETRIC_LEFT))
continue;
commit->util = add_commit_patch_id(commit, &ids);
}
/* either cherry_mark or cherry_pick are true */
cherry_flag = revs->cherry_mark ? PATCHSAME : SHOWN;
/* Check the other side */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
struct patch_id *id;
unsigned flags = commit->object.flags;
if (flags & BOUNDARY)
continue;
/*
* If we have fewer left, left_first is set and we omit
* commits on the left branch in this loop.
*/
if (left_first == !!(flags & SYMMETRIC_LEFT))
continue;
/*
* Have we seen the same patch id?
*/
id = has_commit_patch_id(commit, &ids);
if (!id)
continue;
id->seen = 1;
commit->object.flags |= cherry_flag;
}
/* Now check the original side for seen ones */
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
struct patch_id *ent;
ent = commit->util;
if (!ent)
continue;
if (ent->seen)
commit->object.flags |= cherry_flag;
commit->util = NULL;
}
free_patch_ids(&ids);
}
/* How many extra uninteresting commits we want to see.. */
#define SLOP 5
static int still_interesting(struct commit_list *src, unsigned long date, int slop,
struct commit **interesting_cache)
{
/*
* No source list at all? We're definitely done..
*/
if (!src)
return 0;
/*
* Does the destination list contain entries with a date
* before the source list? Definitely _not_ done.
*/
if (date <= src->item->date)
return SLOP;
/*
* Does the source list still have interesting commits in
* it? Definitely not done..
*/
if (!everybody_uninteresting(src, interesting_cache))
return SLOP;
/* Ok, we're closing in.. */
return slop-1;
}
/*
* "rev-list --ancestry-path A..B" computes commits that are ancestors
* of B but not ancestors of A but further limits the result to those
* that are descendants of A. This takes the list of bottom commits and
* the result of "A..B" without --ancestry-path, and limits the latter
* further to the ones that can reach one of the commits in "bottom".
*/
static void limit_to_ancestry(struct commit_list *bottom, struct commit_list *list)
{
struct commit_list *p;
struct commit_list *rlist = NULL;
int made_progress;
/*
* Reverse the list so that it will be likely that we would
* process parents before children.
*/
for (p = list; p; p = p->next)
commit_list_insert(p->item, &rlist);
for (p = bottom; p; p = p->next)
p->item->object.flags |= TMP_MARK;
/*
* Mark the ones that can reach bottom commits in "list",
* in a bottom-up fashion.
*/
do {
made_progress = 0;
for (p = rlist; p; p = p->next) {
struct commit *c = p->item;
struct commit_list *parents;
if (c->object.flags & (TMP_MARK | UNINTERESTING))
continue;
for (parents = c->parents;
parents;
parents = parents->next) {
if (!(parents->item->object.flags & TMP_MARK))
continue;
c->object.flags |= TMP_MARK;
made_progress = 1;
break;
}
}
} while (made_progress);
/*
* NEEDSWORK: decide if we want to remove parents that are
* not marked with TMP_MARK from commit->parents for commits
* in the resulting list. We may not want to do that, though.
*/
/*
* The ones that are not marked with TMP_MARK are uninteresting
*/
for (p = list; p; p = p->next) {
struct commit *c = p->item;
if (c->object.flags & TMP_MARK)
continue;
c->object.flags |= UNINTERESTING;
}
/* We are done with the TMP_MARK */
for (p = list; p; p = p->next)
p->item->object.flags &= ~TMP_MARK;
for (p = bottom; p; p = p->next)
p->item->object.flags &= ~TMP_MARK;
free_commit_list(rlist);
}
/*
* Before walking the history, keep the set of "negative" refs the
* caller has asked to exclude.
*
* This is used to compute "rev-list --ancestry-path A..B", as we need
* to filter the result of "A..B" further to the ones that can actually
* reach A.
*/
static struct commit_list *collect_bottom_commits(struct commit_list *list)
{
struct commit_list *elem, *bottom = NULL;
for (elem = list; elem; elem = elem->next)
if (elem->item->object.flags & BOTTOM)
commit_list_insert(elem->item, &bottom);
return bottom;
}
/* Assumes either left_only or right_only is set */
static void limit_left_right(struct commit_list *list, struct rev_info *revs)
{
struct commit_list *p;
for (p = list; p; p = p->next) {
struct commit *commit = p->item;
if (revs->right_only) {
if (commit->object.flags & SYMMETRIC_LEFT)
commit->object.flags |= SHOWN;
} else /* revs->left_only is set */
if (!(commit->object.flags & SYMMETRIC_LEFT))
commit->object.flags |= SHOWN;
}
}
static int limit_list(struct rev_info *revs)
{
int slop = SLOP;
unsigned long date = ~0ul;
struct commit_list *list = revs->commits;
struct commit_list *newlist = NULL;
struct commit_list **p = &newlist;
struct commit_list *bottom = NULL;
struct commit *interesting_cache = NULL;
if (revs->ancestry_path) {
bottom = collect_bottom_commits(list);
if (!bottom)
die("--ancestry-path given but there are no bottom commits");
}
while (list) {
struct commit *commit = pop_commit(&list);
struct object *obj = &commit->object;
show_early_output_fn_t show;
if (commit == interesting_cache)
interesting_cache = NULL;
if (revs->max_age != -1 && (commit->date < revs->max_age))
obj->flags |= UNINTERESTING;
if (add_parents_to_list(revs, commit, &list, NULL) < 0)
return -1;
if (obj->flags & UNINTERESTING) {
mark_parents_uninteresting(commit);
if (revs->show_all)
p = &commit_list_insert(commit, p)->next;
slop = still_interesting(list, date, slop, &interesting_cache);
if (slop)
continue;
/* If showing all, add the whole pending list to the end */
if (revs->show_all)
*p = list;
break;
}
if (revs->min_age != -1 && (commit->date > revs->min_age))
continue;
date = commit->date;
p = &commit_list_insert(commit, p)->next;
show = show_early_output;
if (!show)
continue;
show(revs, newlist);
show_early_output = NULL;
}
if (revs->cherry_pick || revs->cherry_mark)
cherry_pick_list(newlist, revs);
if (revs->left_only || revs->right_only)
limit_left_right(newlist, revs);
if (bottom) {
limit_to_ancestry(bottom, newlist);
free_commit_list(bottom);
}
/*
* Check if any commits have become TREESAME by some of their parents
* becoming UNINTERESTING.
*/
if (limiting_can_increase_treesame(revs))
for (list = newlist; list; list = list->next) {
struct commit *c = list->item;
if (c->object.flags & (UNINTERESTING | TREESAME))
continue;
update_treesame(revs, c);
}
revs->commits = newlist;
return 0;
}
/*
* Add an entry to refs->cmdline with the specified information.
* *name is copied.
*/
static void add_rev_cmdline(struct rev_info *revs,
struct object *item,
const char *name,
int whence,
unsigned flags)
{
struct rev_cmdline_info *info = &revs->cmdline;
int nr = info->nr;
ALLOC_GROW(info->rev, nr + 1, info->alloc);
info->rev[nr].item = item;
info->rev[nr].name = xstrdup(name);
info->rev[nr].whence = whence;
info->rev[nr].flags = flags;
info->nr++;
}
static void add_rev_cmdline_list(struct rev_info *revs,
struct commit_list *commit_list,
int whence,
unsigned flags)
{
while (commit_list) {
struct object *object = &commit_list->item->object;
add_rev_cmdline(revs, object, oid_to_hex(&object->oid),
whence, flags);
commit_list = commit_list->next;
}
}
struct all_refs_cb {
int all_flags;
int warned_bad_reflog;
struct rev_info *all_revs;
const char *name_for_errormsg;
};
int ref_excluded(struct string_list *ref_excludes, const char *path)
{
struct string_list_item *item;
if (!ref_excludes)
return 0;
for_each_string_list_item(item, ref_excludes) {
if (!wildmatch(item->string, path, 0, NULL))
return 1;
}
return 0;
}
static int handle_one_ref(const char *path, const struct object_id *oid,
int flag, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
struct object *object;
if (ref_excluded(cb->all_revs->ref_excludes, path))
return 0;
object = get_reference(cb->all_revs, path, oid->hash, cb->all_flags);
add_rev_cmdline(cb->all_revs, object, path, REV_CMD_REF, cb->all_flags);
add_pending_sha1(cb->all_revs, path, oid->hash, cb->all_flags);
return 0;
}
static void init_all_refs_cb(struct all_refs_cb *cb, struct rev_info *revs,
unsigned flags)
{
cb->all_revs = revs;
cb->all_flags = flags;
}
void clear_ref_exclusion(struct string_list **ref_excludes_p)
{
if (*ref_excludes_p) {
string_list_clear(*ref_excludes_p, 0);
free(*ref_excludes_p);
}
*ref_excludes_p = NULL;
}
void add_ref_exclusion(struct string_list **ref_excludes_p, const char *exclude)
{
if (!*ref_excludes_p) {
*ref_excludes_p = xcalloc(1, sizeof(**ref_excludes_p));
(*ref_excludes_p)->strdup_strings = 1;
}
string_list_append(*ref_excludes_p, exclude);
}
static void handle_refs(const char *submodule, struct rev_info *revs, unsigned flags,
int (*for_each)(const char *, each_ref_fn, void *))
{
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, flags);
for_each(submodule, handle_one_ref, &cb);
}
static void handle_one_reflog_commit(unsigned char *sha1, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
if (!is_null_sha1(sha1)) {
struct object *o = parse_object(sha1);
if (o) {
o->flags |= cb->all_flags;
/* ??? CMDLINEFLAGS ??? */
add_pending_object(cb->all_revs, o, "");
}
else if (!cb->warned_bad_reflog) {
warning("reflog of '%s' references pruned commits",
cb->name_for_errormsg);
cb->warned_bad_reflog = 1;
}
}
}
static int handle_one_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
const char *email, unsigned long timestamp, int tz,
const char *message, void *cb_data)
{
handle_one_reflog_commit(osha1, cb_data);
handle_one_reflog_commit(nsha1, cb_data);
return 0;
}
static int handle_one_reflog(const char *path, const struct object_id *oid,
int flag, void *cb_data)
{
struct all_refs_cb *cb = cb_data;
cb->warned_bad_reflog = 0;
cb->name_for_errormsg = path;
for_each_reflog_ent(path, handle_one_reflog_ent, cb_data);
return 0;
}
void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
{
struct all_refs_cb cb;
cb.all_revs = revs;
cb.all_flags = flags;
for_each_reflog(handle_one_reflog, &cb);
}
static void add_cache_tree(struct cache_tree *it, struct rev_info *revs,
struct strbuf *path)
{
size_t baselen = path->len;
int i;
if (it->entry_count >= 0) {
struct tree *tree = lookup_tree(it->sha1);
add_pending_object_with_path(revs, &tree->object, "",
040000, path->buf);
}
for (i = 0; i < it->subtree_nr; i++) {
struct cache_tree_sub *sub = it->down[i];
strbuf_addf(path, "%s%s", baselen ? "/" : "", sub->name);
add_cache_tree(sub->cache_tree, revs, path);
strbuf_setlen(path, baselen);
}
}
void add_index_objects_to_pending(struct rev_info *revs, unsigned flags)
{
int i;
read_cache();
for (i = 0; i < active_nr; i++) {
struct cache_entry *ce = active_cache[i];
struct blob *blob;
if (S_ISGITLINK(ce->ce_mode))
continue;
blob = lookup_blob(ce->sha1);
if (!blob)
die("unable to add index blob to traversal");
add_pending_object_with_path(revs, &blob->object, "",
ce->ce_mode, ce->name);
}
if (active_cache_tree) {
struct strbuf path = STRBUF_INIT;
add_cache_tree(active_cache_tree, revs, &path);
strbuf_release(&path);
}
}
static int add_parents_only(struct rev_info *revs, const char *arg_, int flags)
{
unsigned char sha1[20];
struct object *it;
struct commit *commit;
struct commit_list *parents;
const char *arg = arg_;
if (*arg == '^') {
flags ^= UNINTERESTING | BOTTOM;
arg++;
}
if (get_sha1_committish(arg, sha1))
return 0;
while (1) {
it = get_reference(revs, arg, sha1, 0);
if (!it && revs->ignore_missing)
return 0;
if (it->type != OBJ_TAG)
break;
if (!((struct tag*)it)->tagged)
return 0;
hashcpy(sha1, ((struct tag*)it)->tagged->oid.hash);
}
if (it->type != OBJ_COMMIT)
return 0;
commit = (struct commit *)it;
for (parents = commit->parents; parents; parents = parents->next) {
it = &parents->item->object;
it->flags |= flags;
add_rev_cmdline(revs, it, arg_, REV_CMD_PARENTS_ONLY, flags);
add_pending_object(revs, it, arg);
}
return 1;
}
void init_revisions(struct rev_info *revs, const char *prefix)
{
memset(revs, 0, sizeof(*revs));
revs->abbrev = DEFAULT_ABBREV;
revs->ignore_merges = 1;
revs->simplify_history = 1;
DIFF_OPT_SET(&revs->pruning, RECURSIVE);
DIFF_OPT_SET(&revs->pruning, QUICK);
revs->pruning.add_remove = file_add_remove;
revs->pruning.change = file_change;
revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
revs->dense = 1;
revs->prefix = prefix;
revs->max_age = -1;
revs->min_age = -1;
revs->skip_count = -1;
revs->max_count = -1;
revs->max_parents = -1;
revs->commit_format = CMIT_FMT_DEFAULT;
init_grep_defaults();
grep_init(&revs->grep_filter, prefix);
revs->grep_filter.status_only = 1;
revs->grep_filter.regflags = REG_NEWLINE;
diff_setup(&revs->diffopt);
if (prefix && !revs->diffopt.prefix) {
revs->diffopt.prefix = prefix;
revs->diffopt.prefix_length = strlen(prefix);
}
revs->notes_opt.use_default_notes = -1;
}
static void add_pending_commit_list(struct rev_info *revs,
struct commit_list *commit_list,
unsigned int flags)
{
while (commit_list) {
struct object *object = &commit_list->item->object;
object->flags |= flags;
add_pending_object(revs, object, oid_to_hex(&object->oid));
commit_list = commit_list->next;
}
}
static void prepare_show_merge(struct rev_info *revs)
{
struct commit_list *bases;
struct commit *head, *other;
unsigned char sha1[20];
const char **prune = NULL;
int i, prune_num = 1; /* counting terminating NULL */
if (get_sha1("HEAD", sha1))
die("--merge without HEAD?");
head = lookup_commit_or_die(sha1, "HEAD");
if (get_sha1("MERGE_HEAD", sha1))
die("--merge without MERGE_HEAD?");
other = lookup_commit_or_die(sha1, "MERGE_HEAD");
add_pending_object(revs, &head->object, "HEAD");
add_pending_object(revs, &other->object, "MERGE_HEAD");
bases = get_merge_bases(head, other);
add_rev_cmdline_list(revs, bases, REV_CMD_MERGE_BASE, UNINTERESTING | BOTTOM);
add_pending_commit_list(revs, bases, UNINTERESTING | BOTTOM);
free_commit_list(bases);
head->object.flags |= SYMMETRIC_LEFT;
if (!active_nr)
read_cache();
for (i = 0; i < active_nr; i++) {
const struct cache_entry *ce = active_cache[i];
if (!ce_stage(ce))
continue;
if (ce_path_match(ce, &revs->prune_data, NULL)) {
prune_num++;
REALLOC_ARRAY(prune, prune_num);
prune[prune_num-2] = ce->name;
prune[prune_num-1] = NULL;
}
while ((i+1 < active_nr) &&
ce_same_name(ce, active_cache[i+1]))
i++;
}
free_pathspec(&revs->prune_data);
parse_pathspec(&revs->prune_data, PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH, "", prune);
revs->limited = 1;
}
int handle_revision_arg(const char *arg_, struct rev_info *revs, int flags, unsigned revarg_opt)
{
struct object_context oc;
char *dotdot;
struct object *object;
unsigned char sha1[20];
int local_flags;
const char *arg = arg_;
int cant_be_filename = revarg_opt & REVARG_CANNOT_BE_FILENAME;
unsigned get_sha1_flags = 0;
flags = flags & UNINTERESTING ? flags | BOTTOM : flags & ~BOTTOM;
dotdot = strstr(arg, "..");
if (dotdot) {
unsigned char from_sha1[20];
const char *next = dotdot + 2;
const char *this = arg;
int symmetric = *next == '.';
unsigned int flags_exclude = flags ^ (UNINTERESTING | BOTTOM);
static const char head_by_default[] = "HEAD";
unsigned int a_flags;
*dotdot = 0;
next += symmetric;
if (!*next)
next = head_by_default;
if (dotdot == arg)
this = head_by_default;
if (this == head_by_default && next == head_by_default &&
!symmetric) {
/*
* Just ".."? That is not a range but the
* pathspec for the parent directory.
*/
if (!cant_be_filename) {
*dotdot = '.';
return -1;
}
}
if (!get_sha1_committish(this, from_sha1) &&
!get_sha1_committish(next, sha1)) {
struct object *a_obj, *b_obj;
if (!cant_be_filename) {
*dotdot = '.';
verify_non_filename(revs->prefix, arg);
}
a_obj = parse_object(from_sha1);
b_obj = parse_object(sha1);
if (!a_obj || !b_obj) {
missing:
if (revs->ignore_missing)
return 0;
die(symmetric
? "Invalid symmetric difference expression %s"
: "Invalid revision range %s", arg);
}
if (!symmetric) {
/* just A..B */
a_flags = flags_exclude;
} else {
/* A...B -- find merge bases between the two */
struct commit *a, *b;
struct commit_list *exclude;
a = (a_obj->type == OBJ_COMMIT
? (struct commit *)a_obj
: lookup_commit_reference(a_obj->oid.hash));
b = (b_obj->type == OBJ_COMMIT
? (struct commit *)b_obj
: lookup_commit_reference(b_obj->oid.hash));
if (!a || !b)
goto missing;
exclude = get_merge_bases(a, b);
add_rev_cmdline_list(revs, exclude,
REV_CMD_MERGE_BASE,
flags_exclude);
add_pending_commit_list(revs, exclude,
flags_exclude);
free_commit_list(exclude);
a_flags = flags | SYMMETRIC_LEFT;
}
a_obj->flags |= a_flags;
b_obj->flags |= flags;
add_rev_cmdline(revs, a_obj, this,
REV_CMD_LEFT, a_flags);
add_rev_cmdline(revs, b_obj, next,
REV_CMD_RIGHT, flags);
add_pending_object(revs, a_obj, this);
add_pending_object(revs, b_obj, next);
return 0;
}
*dotdot = '.';
}
dotdot = strstr(arg, "^@");
if (dotdot && !dotdot[2]) {
*dotdot = 0;
if (add_parents_only(revs, arg, flags))
return 0;
*dotdot = '^';
}
dotdot = strstr(arg, "^!");
if (dotdot && !dotdot[2]) {
*dotdot = 0;
if (!add_parents_only(revs, arg, flags ^ (UNINTERESTING | BOTTOM)))
*dotdot = '^';
}
local_flags = 0;
if (*arg == '^') {
local_flags = UNINTERESTING | BOTTOM;
arg++;
}
if (revarg_opt & REVARG_COMMITTISH)
get_sha1_flags = GET_SHA1_COMMITTISH;
if (get_sha1_with_context(arg, get_sha1_flags, sha1, &oc))
return revs->ignore_missing ? 0 : -1;
if (!cant_be_filename)
verify_non_filename(revs->prefix, arg);
object = get_reference(revs, arg, sha1, flags ^ local_flags);
add_rev_cmdline(revs, object, arg_, REV_CMD_REV, flags ^ local_flags);
add_pending_object_with_mode(revs, object, arg, oc.mode);
return 0;
}
struct cmdline_pathspec {
int alloc;
int nr;
const char **path;
};
static void append_prune_data(struct cmdline_pathspec *prune, const char **av)
{
while (*av) {
ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
prune->path[prune->nr++] = *(av++);
}
}
static void read_pathspec_from_stdin(struct rev_info *revs, struct strbuf *sb,
struct cmdline_pathspec *prune)
{
while (strbuf_getline(sb, stdin) != EOF) {
ALLOC_GROW(prune->path, prune->nr + 1, prune->alloc);
prune->path[prune->nr++] = xstrdup(sb->buf);
}
}
static void read_revisions_from_stdin(struct rev_info *revs,
struct cmdline_pathspec *prune)
{
struct strbuf sb;
int seen_dashdash = 0;
int save_warning;
save_warning = warn_on_object_refname_ambiguity;
warn_on_object_refname_ambiguity = 0;
strbuf_init(&sb, 1000);
while (strbuf_getline(&sb, stdin) != EOF) {
int len = sb.len;
if (!len)
break;
if (sb.buf[0] == '-') {
if (len == 2 && sb.buf[1] == '-') {
seen_dashdash = 1;
break;
}
die("options not supported in --stdin mode");
}
if (handle_revision_arg(sb.buf, revs, 0,
REVARG_CANNOT_BE_FILENAME))
die("bad revision '%s'", sb.buf);
}
if (seen_dashdash)
read_pathspec_from_stdin(revs, &sb, prune);
strbuf_release(&sb);
warn_on_object_refname_ambiguity = save_warning;
}
static void add_grep(struct rev_info *revs, const char *ptn, enum grep_pat_token what)
{
append_grep_pattern(&revs->grep_filter, ptn, "command line", 0, what);
}
static void add_header_grep(struct rev_info *revs, enum grep_header_field field, const char *pattern)
{
append_header_grep_pattern(&revs->grep_filter, field, pattern);
}
static void add_message_grep(struct rev_info *revs, const char *pattern)
{
add_grep(revs, pattern, GREP_PATTERN_BODY);
}
static int handle_revision_opt(struct rev_info *revs, int argc, const char **argv,
int *unkc, const char **unkv)
{
const char *arg = argv[0];
const char *optarg;
int argcount;
/* pseudo revision arguments */
if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
!strcmp(arg, "--tags") || !strcmp(arg, "--remotes") ||
!strcmp(arg, "--reflog") || !strcmp(arg, "--not") ||
!strcmp(arg, "--no-walk") || !strcmp(arg, "--do-walk") ||
!strcmp(arg, "--bisect") || starts_with(arg, "--glob=") ||
!strcmp(arg, "--indexed-objects") ||
starts_with(arg, "--exclude=") ||
starts_with(arg, "--branches=") || starts_with(arg, "--tags=") ||
starts_with(arg, "--remotes=") || starts_with(arg, "--no-walk="))
{
unkv[(*unkc)++] = arg;
return 1;
}
if ((argcount = parse_long_opt("max-count", argv, &optarg))) {
revs->max_count = atoi(optarg);
revs->no_walk = 0;
return argcount;
} else if ((argcount = parse_long_opt("skip", argv, &optarg))) {
revs->skip_count = atoi(optarg);
return argcount;
} else if ((*arg == '-') && isdigit(arg[1])) {
/* accept -<digit>, like traditional "head" */
if (strtol_i(arg + 1, 10, &revs->max_count) < 0 ||
revs->max_count < 0)
die("'%s': not a non-negative integer", arg + 1);
revs->no_walk = 0;
} else if (!strcmp(arg, "-n")) {
if (argc <= 1)
return error("-n requires an argument");
revs->max_count = atoi(argv[1]);
revs->no_walk = 0;
return 2;
} else if (starts_with(arg, "-n")) {
revs->max_count = atoi(arg + 2);
revs->no_walk = 0;
} else if ((argcount = parse_long_opt("max-age", argv, &optarg))) {
revs->max_age = atoi(optarg);
return argcount;
} else if ((argcount = parse_long_opt("since", argv, &optarg))) {
revs->max_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("after", argv, &optarg))) {
revs->max_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("min-age", argv, &optarg))) {
revs->min_age = atoi(optarg);
return argcount;
} else if ((argcount = parse_long_opt("before", argv, &optarg))) {
revs->min_age = approxidate(optarg);
return argcount;
} else if ((argcount = parse_long_opt("until", argv, &optarg))) {
revs->min_age = approxidate(optarg);
return argcount;
} else if (!strcmp(arg, "--first-parent")) {
revs->first_parent_only = 1;
} else if (!strcmp(arg, "--ancestry-path")) {
revs->ancestry_path = 1;
revs->simplify_history = 0;
revs->limited = 1;
} else if (!strcmp(arg, "-g") || !strcmp(arg, "--walk-reflogs")) {
init_reflog_walk(&revs->reflog_info);
} else if (!strcmp(arg, "--default")) {
if (argc <= 1)
return error("bad --default argument");
revs->def = argv[1];
return 2;
} else if (!strcmp(arg, "--merge")) {
revs->show_merge = 1;
} else if (!strcmp(arg, "--topo-order")) {
revs->sort_order = REV_SORT_IN_GRAPH_ORDER;
revs->topo_order = 1;
} else if (!strcmp(arg, "--simplify-merges")) {
revs->simplify_merges = 1;
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->simplify_history = 0;
revs->limited = 1;
} else if (!strcmp(arg, "--simplify-by-decoration")) {
revs->simplify_merges = 1;
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->simplify_history = 0;
revs->simplify_by_decoration = 1;
revs->limited = 1;
revs->prune = 1;
load_ref_decorations(DECORATE_SHORT_REFS);
} else if (!strcmp(arg, "--date-order")) {
revs->sort_order = REV_SORT_BY_COMMIT_DATE;
revs->topo_order = 1;
} else if (!strcmp(arg, "--author-date-order")) {
revs->sort_order = REV_SORT_BY_AUTHOR_DATE;
revs->topo_order = 1;
} else if (starts_with(arg, "--early-output")) {
int count = 100;
switch (arg[14]) {
case '=':
count = atoi(arg+15);
/* Fallthrough */
case 0:
revs->topo_order = 1;
revs->early_output = count;
}
} else if (!strcmp(arg, "--parents")) {
revs->rewrite_parents = 1;
revs->print_parents = 1;
} else if (!strcmp(arg, "--dense")) {
revs->dense = 1;
} else if (!strcmp(arg, "--sparse")) {
revs->dense = 0;
} else if (!strcmp(arg, "--show-all")) {
revs->show_all = 1;
} else if (!strcmp(arg, "--remove-empty")) {
revs->remove_empty_trees = 1;
} else if (!strcmp(arg, "--merges")) {
revs->min_parents = 2;
} else if (!strcmp(arg, "--no-merges")) {
revs->max_parents = 1;
} else if (starts_with(arg, "--min-parents=")) {
revs->min_parents = atoi(arg+14);
} else if (starts_with(arg, "--no-min-parents")) {
revs->min_parents = 0;
} else if (starts_with(arg, "--max-parents=")) {
revs->max_parents = atoi(arg+14);
} else if (starts_with(arg, "--no-max-parents")) {
revs->max_parents = -1;
} else if (!strcmp(arg, "--boundary")) {
revs->boundary = 1;
} else if (!strcmp(arg, "--left-right")) {
revs->left_right = 1;
} else if (!strcmp(arg, "--left-only")) {
if (revs->right_only)
die("--left-only is incompatible with --right-only"
" or --cherry");
revs->left_only = 1;
} else if (!strcmp(arg, "--right-only")) {
if (revs->left_only)
die("--right-only is incompatible with --left-only");
revs->right_only = 1;
} else if (!strcmp(arg, "--cherry")) {
if (revs->left_only)
die("--cherry is incompatible with --left-only");
revs->cherry_mark = 1;
revs->right_only = 1;
revs->max_parents = 1;
revs->limited = 1;
} else if (!strcmp(arg, "--count")) {
revs->count = 1;
} else if (!strcmp(arg, "--cherry-mark")) {
if (revs->cherry_pick)
die("--cherry-mark is incompatible with --cherry-pick");
revs->cherry_mark = 1;
revs->limited = 1; /* needs limit_list() */
} else if (!strcmp(arg, "--cherry-pick")) {
if (revs->cherry_mark)
die("--cherry-pick is incompatible with --cherry-mark");
revs->cherry_pick = 1;
revs->limited = 1;
} else if (!strcmp(arg, "--objects")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
} else if (!strcmp(arg, "--objects-edge")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->edge_hint = 1;
} else if (!strcmp(arg, "--objects-edge-aggressive")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->edge_hint = 1;
revs->edge_hint_aggressive = 1;
} else if (!strcmp(arg, "--verify-objects")) {
revs->tag_objects = 1;
revs->tree_objects = 1;
revs->blob_objects = 1;
revs->verify_objects = 1;
} else if (!strcmp(arg, "--unpacked")) {
revs->unpacked = 1;
} else if (starts_with(arg, "--unpacked=")) {
die("--unpacked=<packfile> no longer supported.");
} else if (!strcmp(arg, "-r")) {
revs->diff = 1;
DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
} else if (!strcmp(arg, "-t")) {
revs->diff = 1;
DIFF_OPT_SET(&revs->diffopt, RECURSIVE);
DIFF_OPT_SET(&revs->diffopt, TREE_IN_RECURSIVE);
} else if (!strcmp(arg, "-m")) {
revs->ignore_merges = 0;
} else if (!strcmp(arg, "-c")) {
revs->diff = 1;
revs->dense_combined_merges = 0;
revs->combine_merges = 1;
} else if (!strcmp(arg, "--cc")) {
revs->diff = 1;
revs->dense_combined_merges = 1;
revs->combine_merges = 1;
} else if (!strcmp(arg, "-v")) {
revs->verbose_header = 1;
} else if (!strcmp(arg, "--pretty")) {
revs->verbose_header = 1;
revs->pretty_given = 1;
get_commit_format(NULL, revs);
} else if (starts_with(arg, "--pretty=") || starts_with(arg, "--format=")) {
/*
* Detached form ("--pretty X" as opposed to "--pretty=X")
* not allowed, since the argument is optional.
*/
revs->verbose_header = 1;
revs->pretty_given = 1;
get_commit_format(arg+9, revs);
} else if (!strcmp(arg, "--show-notes") || !strcmp(arg, "--notes")) {
revs->show_notes = 1;
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = 1;
} else if (!strcmp(arg, "--show-signature")) {
revs->show_signature = 1;
} else if (!strcmp(arg, "--show-linear-break") ||
starts_with(arg, "--show-linear-break=")) {
if (starts_with(arg, "--show-linear-break="))
revs->break_bar = xstrdup(arg + 20);
else
revs->break_bar = " ..........";
revs->track_linear = 1;
revs->track_first_time = 1;
} else if (starts_with(arg, "--show-notes=") ||
starts_with(arg, "--notes=")) {
struct strbuf buf = STRBUF_INIT;
revs->show_notes = 1;
revs->show_notes_given = 1;
if (starts_with(arg, "--show-notes")) {
if (revs->notes_opt.use_default_notes < 0)
revs->notes_opt.use_default_notes = 1;
strbuf_addstr(&buf, arg+13);
}
else
strbuf_addstr(&buf, arg+8);
expand_notes_ref(&buf);
string_list_append(&revs->notes_opt.extra_notes_refs,
strbuf_detach(&buf, NULL));
} else if (!strcmp(arg, "--no-notes")) {
revs->show_notes = 0;
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = -1;
/* we have been strdup'ing ourselves, so trick
* string_list into free()ing strings */
revs->notes_opt.extra_notes_refs.strdup_strings = 1;
string_list_clear(&revs->notes_opt.extra_notes_refs, 0);
revs->notes_opt.extra_notes_refs.strdup_strings = 0;
} else if (!strcmp(arg, "--standard-notes")) {
revs->show_notes_given = 1;
revs->notes_opt.use_default_notes = 1;
} else if (!strcmp(arg, "--no-standard-notes")) {
revs->notes_opt.use_default_notes = 0;
} else if (!strcmp(arg, "--oneline")) {
revs->verbose_header = 1;
get_commit_format("oneline", revs);
revs->pretty_given = 1;
revs->abbrev_commit = 1;
} else if (!strcmp(arg, "--graph")) {
revs->topo_order = 1;
revs->rewrite_parents = 1;
revs->graph = graph_init(revs);
} else if (!strcmp(arg, "--root")) {
revs->show_root_diff = 1;
} else if (!strcmp(arg, "--no-commit-id")) {
revs->no_commit_id = 1;
} else if (!strcmp(arg, "--always")) {
revs->always_show_header = 1;
} else if (!strcmp(arg, "--no-abbrev")) {
revs->abbrev = 0;
} else if (!strcmp(arg, "--abbrev")) {
revs->abbrev = DEFAULT_ABBREV;
} else if (starts_with(arg, "--abbrev=")) {
revs->abbrev = strtoul(arg + 9, NULL, 10);
if (revs->abbrev < MINIMUM_ABBREV)
revs->abbrev = MINIMUM_ABBREV;
else if (revs->abbrev > 40)
revs->abbrev = 40;
} else if (!strcmp(arg, "--abbrev-commit")) {
revs->abbrev_commit = 1;
revs->abbrev_commit_given = 1;
} else if (!strcmp(arg, "--no-abbrev-commit")) {
revs->abbrev_commit = 0;
} else if (!strcmp(arg, "--full-diff")) {
revs->diff = 1;
revs->full_diff = 1;
} else if (!strcmp(arg, "--full-history")) {
revs->simplify_history = 0;
} else if (!strcmp(arg, "--relative-date")) {
revs->date_mode.type = DATE_RELATIVE;
revs->date_mode_explicit = 1;
} else if ((argcount = parse_long_opt("date", argv, &optarg))) {
parse_date_format(optarg, &revs->date_mode);
revs->date_mode_explicit = 1;
return argcount;
} else if (!strcmp(arg, "--log-size")) {
revs->show_log_size = 1;
}
/*
* Grepping the commit log
*/
else if ((argcount = parse_long_opt("author", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_AUTHOR, optarg);
return argcount;
} else if ((argcount = parse_long_opt("committer", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_COMMITTER, optarg);
return argcount;
} else if ((argcount = parse_long_opt("grep-reflog", argv, &optarg))) {
add_header_grep(revs, GREP_HEADER_REFLOG, optarg);
return argcount;
} else if ((argcount = parse_long_opt("grep", argv, &optarg))) {
add_message_grep(revs, optarg);
return argcount;
} else if (!strcmp(arg, "--grep-debug")) {
revs->grep_filter.debug = 1;
} else if (!strcmp(arg, "--basic-regexp")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_BRE, &revs->grep_filter);
} else if (!strcmp(arg, "--extended-regexp") || !strcmp(arg, "-E")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, &revs->grep_filter);
} else if (!strcmp(arg, "--regexp-ignore-case") || !strcmp(arg, "-i")) {
revs->grep_filter.regflags |= REG_ICASE;
DIFF_OPT_SET(&revs->diffopt, PICKAXE_IGNORE_CASE);
} else if (!strcmp(arg, "--fixed-strings") || !strcmp(arg, "-F")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_FIXED, &revs->grep_filter);
} else if (!strcmp(arg, "--perl-regexp")) {
grep_set_pattern_type_option(GREP_PATTERN_TYPE_PCRE, &revs->grep_filter);
} else if (!strcmp(arg, "--all-match")) {
revs->grep_filter.all_match = 1;
} else if (!strcmp(arg, "--invert-grep")) {
revs->invert_grep = 1;
} else if ((argcount = parse_long_opt("encoding", argv, &optarg))) {
if (strcmp(optarg, "none"))
git_log_output_encoding = xstrdup(optarg);
else
git_log_output_encoding = "";
return argcount;
} else if (!strcmp(arg, "--reverse")) {
revs->reverse ^= 1;
} else if (!strcmp(arg, "--children")) {
revs->children.name = "children";
revs->limited = 1;
} else if (!strcmp(arg, "--ignore-missing")) {
revs->ignore_missing = 1;
} else {
int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
if (!opts)
unkv[(*unkc)++] = arg;
return opts;
}
if (revs->graph && revs->track_linear)
die("--show-linear-break and --graph are incompatible");
return 1;
}
void parse_revision_opt(struct rev_info *revs, struct parse_opt_ctx_t *ctx,
const struct option *options,
const char * const usagestr[])
{
int n = handle_revision_opt(revs, ctx->argc, ctx->argv,
&ctx->cpidx, ctx->out);
if (n <= 0) {
error("unknown option `%s'", ctx->argv[0]);
usage_with_options(usagestr, options);
}
ctx->argv += n;
ctx->argc -= n;
}
static int for_each_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data, const char *term) {
struct strbuf bisect_refs = STRBUF_INIT;
int status;
strbuf_addf(&bisect_refs, "refs/bisect/%s", term);
status = for_each_ref_in_submodule(submodule, bisect_refs.buf, fn, cb_data);
strbuf_release(&bisect_refs);
return status;
}
static int for_each_bad_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
{
return for_each_bisect_ref(submodule, fn, cb_data, term_bad);
}
static int for_each_good_bisect_ref(const char *submodule, each_ref_fn fn, void *cb_data)
{
return for_each_bisect_ref(submodule, fn, cb_data, term_good);
}
static int handle_revision_pseudo_opt(const char *submodule,
struct rev_info *revs,
int argc, const char **argv, int *flags)
{
const char *arg = argv[0];
const char *optarg;
int argcount;
/*
* NOTE!
*
* Commands like "git shortlog" will not accept the options below
* unless parse_revision_opt queues them (as opposed to erroring
* out).
*
* When implementing your new pseudo-option, remember to
* register it in the list at the top of handle_revision_opt.
*/
if (!strcmp(arg, "--all")) {
handle_refs(submodule, revs, *flags, for_each_ref_submodule);
handle_refs(submodule, revs, *flags, head_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--branches")) {
handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--bisect")) {
read_bisect_terms(&term_bad, &term_good);
handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref);
handle_refs(submodule, revs, *flags ^ (UNINTERESTING | BOTTOM), for_each_good_bisect_ref);
revs->bisect = 1;
} else if (!strcmp(arg, "--tags")) {
handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--remotes")) {
handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule);
clear_ref_exclusion(&revs->ref_excludes);
} else if ((argcount = parse_long_opt("glob", argv, &optarg))) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref(handle_one_ref, optarg, &cb);
clear_ref_exclusion(&revs->ref_excludes);
return argcount;
} else if ((argcount = parse_long_opt("exclude", argv, &optarg))) {
add_ref_exclusion(&revs->ref_excludes, optarg);
return argcount;
} else if (starts_with(arg, "--branches=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 11, "refs/heads/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (starts_with(arg, "--tags=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 7, "refs/tags/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (starts_with(arg, "--remotes=")) {
struct all_refs_cb cb;
init_all_refs_cb(&cb, revs, *flags);
for_each_glob_ref_in(handle_one_ref, arg + 10, "refs/remotes/", &cb);
clear_ref_exclusion(&revs->ref_excludes);
} else if (!strcmp(arg, "--reflog")) {
add_reflogs_to_pending(revs, *flags);
} else if (!strcmp(arg, "--indexed-objects")) {
add_index_objects_to_pending(revs, *flags);
} else if (!strcmp(arg, "--not")) {
*flags ^= UNINTERESTING | BOTTOM;
} else if (!strcmp(arg, "--no-walk")) {
revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
} else if (starts_with(arg, "--no-walk=")) {
/*
* Detached form ("--no-walk X" as opposed to "--no-walk=X")
* not allowed, since the argument is optional.
*/
if (!strcmp(arg + 10, "sorted"))
revs->no_walk = REVISION_WALK_NO_WALK_SORTED;
else if (!strcmp(arg + 10, "unsorted"))
revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED;
else
return error("invalid argument to --no-walk");
} else if (!strcmp(arg, "--do-walk")) {
revs->no_walk = 0;
} else {
return 0;
}
return 1;
}
static void NORETURN diagnose_missing_default(const char *def)
{
unsigned char sha1[20];
int flags;
const char *refname;
refname = resolve_ref_unsafe(def, 0, sha1, &flags);
if (!refname || !(flags & REF_ISSYMREF) || (flags & REF_ISBROKEN))
die(_("your current branch appears to be broken"));
skip_prefix(refname, "refs/heads/", &refname);
die(_("your current branch '%s' does not have any commits yet"),
refname);
}
/*
* Parse revision information, filling in the "rev_info" structure,
* and removing the used arguments from the argument list.
*
* Returns the number of arguments left that weren't recognized
* (which are also moved to the head of the argument list)
*/
int setup_revisions(int argc, const char **argv, struct rev_info *revs, struct setup_revision_opt *opt)
{
int i, flags, left, seen_dashdash, read_from_stdin, got_rev_arg = 0, revarg_opt;
struct cmdline_pathspec prune_data;
const char *submodule = NULL;
memset(&prune_data, 0, sizeof(prune_data));
if (opt)
submodule = opt->submodule;
/* First, search for "--" */
if (opt && opt->assume_dashdash) {
seen_dashdash = 1;
} else {
seen_dashdash = 0;
for (i = 1; i < argc; i++) {
const char *arg = argv[i];
if (strcmp(arg, "--"))
continue;
argv[i] = NULL;
argc = i;
if (argv[i + 1])
append_prune_data(&prune_data, argv + i + 1);
seen_dashdash = 1;
break;
}
}
/* Second, deal with arguments and options */
flags = 0;
revarg_opt = opt ? opt->revarg_opt : 0;
if (seen_dashdash)
revarg_opt |= REVARG_CANNOT_BE_FILENAME;
read_from_stdin = 0;
for (left = i = 1; i < argc; i++) {
const char *arg = argv[i];
if (*arg == '-') {
int opts;
opts = handle_revision_pseudo_opt(submodule,
revs, argc - i, argv + i,
&flags);
if (opts > 0) {
i += opts - 1;
continue;
}
if (!strcmp(arg, "--stdin")) {
if (revs->disable_stdin) {
argv[left++] = arg;
continue;
}
if (read_from_stdin++)
die("--stdin given twice?");
read_revisions_from_stdin(revs, &prune_data);
continue;
}
opts = handle_revision_opt(revs, argc - i, argv + i, &left, argv);
if (opts > 0) {
i += opts - 1;
continue;
}
if (opts < 0)
exit(128);
continue;
}
if (handle_revision_arg(arg, revs, flags, revarg_opt)) {
int j;
if (seen_dashdash || *arg == '^')
die("bad revision '%s'", arg);
/* If we didn't have a "--":
* (1) all filenames must exist;
* (2) all rev-args must not be interpretable
* as a valid filename.
* but the latter we have checked in the main loop.
*/
for (j = i; j < argc; j++)
verify_filename(revs->prefix, argv[j], j == i);
append_prune_data(&prune_data, argv + i);
break;
}
else
got_rev_arg = 1;
}
if (prune_data.nr) {
/*
* If we need to introduce the magic "a lone ':' means no
* pathspec whatsoever", here is the place to do so.
*
* if (prune_data.nr == 1 && !strcmp(prune_data[0], ":")) {
* prune_data.nr = 0;
* prune_data.alloc = 0;
* free(prune_data.path);
* prune_data.path = NULL;
* } else {
* terminate prune_data.alloc with NULL and
* call init_pathspec() to set revs->prune_data here.
* }
*/
ALLOC_GROW(prune_data.path, prune_data.nr + 1, prune_data.alloc);
prune_data.path[prune_data.nr++] = NULL;
parse_pathspec(&revs->prune_data, 0, 0,
revs->prefix, prune_data.path);
}
if (revs->def == NULL)
revs->def = opt ? opt->def : NULL;
if (opt && opt->tweak)
opt->tweak(revs, opt);
if (revs->show_merge)
prepare_show_merge(revs);
if (revs->def && !revs->pending.nr && !got_rev_arg) {
unsigned char sha1[20];
struct object *object;
struct object_context oc;
if (get_sha1_with_context(revs->def, 0, sha1, &oc))
diagnose_missing_default(revs->def);
object = get_reference(revs, revs->def, sha1, 0);
add_pending_object_with_mode(revs, object, revs->def, oc.mode);
}
/* Did the user ask for any diff output? Run the diff! */
if (revs->diffopt.output_format & ~DIFF_FORMAT_NO_OUTPUT)
revs->diff = 1;
/* Pickaxe, diff-filter and rename following need diffs */
if (revs->diffopt.pickaxe ||
revs->diffopt.filter ||
DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
revs->diff = 1;
if (revs->topo_order)
revs->limited = 1;
if (revs->prune_data.nr) {
copy_pathspec(&revs->pruning.pathspec, &revs->prune_data);
/* Can't prune commits with rename following: the paths change.. */
if (!DIFF_OPT_TST(&revs->diffopt, FOLLOW_RENAMES))
revs->prune = 1;
if (!revs->full_diff)
copy_pathspec(&revs->diffopt.pathspec,
&revs->prune_data);
}
if (revs->combine_merges)
revs->ignore_merges = 0;
revs->diffopt.abbrev = revs->abbrev;
if (revs->line_level_traverse) {
revs->limited = 1;
revs->topo_order = 1;
}
diff_setup_done(&revs->diffopt);
grep_commit_pattern_type(GREP_PATTERN_TYPE_UNSPECIFIED,
&revs->grep_filter);
compile_grep_patterns(&revs->grep_filter);
if (revs->reverse && revs->reflog_info)
die("cannot combine --reverse with --walk-reflogs");
if (revs->rewrite_parents && revs->children.name)
die("cannot combine --parents and --children");
/*
* Limitations on the graph functionality
*/
if (revs->reverse && revs->graph)
die("cannot combine --reverse with --graph");
if (revs->reflog_info && revs->graph)
die("cannot combine --walk-reflogs with --graph");
if (revs->no_walk && revs->graph)
die("cannot combine --no-walk with --graph");
if (!revs->reflog_info && revs->grep_filter.use_reflog_filter)
die("cannot use --grep-reflog without --walk-reflogs");
if (revs->first_parent_only && revs->bisect)
die(_("--first-parent is incompatible with --bisect"));
return left;
}
static void add_child(struct rev_info *revs, struct commit *parent, struct commit *child)
{
struct commit_list *l = xcalloc(1, sizeof(*l));
l->item = child;
l->next = add_decoration(&revs->children, &parent->object, l);
}
static int remove_duplicate_parents(struct rev_info *revs, struct commit *commit)
{
struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
struct commit_list **pp, *p;
int surviving_parents;
/* Examine existing parents while marking ones we have seen... */
pp = &commit->parents;
surviving_parents = 0;
while ((p = *pp) != NULL) {
struct commit *parent = p->item;
if (parent->object.flags & TMP_MARK) {
*pp = p->next;
if (ts)
compact_treesame(revs, commit, surviving_parents);
continue;
}
parent->object.flags |= TMP_MARK;
surviving_parents++;
pp = &p->next;
}
/* clear the temporary mark */
for (p = commit->parents; p; p = p->next) {
p->item->object.flags &= ~TMP_MARK;
}
/* no update_treesame() - removing duplicates can't affect TREESAME */
return surviving_parents;
}
struct merge_simplify_state {
struct commit *simplified;
};
static struct merge_simplify_state *locate_simplify_state(struct rev_info *revs, struct commit *commit)
{
struct merge_simplify_state *st;
st = lookup_decoration(&revs->merge_simplification, &commit->object);
if (!st) {
st = xcalloc(1, sizeof(*st));
add_decoration(&revs->merge_simplification, &commit->object, st);
}
return st;
}
static int mark_redundant_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list *h = reduce_heads(commit->parents);
int i = 0, marked = 0;
struct commit_list *po, *pn;
/* Want these for sanity-checking only */
int orig_cnt = commit_list_count(commit->parents);
int cnt = commit_list_count(h);
/*
* Not ready to remove items yet, just mark them for now, based
* on the output of reduce_heads(). reduce_heads outputs the reduced
* set in its original order, so this isn't too hard.
*/
po = commit->parents;
pn = h;
while (po) {
if (pn && po->item == pn->item) {
pn = pn->next;
i++;
} else {
po->item->object.flags |= TMP_MARK;
marked++;
}
po=po->next;
}
if (i != cnt || cnt+marked != orig_cnt)
die("mark_redundant_parents %d %d %d %d", orig_cnt, cnt, i, marked);
free_commit_list(h);
return marked;
}
static int mark_treesame_root_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list *p;
int marked = 0;
for (p = commit->parents; p; p = p->next) {
struct commit *parent = p->item;
if (!parent->parents && (parent->object.flags & TREESAME)) {
parent->object.flags |= TMP_MARK;
marked++;
}
}
return marked;
}
/*
* Awkward naming - this means one parent we are TREESAME to.
* cf mark_treesame_root_parents: root parents that are TREESAME (to an
* empty tree). Better name suggestions?
*/
static int leave_one_treesame_to_parent(struct rev_info *revs, struct commit *commit)
{
struct treesame_state *ts = lookup_decoration(&revs->treesame, &commit->object);
struct commit *unmarked = NULL, *marked = NULL;
struct commit_list *p;
unsigned n;
for (p = commit->parents, n = 0; p; p = p->next, n++) {
if (ts->treesame[n]) {
if (p->item->object.flags & TMP_MARK) {
if (!marked)
marked = p->item;
} else {
if (!unmarked) {
unmarked = p->item;
break;
}
}
}
}
/*
* If we are TREESAME to a marked-for-deletion parent, but not to any
* unmarked parents, unmark the first TREESAME parent. This is the
* parent that the default simplify_history==1 scan would have followed,
* and it doesn't make sense to omit that path when asking for a
* simplified full history. Retaining it improves the chances of
* understanding odd missed merges that took an old version of a file.
*
* Example:
*
* I--------*X A modified the file, but mainline merge X used
* \ / "-s ours", so took the version from I. X is
* `-*A--' TREESAME to I and !TREESAME to A.
*
* Default log from X would produce "I". Without this check,
* --full-history --simplify-merges would produce "I-A-X", showing
* the merge commit X and that it changed A, but not making clear that
* it had just taken the I version. With this check, the topology above
* is retained.
*
* Note that it is possible that the simplification chooses a different
* TREESAME parent from the default, in which case this test doesn't
* activate, and we _do_ drop the default parent. Example:
*
* I------X A modified the file, but it was reverted in B,
* \ / meaning mainline merge X is TREESAME to both
* *A-*B parents.
*
* Default log would produce "I" by following the first parent;
* --full-history --simplify-merges will produce "I-A-B". But this is a
* reasonable result - it presents a logical full history leading from
* I to X, and X is not an important merge.
*/
if (!unmarked && marked) {
marked->object.flags &= ~TMP_MARK;
return 1;
}
return 0;
}
static int remove_marked_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp, *p;
int nth_parent, removed = 0;
pp = &commit->parents;
nth_parent = 0;
while ((p = *pp) != NULL) {
struct commit *parent = p->item;
if (parent->object.flags & TMP_MARK) {
parent->object.flags &= ~TMP_MARK;
*pp = p->next;
free(p);
removed++;
compact_treesame(revs, commit, nth_parent);
continue;
}
pp = &p->next;
nth_parent++;
}
/* Removing parents can only increase TREESAMEness */
if (removed && !(commit->object.flags & TREESAME))
update_treesame(revs, commit);
return nth_parent;
}
static struct commit_list **simplify_one(struct rev_info *revs, struct commit *commit, struct commit_list **tail)
{
struct commit_list *p;
struct commit *parent;
struct merge_simplify_state *st, *pst;
int cnt;
st = locate_simplify_state(revs, commit);
/*
* Have we handled this one?
*/
if (st->simplified)
return tail;
/*
* An UNINTERESTING commit simplifies to itself, so does a
* root commit. We do not rewrite parents of such commit
* anyway.
*/
if ((commit->object.flags & UNINTERESTING) || !commit->parents) {
st->simplified = commit;
return tail;
}
/*
* Do we know what commit all of our parents that matter
* should be rewritten to? Otherwise we are not ready to
* rewrite this one yet.
*/
for (cnt = 0, p = commit->parents; p; p = p->next) {
pst = locate_simplify_state(revs, p->item);
if (!pst->simplified) {
tail = &commit_list_insert(p->item, tail)->next;
cnt++;
}
if (revs->first_parent_only)
break;
}
if (cnt) {
tail = &commit_list_insert(commit, tail)->next;
return tail;
}
/*
* Rewrite our list of parents. Note that this cannot
* affect our TREESAME flags in any way - a commit is
* always TREESAME to its simplification.
*/
for (p = commit->parents; p; p = p->next) {
pst = locate_simplify_state(revs, p->item);
p->item = pst->simplified;
if (revs->first_parent_only)
break;
}
if (revs->first_parent_only)
cnt = 1;
else
cnt = remove_duplicate_parents(revs, commit);
/*
* It is possible that we are a merge and one side branch
* does not have any commit that touches the given paths;
* in such a case, the immediate parent from that branch
* will be rewritten to be the merge base.
*
* o----X X: the commit we are looking at;
* / / o: a commit that touches the paths;
* ---o----'
*
* Further, a merge of an independent branch that doesn't
* touch the path will reduce to a treesame root parent:
*
* ----o----X X: the commit we are looking at;
* / o: a commit that touches the paths;
* r r: a root commit not touching the paths
*
* Detect and simplify both cases.
*/
if (1 < cnt) {
int marked = mark_redundant_parents(revs, commit);
marked += mark_treesame_root_parents(revs, commit);
if (marked)
marked -= leave_one_treesame_to_parent(revs, commit);
if (marked)
cnt = remove_marked_parents(revs, commit);
}
/*
* A commit simplifies to itself if it is a root, if it is
* UNINTERESTING, if it touches the given paths, or if it is a
* merge and its parents don't simplify to one relevant commit
* (the first two cases are already handled at the beginning of
* this function).
*
* Otherwise, it simplifies to what its sole relevant parent
* simplifies to.
*/
if (!cnt ||
(commit->object.flags & UNINTERESTING) ||
!(commit->object.flags & TREESAME) ||
(parent = one_relevant_parent(revs, commit->parents)) == NULL)
st->simplified = commit;
else {
pst = locate_simplify_state(revs, parent);
st->simplified = pst->simplified;
}
return tail;
}
static void simplify_merges(struct rev_info *revs)
{
struct commit_list *list, *next;
struct commit_list *yet_to_do, **tail;
struct commit *commit;
if (!revs->prune)
return;
/* feed the list reversed */
yet_to_do = NULL;
for (list = revs->commits; list; list = next) {
commit = list->item;
next = list->next;
/*
* Do not free(list) here yet; the original list
* is used later in this function.
*/
commit_list_insert(commit, &yet_to_do);
}
while (yet_to_do) {
list = yet_to_do;
yet_to_do = NULL;
tail = &yet_to_do;
while (list) {
commit = pop_commit(&list);
tail = simplify_one(revs, commit, tail);
}
}
/* clean up the result, removing the simplified ones */
list = revs->commits;
revs->commits = NULL;
tail = &revs->commits;
while (list) {
struct merge_simplify_state *st;
commit = pop_commit(&list);
st = locate_simplify_state(revs, commit);
if (st->simplified == commit)
tail = &commit_list_insert(commit, tail)->next;
}
}
static void set_children(struct rev_info *revs)
{
struct commit_list *l;
for (l = revs->commits; l; l = l->next) {
struct commit *commit = l->item;
struct commit_list *p;
for (p = commit->parents; p; p = p->next)
add_child(revs, p->item, commit);
}
}
void reset_revision_walk(void)
{
clear_object_flags(SEEN | ADDED | SHOWN);
}
int prepare_revision_walk(struct rev_info *revs)
{
int i;
struct object_array old_pending;
struct commit_list **next = &revs->commits;
memcpy(&old_pending, &revs->pending, sizeof(old_pending));
revs->pending.nr = 0;
revs->pending.alloc = 0;
revs->pending.objects = NULL;
for (i = 0; i < old_pending.nr; i++) {
struct object_array_entry *e = old_pending.objects + i;
struct commit *commit = handle_commit(revs, e);
if (commit) {
if (!(commit->object.flags & SEEN)) {
commit->object.flags |= SEEN;
next = commit_list_append(commit, next);
}
}
}
if (!revs->leak_pending)
object_array_clear(&old_pending);
/* Signal whether we need per-parent treesame decoration */
if (revs->simplify_merges ||
(revs->limited && limiting_can_increase_treesame(revs)))
revs->treesame.name = "treesame";
if (revs->no_walk != REVISION_WALK_NO_WALK_UNSORTED)
commit_list_sort_by_date(&revs->commits);
if (revs->no_walk)
return 0;
if (revs->limited)
if (limit_list(revs) < 0)
return -1;
if (revs->topo_order)
sort_in_topological_order(&revs->commits, revs->sort_order);
if (revs->line_level_traverse)
line_log_filter(revs);
if (revs->simplify_merges)
simplify_merges(revs);
if (revs->children.name)
set_children(revs);
return 0;
}
static enum rewrite_result rewrite_one(struct rev_info *revs, struct commit **pp)
{
struct commit_list *cache = NULL;
for (;;) {
struct commit *p = *pp;
if (!revs->limited)
if (add_parents_to_list(revs, p, &revs->commits, &cache) < 0)
return rewrite_one_error;
if (p->object.flags & UNINTERESTING)
return rewrite_one_ok;
if (!(p->object.flags & TREESAME))
return rewrite_one_ok;
if (!p->parents)
return rewrite_one_noparents;
if ((p = one_relevant_parent(revs, p->parents)) == NULL)
return rewrite_one_ok;
*pp = p;
}
}
int rewrite_parents(struct rev_info *revs, struct commit *commit,
rewrite_parent_fn_t rewrite_parent)
{
struct commit_list **pp = &commit->parents;
while (*pp) {
struct commit_list *parent = *pp;
switch (rewrite_parent(revs, &parent->item)) {
case rewrite_one_ok:
break;
case rewrite_one_noparents:
*pp = parent->next;
continue;
case rewrite_one_error:
return -1;
}
pp = &parent->next;
}
remove_duplicate_parents(revs, commit);
return 0;
}
static int commit_rewrite_person(struct strbuf *buf, const char *what, struct string_list *mailmap)
{
char *person, *endp;
size_t len, namelen, maillen;
const char *name;
const char *mail;
struct ident_split ident;
person = strstr(buf->buf, what);
if (!person)
return 0;
person += strlen(what);
endp = strchr(person, '\n');
if (!endp)
return 0;
len = endp - person;
if (split_ident_line(&ident, person, len))
return 0;
mail = ident.mail_begin;
maillen = ident.mail_end - ident.mail_begin;
name = ident.name_begin;
namelen = ident.name_end - ident.name_begin;
if (map_user(mailmap, &mail, &maillen, &name, &namelen)) {
struct strbuf namemail = STRBUF_INIT;
strbuf_addf(&namemail, "%.*s <%.*s>",
(int)namelen, name, (int)maillen, mail);
strbuf_splice(buf, ident.name_begin - buf->buf,
ident.mail_end - ident.name_begin + 1,
namemail.buf, namemail.len);
strbuf_release(&namemail);
return 1;
}
return 0;
}
static int commit_match(struct commit *commit, struct rev_info *opt)
{
int retval;
const char *encoding;
const char *message;
struct strbuf buf = STRBUF_INIT;
if (!opt->grep_filter.pattern_list && !opt->grep_filter.header_list)
return 1;
/* Prepend "fake" headers as needed */
if (opt->grep_filter.use_reflog_filter) {
strbuf_addstr(&buf, "reflog ");
get_reflog_message(&buf, opt->reflog_info);
strbuf_addch(&buf, '\n');
}
/*
* We grep in the user's output encoding, under the assumption that it
* is the encoding they are most likely to write their grep pattern
* for. In addition, it means we will match the "notes" encoding below,
* so we will not end up with a buffer that has two different encodings
* in it.
*/
encoding = get_log_output_encoding();
message = logmsg_reencode(commit, NULL, encoding);
/* Copy the commit to temporary if we are using "fake" headers */
if (buf.len)
strbuf_addstr(&buf, message);
if (opt->grep_filter.header_list && opt->mailmap) {
if (!buf.len)
strbuf_addstr(&buf, message);
commit_rewrite_person(&buf, "\nauthor ", opt->mailmap);
commit_rewrite_person(&buf, "\ncommitter ", opt->mailmap);
}
/* Append "fake" message parts as needed */
if (opt->show_notes) {
if (!buf.len)
strbuf_addstr(&buf, message);
format_display_notes(commit->object.oid.hash, &buf, encoding, 1);
}
/*
* Find either in the original commit message, or in the temporary.
* Note that we cast away the constness of "message" here. It is
* const because it may come from the cached commit buffer. That's OK,
* because we know that it is modifiable heap memory, and that while
* grep_buffer may modify it for speed, it will restore any
* changes before returning.
*/
if (buf.len)
retval = grep_buffer(&opt->grep_filter, buf.buf, buf.len);
else
retval = grep_buffer(&opt->grep_filter,
(char *)message, strlen(message));
strbuf_release(&buf);
unuse_commit_buffer(commit, message);
return opt->invert_grep ? !retval : retval;
}
static inline int want_ancestry(const struct rev_info *revs)
{
return (revs->rewrite_parents || revs->children.name);
}
enum commit_action get_commit_action(struct rev_info *revs, struct commit *commit)
{
if (commit->object.flags & SHOWN)
return commit_ignore;
if (revs->unpacked && has_sha1_pack(commit->object.oid.hash))
return commit_ignore;
if (revs->show_all)
return commit_show;
if (commit->object.flags & UNINTERESTING)
return commit_ignore;
if (revs->min_age != -1 && (commit->date > revs->min_age))
return commit_ignore;
if (revs->min_parents || (revs->max_parents >= 0)) {
int n = commit_list_count(commit->parents);
if ((n < revs->min_parents) ||
((revs->max_parents >= 0) && (n > revs->max_parents)))
return commit_ignore;
}
if (!commit_match(commit, revs))
return commit_ignore;
if (revs->prune && revs->dense) {
/* Commit without changes? */
if (commit->object.flags & TREESAME) {
int n;
struct commit_list *p;
/* drop merges unless we want parenthood */
if (!want_ancestry(revs))
return commit_ignore;
/*
* If we want ancestry, then need to keep any merges
* between relevant commits to tie together topology.
* For consistency with TREESAME and simplification
* use "relevant" here rather than just INTERESTING,
* to treat bottom commit(s) as part of the topology.
*/
for (n = 0, p = commit->parents; p; p = p->next)
if (relevant_commit(p->item))
if (++n >= 2)
return commit_show;
return commit_ignore;
}
}
return commit_show;
}
define_commit_slab(saved_parents, struct commit_list *);
#define EMPTY_PARENT_LIST ((struct commit_list *)-1)
/*
* You may only call save_parents() once per commit (this is checked
* for non-root commits).
*/
static void save_parents(struct rev_info *revs, struct commit *commit)
{
struct commit_list **pp;
if (!revs->saved_parents_slab) {
revs->saved_parents_slab = xmalloc(sizeof(struct saved_parents));
init_saved_parents(revs->saved_parents_slab);
}
pp = saved_parents_at(revs->saved_parents_slab, commit);
/*
* When walking with reflogs, we may visit the same commit
* several times: once for each appearance in the reflog.
*
* In this case, save_parents() will be called multiple times.
* We want to keep only the first set of parents. We need to
* store a sentinel value for an empty (i.e., NULL) parent
* list to distinguish it from a not-yet-saved list, however.
*/
if (*pp)
return;
if (commit->parents)
*pp = copy_commit_list(commit->parents);
else
*pp = EMPTY_PARENT_LIST;
}
static void free_saved_parents(struct rev_info *revs)
{
if (revs->saved_parents_slab)
clear_saved_parents(revs->saved_parents_slab);
}
struct commit_list *get_saved_parents(struct rev_info *revs, const struct commit *commit)
{
struct commit_list *parents;
if (!revs->saved_parents_slab)
return commit->parents;
parents = *saved_parents_at(revs->saved_parents_slab, commit);
if (parents == EMPTY_PARENT_LIST)
return NULL;
return parents;
}
enum commit_action simplify_commit(struct rev_info *revs, struct commit *commit)
{
enum commit_action action = get_commit_action(revs, commit);
if (action == commit_show &&
!revs->show_all &&
revs->prune && revs->dense && want_ancestry(revs)) {
/*
* --full-diff on simplified parents is no good: it
* will show spurious changes from the commits that
* were elided. So we save the parents on the side
* when --full-diff is in effect.
*/
if (revs->full_diff)
save_parents(revs, commit);
if (rewrite_parents(revs, commit, rewrite_one) < 0)
return commit_error;
}
return action;
}
static void track_linear(struct rev_info *revs, struct commit *commit)
{
if (revs->track_first_time) {
revs->linear = 1;
revs->track_first_time = 0;
} else {
struct commit_list *p;
for (p = revs->previous_parents; p; p = p->next)
if (p->item == NULL || /* first commit */
!oidcmp(&p->item->object.oid, &commit->object.oid))
break;
revs->linear = p != NULL;
}
if (revs->reverse) {
if (revs->linear)
commit->object.flags |= TRACK_LINEAR;
}
free_commit_list(revs->previous_parents);
revs->previous_parents = copy_commit_list(commit->parents);
}
static struct commit *get_revision_1(struct rev_info *revs)
{
if (!revs->commits)
return NULL;
do {
struct commit *commit = pop_commit(&revs->commits);
if (revs->reflog_info) {
save_parents(revs, commit);
fake_reflog_parent(revs->reflog_info, commit);
commit->object.flags &= ~(ADDED | SEEN | SHOWN);
}
/*
* If we haven't done the list limiting, we need to look at
* the parents here. We also need to do the date-based limiting
* that we'd otherwise have done in limit_list().
*/
if (!revs->limited) {
if (revs->max_age != -1 &&
(commit->date < revs->max_age))
continue;
if (add_parents_to_list(revs, commit, &revs->commits, NULL) < 0) {
if (!revs->ignore_missing_links)
die("Failed to traverse parents of commit %s",
oid_to_hex(&commit->object.oid));
}
}
switch (simplify_commit(revs, commit)) {
case commit_ignore:
continue;
case commit_error:
die("Failed to simplify parents of commit %s",
oid_to_hex(&commit->object.oid));
default:
if (revs->track_linear)
track_linear(revs, commit);
return commit;
}
} while (revs->commits);
return NULL;
}
/*
* Return true for entries that have not yet been shown. (This is an
* object_array_each_func_t.)
*/
static int entry_unshown(struct object_array_entry *entry, void *cb_data_unused)
{
return !(entry->item->flags & SHOWN);
}
/*
* If array is on the verge of a realloc, garbage-collect any entries
* that have already been shown to try to free up some space.
*/
static void gc_boundary(struct object_array *array)
{
if (array->nr == array->alloc)
object_array_filter(array, entry_unshown, NULL);
}
static void create_boundary_commit_list(struct rev_info *revs)
{
unsigned i;
struct commit *c;
struct object_array *array = &revs->boundary_commits;
struct object_array_entry *objects = array->objects;
/*
* If revs->commits is non-NULL at this point, an error occurred in
* get_revision_1(). Ignore the error and continue printing the
* boundary commits anyway. (This is what the code has always
* done.)
*/
if (revs->commits) {
free_commit_list(revs->commits);
revs->commits = NULL;
}
/*
* Put all of the actual boundary commits from revs->boundary_commits
* into revs->commits
*/
for (i = 0; i < array->nr; i++) {
c = (struct commit *)(objects[i].item);
if (!c)
continue;
if (!(c->object.flags & CHILD_SHOWN))
continue;
if (c->object.flags & (SHOWN | BOUNDARY))
continue;
c->object.flags |= BOUNDARY;
commit_list_insert(c, &revs->commits);
}
/*
* If revs->topo_order is set, sort the boundary commits
* in topological order
*/
sort_in_topological_order(&revs->commits, revs->sort_order);
}
static struct commit *get_revision_internal(struct rev_info *revs)
{
struct commit *c = NULL;
struct commit_list *l;
if (revs->boundary == 2) {
/*
* All of the normal commits have already been returned,
* and we are now returning boundary commits.
* create_boundary_commit_list() has populated
* revs->commits with the remaining commits to return.
*/
c = pop_commit(&revs->commits);
if (c)
c->object.flags |= SHOWN;
return c;
}
/*
* If our max_count counter has reached zero, then we are done. We
* don't simply return NULL because we still might need to show
* boundary commits. But we want to avoid calling get_revision_1, which
* might do a considerable amount of work finding the next commit only
* for us to throw it away.
*
* If it is non-zero, then either we don't have a max_count at all
* (-1), or it is still counting, in which case we decrement.
*/
if (revs->max_count) {
c = get_revision_1(revs);
if (c) {
while (revs->skip_count > 0) {
revs->skip_count--;
c = get_revision_1(revs);
if (!c)
break;
}
}
if (revs->max_count > 0)
revs->max_count--;
}
if (c)
c->object.flags |= SHOWN;
if (!revs->boundary)
return c;
if (!c) {
/*
* get_revision_1() runs out the commits, and
* we are done computing the boundaries.
* switch to boundary commits output mode.
*/
revs->boundary = 2;
/*
* Update revs->commits to contain the list of
* boundary commits.
*/
create_boundary_commit_list(revs);
return get_revision_internal(revs);
}
/*
* boundary commits are the commits that are parents of the
* ones we got from get_revision_1() but they themselves are
* not returned from get_revision_1(). Before returning
* 'c', we need to mark its parents that they could be boundaries.
*/
for (l = c->parents; l; l = l->next) {
struct object *p;
p = &(l->item->object);
if (p->flags & (CHILD_SHOWN | SHOWN))
continue;
p->flags |= CHILD_SHOWN;
gc_boundary(&revs->boundary_commits);
add_object_array(p, NULL, &revs->boundary_commits);
}
return c;
}
struct commit *get_revision(struct rev_info *revs)
{
struct commit *c;
struct commit_list *reversed;
if (revs->reverse) {
reversed = NULL;
while ((c = get_revision_internal(revs)))
commit_list_insert(c, &reversed);
revs->commits = reversed;
revs->reverse = 0;
revs->reverse_output_stage = 1;
}
if (revs->reverse_output_stage) {
c = pop_commit(&revs->commits);
if (revs->track_linear)
revs->linear = !!(c && c->object.flags & TRACK_LINEAR);
return c;
}
c = get_revision_internal(revs);
if (c && revs->graph)
graph_update(revs->graph, c);
if (!c) {
free_saved_parents(revs);
if (revs->previous_parents) {
free_commit_list(revs->previous_parents);
revs->previous_parents = NULL;
}
}
return c;
}
char *get_revision_mark(const struct rev_info *revs, const struct commit *commit)
{
if (commit->object.flags & BOUNDARY)
return "-";
else if (commit->object.flags & UNINTERESTING)
return "^";
else if (commit->object.flags & PATCHSAME)
return "=";
else if (!revs || revs->left_right) {
if (commit->object.flags & SYMMETRIC_LEFT)
return "<";
else
return ">";
} else if (revs->graph)
return "*";
else if (revs->cherry_mark)
return "+";
return "";
}
void put_revision_mark(const struct rev_info *revs, const struct commit *commit)
{
char *mark = get_revision_mark(revs, commit);
if (!strlen(mark))
return;
fputs(mark, stdout);
putchar(' ');
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_4946_7 |
crossvul-cpp_data_bad_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;
}
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/bad_4787_12 |
crossvul-cpp_data_bad_552_3 | /*
* Boa, an http server
* Copyright (C) 1995 Paul Phillips <paulp@go2net.com>
* Copyright (C) 1996-1999 Larry Doolittle <ldoolitt@boa.org>
* Copyright (C) 1999-2004 Jon Nelson <jnelson@boa.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/* $Id: log.c,v 1.36.2.27 2005/02/22 14:11:29 jnelson Exp $*/
#include "boa.h"
int cgi_log_fd;
/*
* Name: open_logs
*
* Description: Opens access log, error log, and if specified, CGI log
* Ties stderr to error log, except during CGI execution, at which
* time CGI log is the stderr for CGIs.
*
* Access log is line buffered, error log is not buffered.
*
*/
void open_logs(void)
{
int access_log;
/* if error_log_name is set, dup2 stderr to it */
/* otherwise, leave stderr alone */
/* we don't want to tie stderr to /dev/null */
if (error_log_name) {
int error_log;
/* open the log file */
error_log = open_gen_fd(error_log_name);
if (error_log < 0) {
DIE("unable to open error log");
}
/* redirect stderr to error_log */
if (dup2(error_log, STDERR_FILENO) == -1) {
DIE("unable to dup2 the error log");
}
close(error_log);
}
if (access_log_name) {
access_log = open_gen_fd(access_log_name);
} else {
access_log = open("/dev/null", 0);
}
if (access_log < 0) {
DIE("unable to open access log");
}
if (dup2(access_log, STDOUT_FILENO) == -1) {
DIE("can't dup2 /dev/null to STDOUT_FILENO");
}
if (fcntl(access_log, F_SETFD, 1) == -1) {
DIE("unable to set close-on-exec flag for access_log");
}
close(access_log);
if (cgi_log_name) {
cgi_log_fd = open_gen_fd(cgi_log_name);
if (cgi_log_fd == -1) {
WARN("open cgi_log");
free(cgi_log_name);
cgi_log_name = NULL;
cgi_log_fd = 0;
} else {
if (fcntl(cgi_log_fd, F_SETFD, 1) == -1) {
WARN("unable to set close-on-exec flag for cgi_log");
free(cgi_log_name);
cgi_log_name = NULL;
close(cgi_log_fd);
cgi_log_fd = 0;
}
}
}
#ifdef SETVBUF_REVERSED
setvbuf(stderr, _IONBF, (char *) NULL, 0);
setvbuf(stdout, _IOLBF, (char *) NULL, 0);
#else
setvbuf(stderr, (char *) NULL, _IONBF, 0);
setvbuf(stdout, (char *) NULL, _IOLBF, 0);
#endif
}
/* Print the remote IP to the stream FP. */
static void
print_remote_ip (request * req, FILE *fp)
{
if (log_forwarded_for) {
const char *s = req->header_forwarded_for;
if (s && *s) {
for (; *s; s++) {
/* Take extra care not to write bogus characters. In
particular no spaces. We know that only IP addresses
and a comma are allowed in the XFF header. */
if (strchr ("0123456789.abcdef:ABCDEF,", *s))
putc (*s, fp);
else
putc ('_', fp);
}
}
else /* Missing - print remote IP in parenthesis. */
fprintf (fp, "(%s)", req->remote_ip_addr);
}
else
fputs (req->remote_ip_addr, fp);
}
/*
* Name: log_access
*
* Description: Writes log data to access_log.
*/
/* NOTES on the commonlog format:
* Taken from notes on the NetBuddy program
* http://www.computer-dynamics.com/commonlog.html
remotehost
remotehost rfc931 authuser [date] "request" status bytes
remotehost - IP of the client
rfc931 - remote name of the user (always '-')
authuser - username entered for authentication - almost always '-'
[date] - the date in [08/Nov/1997:01:05:03 -0600] (with brackets) format
"request" - literal request from the client (boa may clean this up,
replacing control-characters with '_' perhaps - NOTE: not done)
status - http status code
bytes - number of bytes transferred
boa appends:
referer
user-agent
and may prepend (depending on configuration):
virtualhost - the name or IP (depending on whether name-based
virtualhosting is enabled) of the host the client accessed
*/
void log_access(request * req)
{
if (!access_log_name)
return;
if (virtualhost) {
printf("%s ", req->local_ip_addr);
} else if (vhost_root) {
printf("%s ", (req->host ? req->host : "(null)"));
}
print_remote_ip (req, stdout);
printf(" - - %s\"%s\" %d %zu \"%s\" \"%s\"\n",
get_commonlog_time(),
req->logline ? req->logline : "-",
req->response_status,
req->bytes_written,
(req->header_referer ? req->header_referer : "-"),
(req->header_user_agent ? req->header_user_agent : "-"));
}
static char *escape_pathname(const char *inp)
{
const unsigned char *s;
char *escaped, *d;
if (!inp) {
return NULL;
}
escaped = malloc (4 * strlen(inp) + 1);
if (!escaped) {
perror("malloc");
return NULL;
}
for (d = escaped, s = (const unsigned char *)inp; *s; s++) {
if (needs_escape (*s)) {
snprintf (d, 5, "\\x%02x", *s);
d += strlen (d);
} else {
*d++ = *s;
}
}
*d++ = '\0';
return escaped;
}
/*
* Name: log_error_doc
*
* Description: Logs the current time and transaction identification
* to the stderr (the error log):
* should always be followed by an fprintf to stderr
*
* Example output:
[08/Nov/1997:01:05:03 -0600] request from 192.228.331.232 "GET /~joeblow/dir/ HTTP/1.0" ("/usr/user1/joeblow/public_html/dir/"): write: Broken pipe
Apache uses:
[Wed Oct 11 14:32:52 2000] [error] [client 127.0.0.1] client denied by server configuration: /export/home/live/ap/htdocs/test
*/
void log_error_doc(request * req)
{
int errno_save = errno;
char *escaped_pathname;
if (virtualhost) {
fprintf(stderr, "%s ", req->local_ip_addr);
} else if (vhost_root) {
fprintf(stderr, "%s ", (req->host ? req->host : "(null)"));
}
escaped_pathname = escape_pathname(req->pathname);
print_remote_ip (req, stderr);
if (vhost_root) {
fprintf(stderr, " - - %srequest [%s] \"%s\" (\"%s\"): ",
get_commonlog_time(),
(req->header_host ? req->header_host : "(null)"),
(req->logline ? req->logline : "(null)"),
(escaped_pathname ? escaped_pathname : "(null)"));
} else {
fprintf(stderr, " - - %srequest \"%s\" (\"%s\"): ",
get_commonlog_time(),
(req->logline ? req->logline : "(null)"),
(escaped_pathname ? escaped_pathname : "(null)"));
}
free(escaped_pathname);
errno = errno_save;
}
/*
* Name: boa_perror
*
* Description: logs an error to user and error file both
*
*/
void boa_perror(request * req, const char *message)
{
log_error_doc(req);
perror(message); /* don't need to save errno because log_error_doc does */
send_r_error(req);
}
/*
* Name: log_error_time
*
* Description: Logs the current time to the stderr (the error log):
* should always be followed by an fprintf to stderr
*/
void log_error_time(void)
{
int errno_save = errno;
fputs(get_commonlog_time(), stderr);
errno = errno_save;
}
/*
* Name: log_error
*
* Description: performs a log_error_time and writes a message to stderr
*
*/
void log_error(const char *mesg)
{
fprintf(stderr, "%s%s", get_commonlog_time(), mesg);
}
/*
* Name: log_error_mesg
*
* Description: performs a log_error_time, writes the file and lineno
* to stderr (saving errno), and then a perror with message
*
*/
#ifdef HAVE_FUNC
void log_error_mesg(const char *file, int line, const char *func, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d (%s) - ", get_commonlog_time(), file, line, func);
errno = errno_save;
perror(mesg);
errno = errno_save;
}
void log_error_mesg_fatal(const char *file, int line, const char *func, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d (%s) - ", get_commonlog_time(), file, line, func);
errno = errno_save;
perror(mesg);
exit(EXIT_FAILURE);
}
#else
void log_error_mesg(const char *file, int line, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d - ", get_commonlog_time(), file, line);
errno = errno_save;
perror(mesg);
errno = errno_save;
}
void log_error_mesg_fatal(const char *file, int line, const char *mesg)
{
int errno_save = errno;
fprintf(stderr, "%s%s:%d - ", get_commonlog_time(), file, line);
errno = errno_save;
perror(mesg);
exit(EXIT_FAILURE);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_552_3 |
crossvul-cpp_data_good_2210_0 | /*
* Copyright 2011-2013 Con Kolivas
* Copyright 2011-2013 Luke Dashjr
* Copyright 2010 Jeff Garzik
* Copyright 2012 Giel van Schijndel
* Copyright 2012 Gavin Andresen
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <pthread.h>
#include <jansson.h>
#include <curl/curl.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#ifdef HAVE_SYS_PRCTL_H
# include <sys/prctl.h>
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__)
# include <pthread_np.h>
#endif
#ifndef WIN32
# ifdef __linux
# include <sys/prctl.h>
# endif
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <netdb.h>
#else
# include <winsock2.h>
# include <mstcpip.h>
# include <ws2tcpip.h>
#endif
#include "miner.h"
#include "elist.h"
#include "compat.h"
#include "util.h"
bool successful_connect = false;
struct timeval nettime;
struct data_buffer {
void *buf;
size_t len;
curl_socket_t *idlemarker;
};
struct upload_buffer {
const void *buf;
size_t len;
};
struct header_info {
char *lp_path;
int rolltime;
char *reason;
char *stratum_url;
bool hadrolltime;
bool canroll;
bool hadexpire;
};
struct tq_ent {
void *data;
struct list_head q_node;
};
static void databuf_free(struct data_buffer *db)
{
if (!db)
return;
free(db->buf);
#ifdef DEBUG_DATABUF
applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
#endif
memset(db, 0, sizeof(*db));
}
// aka data_buffer_write
static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct data_buffer *db = user_data;
size_t oldlen, newlen;
oldlen = db->len;
if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
return 0;
if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
nmemb = (SIZE_MAX - oldlen) / size;
size_t len = size * nmemb;
void *newmem;
static const unsigned char zero = 0;
if (db->idlemarker) {
const unsigned char *cptr = ptr;
for (size_t i = 0; i < len; ++i)
if (!(isspace(cptr[i]) || cptr[i] == '{')) {
*db->idlemarker = CURL_SOCKET_BAD;
db->idlemarker = NULL;
break;
}
}
newlen = oldlen + len;
newmem = realloc(db->buf, newlen + 1);
#ifdef DEBUG_DATABUF
applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
#endif
if (!newmem)
return 0;
db->buf = newmem;
db->len = newlen;
memcpy(db->buf + oldlen, ptr, len);
memcpy(db->buf + newlen, &zero, 1); /* null terminate */
return nmemb;
}
static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
void *user_data)
{
struct upload_buffer *ub = user_data;
unsigned int len = size * nmemb;
if (len > ub->len)
len = ub->len;
if (len) {
memcpy(ptr, ub->buf, len);
ub->buf += len;
ub->len -= len;
}
return len;
}
static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
{
struct header_info *hi = user_data;
size_t remlen, slen, ptrlen = size * nmemb;
char *rem, *val = NULL, *key = NULL;
void *tmp;
val = calloc(1, ptrlen);
key = calloc(1, ptrlen);
if (!key || !val)
goto out;
tmp = memchr(ptr, ':', ptrlen);
if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
goto out;
slen = tmp - ptr;
if ((slen + 1) == ptrlen) /* skip key w/ no value */
goto out;
memcpy(key, ptr, slen); /* store & nul term key */
key[slen] = 0;
rem = ptr + slen + 1; /* trim value's leading whitespace */
remlen = ptrlen - slen - 1;
while ((remlen > 0) && (isspace(*rem))) {
remlen--;
rem++;
}
memcpy(val, rem, remlen); /* store value, trim trailing ws */
val[remlen] = 0;
while ((*val) && (isspace(val[strlen(val) - 1])))
val[strlen(val) - 1] = 0;
if (!*val) /* skip blank value */
goto out;
if (opt_protocol)
applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
if (!strcasecmp("X-Roll-Ntime", key)) {
hi->hadrolltime = true;
if (!strncasecmp("N", val, 1))
applog(LOG_DEBUG, "X-Roll-Ntime: N found");
else {
hi->canroll = true;
/* Check to see if expire= is supported and if not, set
* the rolltime to the default scantime */
if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
sscanf(val + 7, "%d", &hi->rolltime);
hi->hadexpire = true;
} else
hi->rolltime = opt_scantime;
applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
}
}
if (!strcasecmp("X-Long-Polling", key)) {
hi->lp_path = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Reject-Reason", key)) {
hi->reason = val; /* steal memory reference */
val = NULL;
}
if (!strcasecmp("X-Stratum", key)) {
hi->stratum_url = val;
val = NULL;
}
out:
free(key);
free(val);
return ptrlen;
}
static int keep_sockalive(SOCKETTYPE fd)
{
const int tcp_keepidle = 60;
const int tcp_keepintvl = 60;
const int keepalive = 1;
int ret = 0;
#ifndef WIN32
const int tcp_keepcnt = 5;
if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
ret = 1;
# ifdef __linux
if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
ret = 1;
if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
ret = 1;
if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
ret = 1;
# endif /* __linux */
# ifdef __APPLE_CC__
if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
ret = 1;
# endif /* __APPLE_CC__ */
#else /* WIN32 */
const int zero = 0;
struct tcp_keepalive vals;
vals.onoff = 1;
vals.keepalivetime = tcp_keepidle * 1000;
vals.keepaliveinterval = tcp_keepintvl * 1000;
DWORD outputBytes;
if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
ret = 1;
if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
ret = 1;
/* Windows happily submits indefinitely to the send buffer blissfully
* unaware nothing is getting there without gracefully failing unless
* we disable the send buffer */
if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
ret = 1;
#endif /* WIN32 */
return ret;
}
int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
curlsocktype __maybe_unused purpose)
{
return keep_sockalive(fd);
}
static void last_nettime(struct timeval *last)
{
rd_lock(&netacc_lock);
last->tv_sec = nettime.tv_sec;
last->tv_usec = nettime.tv_usec;
rd_unlock(&netacc_lock);
}
static void set_nettime(void)
{
wr_lock(&netacc_lock);
gettimeofday(&nettime, NULL);
wr_unlock(&netacc_lock);
}
static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
char *data, size_t size,
void *userdata)
{
struct pool *pool = (struct pool *)userdata;
switch(type) {
case CURLINFO_HEADER_IN:
case CURLINFO_DATA_IN:
case CURLINFO_SSL_DATA_IN:
pool->cgminer_pool_stats.bytes_received += size;
total_bytes_xfer += size;
pool->cgminer_pool_stats.net_bytes_received += size;
break;
case CURLINFO_HEADER_OUT:
case CURLINFO_DATA_OUT:
case CURLINFO_SSL_DATA_OUT:
pool->cgminer_pool_stats.bytes_sent += size;
total_bytes_xfer += size;
pool->cgminer_pool_stats.net_bytes_sent += size;
break;
case CURLINFO_TEXT:
{
if (!opt_protocol)
break;
// data is not null-terminated, so we need to copy and terminate it for applog
char datacp[size + 1];
memcpy(datacp, data, size);
while (isspace(datacp[size-1]))
--size;
datacp[size] = '\0';
applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
break;
}
default:
break;
}
return 0;
}
struct json_rpc_call_state {
struct data_buffer all_data;
struct header_info hi;
void *priv;
char curl_err_str[CURL_ERROR_SIZE];
struct curl_slist *headers;
struct upload_buffer upload_data;
struct pool *pool;
};
void json_rpc_call_async(CURL *curl, const char *url,
const char *userpass, const char *rpc_req,
bool longpoll,
struct pool *pool, bool share,
void *priv)
{
struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
*state = (struct json_rpc_call_state){
.priv = priv,
.pool = pool,
};
long timeout = longpoll ? (60 * 60) : 60;
char len_hdr[64], user_agent_hdr[128];
struct curl_slist *headers = NULL;
if (longpoll)
state->all_data.idlemarker = &pool->lp_socket;
/* it is assumed that 'curl' is freshly [re]initialized at this pt */
curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
/* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
* to enable it */
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_ENCODING, "");
curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
/* Shares are staggered already and delays in submission can be costly
* so do not delay them */
if (!opt_delaynet || share)
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
if (pool->rpc_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
} else if (opt_socks_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
if (userpass) {
curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if (longpoll)
curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
curl_easy_setopt(curl, CURLOPT_POST, 1);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
state->upload_data.buf = rpc_req;
state->upload_data.len = strlen(rpc_req);
sprintf(len_hdr, "Content-Length: %lu",
(unsigned long) state->upload_data.len);
sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
headers = curl_slist_append(headers,
"Content-type: application/json");
headers = curl_slist_append(headers,
"X-Mining-Extensions: longpoll midstate rollntime submitold");
if (longpoll)
headers = curl_slist_append(headers,
"X-Minimum-Wait: 0");
if (likely(global_hashrate)) {
char ghashrate[255];
sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
headers = curl_slist_append(headers, ghashrate);
}
headers = curl_slist_append(headers, len_hdr);
headers = curl_slist_append(headers, user_agent_hdr);
headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
state->headers = headers;
if (opt_delaynet) {
/* Don't delay share submission, but still track the nettime */
if (!share) {
long long now_msecs, last_msecs;
struct timeval now, last;
gettimeofday(&now, NULL);
last_nettime(&last);
now_msecs = (long long)now.tv_sec * 1000;
now_msecs += now.tv_usec / 1000;
last_msecs = (long long)last.tv_sec * 1000;
last_msecs += last.tv_usec / 1000;
if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
struct timespec rgtp;
rgtp.tv_sec = 0;
rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
nanosleep(&rgtp, NULL);
}
}
set_nettime();
}
}
json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
{
struct json_rpc_call_state *state;
if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
applog(LOG_ERR, "Failed to get private curl data");
if (out_priv)
*(void**)out_priv = NULL;
goto err_out;
}
if (out_priv)
*(void**)out_priv = state->priv;
json_t *val, *err_val, *res_val;
json_error_t err;
struct pool *pool = state->pool;
bool probing = probe && !pool->probed;
if (rc) {
applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
goto err_out;
}
if (!state->all_data.buf) {
applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
goto err_out;
}
pool->cgminer_pool_stats.times_sent++;
pool->cgminer_pool_stats.times_received++;
if (probing) {
pool->probed = true;
/* If X-Long-Polling was found, activate long polling */
if (state->hi.lp_path) {
if (pool->hdr_path != NULL)
free(pool->hdr_path);
pool->hdr_path = state->hi.lp_path;
} else
pool->hdr_path = NULL;
if (state->hi.stratum_url) {
pool->stratum_url = state->hi.stratum_url;
state->hi.stratum_url = NULL;
}
} else {
if (state->hi.lp_path) {
free(state->hi.lp_path);
state->hi.lp_path = NULL;
}
if (state->hi.stratum_url) {
free(state->hi.stratum_url);
state->hi.stratum_url = NULL;
}
}
if (pool->force_rollntime)
{
state->hi.canroll = true;
state->hi.hadexpire = true;
state->hi.rolltime = pool->force_rollntime;
}
if (rolltime)
*rolltime = state->hi.rolltime;
pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
pool->cgminer_pool_stats.canroll = state->hi.canroll;
pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
val = JSON_LOADS(state->all_data.buf, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
if (opt_protocol)
applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
goto err_out;
}
if (opt_protocol) {
char *s = json_dumps(val, JSON_INDENT(3));
applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
free(s);
}
/* JSON-RPC valid response returns a non-null 'result',
* and a null 'error'.
*/
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val ||(err_val && !json_is_null(err_val))) {
char *s;
if (err_val)
s = json_dumps(err_val, JSON_INDENT(3));
else
s = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC call failed: %s", s);
free(s);
json_decref(val);
goto err_out;
}
if (state->hi.reason) {
json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
free(state->hi.reason);
state->hi.reason = NULL;
}
successful_connect = true;
databuf_free(&state->all_data);
curl_slist_free_all(state->headers);
curl_easy_reset(curl);
free(state);
return val;
err_out:
databuf_free(&state->all_data);
curl_slist_free_all(state->headers);
curl_easy_reset(curl);
if (!successful_connect)
applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
free(state);
return NULL;
}
json_t *json_rpc_call(CURL *curl, const char *url,
const char *userpass, const char *rpc_req,
bool probe, bool longpoll, int *rolltime,
struct pool *pool, bool share)
{
json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
int rc = curl_easy_perform(curl);
return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
}
bool our_curl_supports_proxy_uris()
{
curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
}
// NOTE: This assumes reference URI is a root
char *absolute_uri(char *uri, const char *ref)
{
if (strstr(uri, "://"))
return strdup(uri);
char *copy_start, *abs;
bool need_slash = false;
copy_start = (uri[0] == '/') ? &uri[1] : uri;
if (ref[strlen(ref) - 1] != '/')
need_slash = true;
abs = malloc(strlen(ref) + strlen(copy_start) + 2);
if (!abs) {
applog(LOG_ERR, "Malloc failure in absolute_uri");
return NULL;
}
sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
return abs;
}
/* Returns a malloced array string of a binary value of arbitrary length. The
* array is rounded up to a 4 byte size to appease architectures that need
* aligned array sizes */
char *bin2hex(const unsigned char *p, size_t len)
{
unsigned int i;
ssize_t slen;
char *s;
slen = len * 2 + 1;
if (slen % 4)
slen += 4 - (slen % 4);
s = calloc(slen, 1);
if (unlikely(!s))
quit(1, "Failed to calloc in bin2hex");
for (i = 0; i < len; i++)
sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
return s;
}
/* Does the reverse of bin2hex but does not allocate any ram */
bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
{
bool ret = false;
while (*hexstr && len) {
char hex_byte[4];
unsigned int v;
if (unlikely(!hexstr[1])) {
applog(LOG_ERR, "hex2bin str truncated");
return ret;
}
memset(hex_byte, 0, 4);
hex_byte[0] = hexstr[0];
hex_byte[1] = hexstr[1];
if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
return ret;
}
*p = (unsigned char) v;
p++;
hexstr += 2;
len--;
}
if (likely(len == 0 && *hexstr == 0))
ret = true;
return ret;
}
void hash_data(unsigned char *out_hash, const unsigned char *data)
{
unsigned char blkheader[80];
// data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
swap32yes(blkheader, data, 80 / 4);
// double-SHA256 to get the block hash
gen_hash(blkheader, out_hash, 80);
}
// Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
void real_block_target(unsigned char *target, const unsigned char *data)
{
uint8_t targetshift;
if (unlikely(data[72] < 3 || data[72] > 0x20))
{
// Invalid (out of bounds) target
memset(target, 0xff, 32);
return;
}
targetshift = data[72] - 3;
memset(target, 0, targetshift);
target[targetshift++] = data[75];
target[targetshift++] = data[74];
target[targetshift++] = data[73];
memset(&target[targetshift], 0, 0x20 - targetshift);
}
bool hash_target_check(const unsigned char *hash, const unsigned char *target)
{
const uint32_t *h32 = (uint32_t*)&hash[0];
const uint32_t *t32 = (uint32_t*)&target[0];
for (int i = 7; i >= 0; --i) {
uint32_t h32i = le32toh(h32[i]);
uint32_t t32i = le32toh(t32[i]);
if (h32i > t32i)
return false;
if (h32i < t32i)
return true;
}
return true;
}
bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
{
bool rc;
rc = hash_target_check(hash, target);
if (opt_debug) {
unsigned char hash_swap[32], target_swap[32];
char *hash_str, *target_str;
for (int i = 0; i < 32; ++i) {
hash_swap[i] = hash[31-i];
target_swap[i] = target[31-i];
}
hash_str = bin2hex(hash_swap, 32);
target_str = bin2hex(target_swap, 32);
applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
hash_str,
target_str,
rc ? "YES (hash < target)" :
"no (false positive; hash > target)");
free(hash_str);
free(target_str);
}
return rc;
}
// This operates on a native-endian SHA256 state
// In other words, on little endian platforms, every 4 bytes are in reverse order
bool fulltest(const unsigned char *hash, const unsigned char *target)
{
unsigned char hash2[32];
swap32tobe(hash2, hash, 32 / 4);
return hash_target_check_v(hash2, target);
}
struct thread_q *tq_new(void)
{
struct thread_q *tq;
tq = calloc(1, sizeof(*tq));
if (!tq)
return NULL;
INIT_LIST_HEAD(&tq->q);
pthread_mutex_init(&tq->mutex, NULL);
pthread_cond_init(&tq->cond, NULL);
return tq;
}
void tq_free(struct thread_q *tq)
{
struct tq_ent *ent, *iter;
if (!tq)
return;
list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
list_del(&ent->q_node);
free(ent);
}
pthread_cond_destroy(&tq->cond);
pthread_mutex_destroy(&tq->mutex);
memset(tq, 0, sizeof(*tq)); /* poison */
free(tq);
}
static void tq_freezethaw(struct thread_q *tq, bool frozen)
{
mutex_lock(&tq->mutex);
tq->frozen = frozen;
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
}
void tq_freeze(struct thread_q *tq)
{
tq_freezethaw(tq, true);
}
void tq_thaw(struct thread_q *tq)
{
tq_freezethaw(tq, false);
}
bool tq_push(struct thread_q *tq, void *data)
{
struct tq_ent *ent;
bool rc = true;
ent = calloc(1, sizeof(*ent));
if (!ent)
return false;
ent->data = data;
INIT_LIST_HEAD(&ent->q_node);
mutex_lock(&tq->mutex);
if (!tq->frozen) {
list_add_tail(&ent->q_node, &tq->q);
} else {
free(ent);
rc = false;
}
pthread_cond_signal(&tq->cond);
mutex_unlock(&tq->mutex);
return rc;
}
void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
{
struct tq_ent *ent;
void *rval = NULL;
int rc;
mutex_lock(&tq->mutex);
if (!list_empty(&tq->q))
goto pop;
if (abstime)
rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
else
rc = pthread_cond_wait(&tq->cond, &tq->mutex);
if (rc)
goto out;
if (list_empty(&tq->q))
goto out;
pop:
ent = list_entry(tq->q.next, struct tq_ent, q_node);
rval = ent->data;
list_del(&ent->q_node);
free(ent);
out:
mutex_unlock(&tq->mutex);
return rval;
}
int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
{
return pthread_create(&thr->pth, attr, start, arg);
}
void thr_info_freeze(struct thr_info *thr)
{
struct tq_ent *ent, *iter;
struct thread_q *tq;
if (!thr)
return;
tq = thr->q;
if (!tq)
return;
mutex_lock(&tq->mutex);
tq->frozen = true;
list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
list_del(&ent->q_node);
free(ent);
}
mutex_unlock(&tq->mutex);
}
void thr_info_cancel(struct thr_info *thr)
{
if (!thr)
return;
if (PTH(thr) != 0L) {
pthread_cancel(thr->pth);
PTH(thr) = 0L;
}
}
/* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
* on SMP machines */
void nmsleep(unsigned int msecs)
{
struct timespec twait, tleft;
int ret;
ldiv_t d;
d = ldiv(msecs, 1000);
tleft.tv_sec = d.quot;
tleft.tv_nsec = d.rem * 1000000;
do {
twait.tv_sec = tleft.tv_sec;
twait.tv_nsec = tleft.tv_nsec;
ret = nanosleep(&twait, &tleft);
} while (ret == -1 && errno == EINTR);
}
/* Returns the microseconds difference between end and start times as a double */
double us_tdiff(struct timeval *end, struct timeval *start)
{
return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
}
/* Returns the seconds difference between end and start times as a double */
double tdiff(struct timeval *end, struct timeval *start)
{
return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
}
bool extract_sockaddr(struct pool *pool, char *url)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
if (url_len >= sizeof(url_address))
{
applog(LOG_WARNING, "%s: Truncating overflowed address '%.*s'",
__func__, url_len, url_begin);
url_len = sizeof(url_address) - 1;
}
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len)
snprintf(port, 6, "%.*s", port_len, port_start);
else
strcpy(port, "80");
free(pool->stratum_port);
pool->stratum_port = strdup(port);
free(pool->sockaddr_url);
pool->sockaddr_url = strdup(url_address);
return true;
}
/* Send a single command across a socket, appending \n to it. This should all
* be done under stratum lock except when first establishing the socket */
static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
{
SOCKETTYPE sock = pool->sock;
ssize_t ssent = 0;
if (opt_protocol)
applog(LOG_DEBUG, "SEND: %s", s);
strcat(s, "\n");
len++;
while (len > 0 ) {
struct timeval timeout = {0, 0};
ssize_t sent;
fd_set wd;
FD_ZERO(&wd);
FD_SET(sock, &wd);
if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
return false;
}
sent = send(pool->sock, s + ssent, len, 0);
if (sent < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
return false;
}
sent = 0;
}
ssent += sent;
len -= sent;
}
pool->cgminer_pool_stats.times_sent++;
pool->cgminer_pool_stats.bytes_sent += ssent;
total_bytes_xfer += ssent;
pool->cgminer_pool_stats.net_bytes_sent += ssent;
return true;
}
bool stratum_send(struct pool *pool, char *s, ssize_t len)
{
bool ret = false;
mutex_lock(&pool->stratum_lock);
if (pool->stratum_active)
ret = __stratum_send(pool, s, len);
else
applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
mutex_unlock(&pool->stratum_lock);
return ret;
}
static bool socket_full(struct pool *pool, bool wait)
{
SOCKETTYPE sock = pool->sock;
struct timeval timeout;
fd_set rd;
FD_ZERO(&rd);
FD_SET(sock, &rd);
timeout.tv_usec = 0;
if (wait)
timeout.tv_sec = 60;
else
timeout.tv_sec = 0;
if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
return true;
return false;
}
/* Check to see if Santa's been good to you */
bool sock_full(struct pool *pool)
{
if (strlen(pool->sockbuf))
return true;
return (socket_full(pool, false));
}
static void clear_sock(struct pool *pool)
{
ssize_t n;
mutex_lock(&pool->stratum_lock);
do
n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
while (n > 0);
mutex_unlock(&pool->stratum_lock);
strcpy(pool->sockbuf, "");
}
/* Make sure the pool sockbuf is large enough to cope with any coinbase size
* by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
* and zeroing the new memory */
static void recalloc_sock(struct pool *pool, size_t len)
{
size_t old, new;
old = strlen(pool->sockbuf);
new = old + len + 1;
if (new < pool->sockbuf_size)
return;
new = new + (RBUFSIZE - (new % RBUFSIZE));
applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
pool->sockbuf = realloc(pool->sockbuf, new);
if (!pool->sockbuf)
quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
memset(pool->sockbuf + old, 0, new - old);
pool->sockbuf_size = new;
}
/* Peeks at a socket to find the first end of line and then reads just that
* from the socket and returns that as a malloced char */
char *recv_line(struct pool *pool)
{
ssize_t len, buflen;
char *tok, *sret = NULL;
if (!strstr(pool->sockbuf, "\n")) {
struct timeval rstart, now;
gettimeofday(&rstart, NULL);
if (!socket_full(pool, true)) {
applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
goto out;
}
mutex_lock(&pool->stratum_lock);
do {
char s[RBUFSIZE];
size_t slen, n;
memset(s, 0, RBUFSIZE);
n = recv(pool->sock, s, RECVSIZE, 0);
if (n < 1 && errno != EAGAIN && errno != EWOULDBLOCK) {
applog(LOG_DEBUG, "Failed to recv sock in recv_line");
break;
}
slen = strlen(s);
recalloc_sock(pool, slen);
strcat(pool->sockbuf, s);
gettimeofday(&now, NULL);
} while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
mutex_unlock(&pool->stratum_lock);
}
buflen = strlen(pool->sockbuf);
tok = strtok(pool->sockbuf, "\n");
if (!tok) {
applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
goto out;
}
sret = strdup(tok);
len = strlen(sret);
/* Copy what's left in the buffer after the \n, including the
* terminating \0 */
if (buflen > len + 1)
memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
else
strcpy(pool->sockbuf, "");
pool->cgminer_pool_stats.times_received++;
pool->cgminer_pool_stats.bytes_received += len;
total_bytes_xfer += len;
pool->cgminer_pool_stats.net_bytes_received += len;
out:
if (!sret)
clear_sock(pool);
else if (opt_protocol)
applog(LOG_DEBUG, "RECVD: %s", sret);
return sret;
}
/* Extracts a string value from a json array with error checking. To be used
* when the value of the string returned is only examined and not to be stored.
* See json_array_string below */
static char *__json_array_string(json_t *val, unsigned int entry)
{
json_t *arr_entry;
if (json_is_null(val))
return NULL;
if (!json_is_array(val))
return NULL;
if (entry > json_array_size(val))
return NULL;
arr_entry = json_array_get(val, entry);
if (!json_is_string(arr_entry))
return NULL;
return (char *)json_string_value(arr_entry);
}
/* Creates a freshly malloced dup of __json_array_string */
static char *json_array_string(json_t *val, unsigned int entry)
{
char *buf = __json_array_string(val, entry);
if (buf)
return strdup(buf);
return NULL;
}
void stratum_probe_transparency(struct pool *pool)
{
// Request transaction data to discourage pools from doing anything shady
char s[1024];
int sLen;
sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
pool->swork.job_id,
pool->swork.job_id);
stratum_send(pool, s, sLen);
if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
pool->swork.transparency_time = time(NULL);
pool->swork.transparency_probed = true;
}
static bool parse_notify(struct pool *pool, json_t *val)
{
char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
bool clean, ret = false;
int merkles, i;
json_t *arr;
arr = json_array_get(val, 4);
if (!arr || !json_is_array(arr))
goto out;
merkles = json_array_size(arr);
job_id = json_array_string(val, 0);
prev_hash = json_array_string(val, 1);
coinbase1 = json_array_string(val, 2);
coinbase2 = json_array_string(val, 3);
bbversion = json_array_string(val, 5);
nbit = json_array_string(val, 6);
ntime = json_array_string(val, 7);
clean = json_is_true(json_array_get(val, 8));
if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
/* Annoying but we must not leak memory */
if (job_id)
free(job_id);
if (prev_hash)
free(prev_hash);
if (coinbase1)
free(coinbase1);
if (coinbase2)
free(coinbase2);
if (bbversion)
free(bbversion);
if (nbit)
free(nbit);
if (ntime)
free(ntime);
goto out;
}
mutex_lock(&pool->pool_lock);
free(pool->swork.job_id);
free(pool->swork.prev_hash);
free(pool->swork.coinbase1);
free(pool->swork.coinbase2);
free(pool->swork.bbversion);
free(pool->swork.nbit);
free(pool->swork.ntime);
pool->swork.job_id = job_id;
pool->swork.prev_hash = prev_hash;
pool->swork.coinbase1 = coinbase1;
pool->swork.cb1_len = strlen(coinbase1) / 2;
pool->swork.coinbase2 = coinbase2;
pool->swork.cb2_len = strlen(coinbase2) / 2;
pool->swork.bbversion = bbversion;
pool->swork.nbit = nbit;
pool->swork.ntime = ntime;
pool->submit_old = !clean;
pool->swork.clean = true;
pool->swork.cb_len = pool->swork.cb1_len + pool->n1_len + pool->n2size + pool->swork.cb2_len;
for (i = 0; i < pool->swork.merkles; i++)
free(pool->swork.merkle[i]);
if (merkles) {
pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
for (i = 0; i < merkles; i++)
pool->swork.merkle[i] = json_array_string(arr, i);
}
pool->swork.merkles = merkles;
if (clean)
pool->nonce2 = 0;
pool->swork.header_len = strlen(pool->swork.bbversion) +
strlen(pool->swork.prev_hash) +
strlen(pool->swork.ntime) +
strlen(pool->swork.nbit) +
/* merkle_hash */ 32 +
/* nonce */ 8 +
/* workpadding */ 96;
pool->swork.header_len = pool->swork.header_len * 2 + 1;
align_len(&pool->swork.header_len);
mutex_unlock(&pool->pool_lock);
applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
pool->pool_no, job_id);
if (opt_protocol) {
applog(LOG_DEBUG, "job_id: %s", job_id);
applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
for (i = 0; i < merkles; i++)
applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
applog(LOG_DEBUG, "bbversion: %s", bbversion);
applog(LOG_DEBUG, "nbit: %s", nbit);
applog(LOG_DEBUG, "ntime: %s", ntime);
applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
}
/* A notify message is the closest stratum gets to a getwork */
pool->getwork_requested++;
total_getworks++;
if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
if (pool->stratum_auth)
stratum_probe_transparency(pool);
ret = true;
out:
return ret;
}
static bool parse_diff(struct pool *pool, json_t *val)
{
double diff;
diff = json_number_value(json_array_get(val, 0));
if (diff == 0)
return false;
mutex_lock(&pool->pool_lock);
pool->swork.diff = diff;
mutex_unlock(&pool->pool_lock);
applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
return true;
}
static bool parse_reconnect(struct pool *pool, json_t *val)
{
char *url, *port, address[256];
memset(address, 0, 255);
url = (char *)json_string_value(json_array_get(val, 0));
if (!url)
url = pool->sockaddr_url;
port = (char *)json_string_value(json_array_get(val, 1));
if (!port)
port = pool->stratum_port;
sprintf(address, "%s:%s", url, port);
if (!extract_sockaddr(pool, address))
return false;
pool->stratum_url = pool->sockaddr_url;
applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
if (!restart_stratum(pool))
return false;
return true;
}
static bool send_version(struct pool *pool, json_t *val)
{
char s[RBUFSIZE];
int id = json_integer_value(json_object_get(val, "id"));
if (!id)
return false;
sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
if (!stratum_send(pool, s, strlen(s)))
return false;
return true;
}
bool parse_method(struct pool *pool, char *s)
{
json_t *val = NULL, *method, *err_val, *params;
json_error_t err;
bool ret = false;
char *buf;
if (!s)
goto out;
val = JSON_LOADS(s, &err);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
method = json_object_get(val, "method");
if (!method)
goto out;
err_val = json_object_get(val, "error");
params = json_object_get(val, "params");
if (err_val && !json_is_null(err_val)) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
free(ss);
goto out;
}
buf = (char *)json_string_value(method);
if (!buf)
goto out;
if (!strncasecmp(buf, "mining.notify", 13)) {
if (parse_notify(pool, params))
pool->stratum_notify = ret = true;
else
pool->stratum_notify = ret = false;
goto out;
}
if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
ret = true;
goto out;
}
if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
ret = true;
goto out;
}
if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
ret = true;
goto out;
}
out:
if (val)
json_decref(val);
return ret;
}
extern bool parse_stratum_response(struct pool *, char *s);
bool auth_stratum(struct pool *pool)
{
json_t *val = NULL, *res_val, *err_val;
char s[RBUFSIZE], *sret = NULL;
json_error_t err;
bool ret = false;
sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
pool->rpc_user, pool->rpc_pass);
if (!stratum_send(pool, s, strlen(s)))
goto out;
/* Parse all data in the queue and anything left should be auth */
while (42) {
sret = recv_line(pool);
if (!sret)
goto out;
if (parse_method(pool, sret))
free(sret);
else
break;
}
val = JSON_LOADS(sret, &err);
free(sret);
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
free(ss);
goto out;
}
ret = true;
applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
pool->probed = true;
pool->stratum_auth = true;
successful_connect = true;
out:
if (val)
json_decref(val);
if (pool->stratum_notify)
stratum_probe_transparency(pool);
return ret;
}
curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
{
struct pool *pool = clientp;
curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
pool->sock = sck;
return sck;
}
static bool setup_stratum_curl(struct pool *pool)
{
char curl_err_str[CURL_ERROR_SIZE];
CURL *curl = NULL;
char s[RBUFSIZE];
applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
mutex_lock(&pool->stratum_lock);
pool->swork.transparency_time = (time_t)-1;
pool->stratum_active = false;
pool->stratum_auth = false;
pool->stratum_notify = false;
pool->swork.transparency_probed = false;
if (!pool->stratum_curl) {
pool->stratum_curl = curl_easy_init();
if (unlikely(!pool->stratum_curl))
quit(1, "Failed to curl_easy_init in initiate_stratum");
}
if (pool->sockbuf)
pool->sockbuf[0] = '\0';
mutex_unlock(&pool->stratum_lock);
curl = pool->stratum_curl;
if (!pool->sockbuf) {
pool->sockbuf = calloc(RBUFSIZE, 1);
if (!pool->sockbuf)
quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
pool->sockbuf_size = RBUFSIZE;
}
/* Create a http url for use with curl */
sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
curl_easy_setopt(curl, CURLOPT_URL, s);
curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
/* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
* to enable it */
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
// CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
if (pool->rpc_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
} else if (opt_socks_proxy) {
curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
}
curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
pool->sock = INVSOCK;
if (curl_easy_perform(curl)) {
applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
return false;
}
if (pool->sock == INVSOCK)
{
curl_easy_cleanup(curl);
applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
return false;
}
keep_sockalive(pool->sock);
pool->cgminer_pool_stats.times_sent++;
pool->cgminer_pool_stats.times_received++;
return true;
}
bool initiate_stratum(struct pool *pool)
{
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
bool ret = false, recvd = false;
json_error_t err;
int n2size;
if (!setup_stratum_curl(pool))
goto out;
resend:
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
if (!__stratum_send(pool, s, strlen(s))) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, true)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = json_array_string(json_array_get(res_val, 0), 1);
if (!sessionid) {
applog(LOG_INFO, "Failed to get sessionid in initiate_stratum");
goto out;
}
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (n2size < 1)
{
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
mutex_lock(&pool->pool_lock);
pool->sessionid = sessionid;
free(pool->nonce1);
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
pool->n2size = n2size;
mutex_unlock(&pool->pool_lock);
applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
ret = true;
out:
if (val)
json_decref(val);
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
pool->pool_no, pool->nonce1, pool->n2size);
}
} else {
if (recvd && pool->sessionid) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
mutex_lock(&pool->pool_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
mutex_unlock(&pool->pool_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
goto resend;
}
applog(LOG_DEBUG, "Initiate stratum failed");
if (pool->sock != INVSOCK) {
shutdown(pool->sock, SHUT_RDWR);
pool->sock = INVSOCK;
}
}
return ret;
}
bool restart_stratum(struct pool *pool)
{
if (!initiate_stratum(pool))
return false;
if (!auth_stratum(pool))
return false;
return true;
}
void suspend_stratum(struct pool *pool)
{
applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
mutex_lock(&pool->stratum_lock);
pool->stratum_active = false;
pool->stratum_auth = false;
curl_easy_cleanup(pool->stratum_curl);
pool->stratum_curl = NULL;
pool->sock = INVSOCK;
mutex_unlock(&pool->stratum_lock);
}
void dev_error(struct cgpu_info *dev, enum dev_reason reason)
{
dev->device_last_not_well = time(NULL);
dev->device_not_well_reason = reason;
switch (reason) {
case REASON_THREAD_FAIL_INIT:
dev->thread_fail_init_count++;
break;
case REASON_THREAD_ZERO_HASH:
dev->thread_zero_hash_count++;
break;
case REASON_THREAD_FAIL_QUEUE:
dev->thread_fail_queue_count++;
break;
case REASON_DEV_SICK_IDLE_60:
dev->dev_sick_idle_60_count++;
break;
case REASON_DEV_DEAD_IDLE_600:
dev->dev_dead_idle_600_count++;
break;
case REASON_DEV_NOSTART:
dev->dev_nostart_count++;
break;
case REASON_DEV_OVER_HEAT:
dev->dev_over_heat_count++;
break;
case REASON_DEV_THERMAL_CUTOFF:
dev->dev_thermal_cutoff_count++;
break;
case REASON_DEV_COMMS_ERROR:
dev->dev_comms_error_count++;
break;
case REASON_DEV_THROTTLE:
dev->dev_throttle_count++;
break;
}
}
/* Realloc an existing string to fit an extra string s, appending s to it. */
void *realloc_strcat(char *ptr, char *s)
{
size_t old = strlen(ptr), len = strlen(s);
char *ret;
if (!len)
return ptr;
len += old + 1;
align_len(&len);
ret = malloc(len);
if (unlikely(!ret))
quit(1, "Failed to malloc in realloc_strcat");
sprintf(ret, "%s%s", ptr, s);
free(ptr);
return ret;
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
prctl(PR_SET_NAME, name, 0, 0, 0);
#elif defined(__APPLE__)
pthread_setname_np(name);
#elif (defined(__FreeBSD__) || defined(__OpenBSD__))
pthread_set_name_np(pthread_self(), name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
#ifdef WIN32
static const char *WindowsErrorStr(DWORD dwMessageId)
{
static LPSTR msg = NULL;
if (msg)
LocalFree(msg);
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, dwMessageId, 0, (LPSTR)&msg, 0, 0))
return msg;
static const char fmt[] = "Error #%ld";
signed long ldMsgId = dwMessageId;
int sz = snprintf((char*)&sz, 0, fmt, ldMsgId) + 1;
msg = (LPTSTR)LocalAlloc(LMEM_FIXED, sz);
sprintf((char*)msg, fmt, ldMsgId);
return msg;
}
#endif
void notifier_init(notifier_t pipefd)
{
#ifdef WIN32
SOCKET listener, connecter, acceptor;
listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener == INVALID_SOCKET)
quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
connecter = socket(AF_INET, SOCK_STREAM, 0);
if (connecter == INVALID_SOCKET)
quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
struct sockaddr_in inaddr = {
.sin_family = AF_INET,
.sin_addr = {
.s_addr = htonl(INADDR_LOOPBACK),
},
.sin_port = 0,
};
{
char reuse = 1;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
}
if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
socklen_t inaddr_sz = sizeof(inaddr);
if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
if (listen(listener, 1) == SOCKET_ERROR)
quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
inaddr.sin_family = AF_INET;
inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
acceptor = accept(listener, NULL, NULL);
if (acceptor == INVALID_SOCKET)
quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
closesocket(listener);
pipefd[0] = connecter;
pipefd[1] = acceptor;
#else
if (pipe(pipefd))
quit(1, "Failed to create pipe in create_notifier");
#endif
}
void notifier_wake(notifier_t fd)
{
if (fd[1] == INVSOCK)
return;
#ifdef WIN32
(void)send(fd[1], "\0", 1, 0);
#else
(void)write(fd[1], "\0", 1);
#endif
}
void notifier_read(notifier_t fd)
{
char buf[0x10];
#ifdef WIN32
(void)recv(fd[0], buf, sizeof(buf), 0);
#else
(void)read(fd[0], buf, sizeof(buf));
#endif
}
void notifier_destroy(notifier_t fd)
{
#ifdef WIN32
closesocket(fd[0]);
closesocket(fd[1]);
#else
close(fd[0]);
close(fd[1]);
#endif
fd[0] = fd[1] = INVSOCK;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_2210_0 |
crossvul-cpp_data_bad_5590_2 | /*
* linux/fs/nls/nls_base.c
*
* Native language support--charsets and unicode translations.
* By Gordon Chaffee 1996, 1997
*
* Unicode based case conversion 1999 by Wolfram Pienkoss
*
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/kmod.h>
#include <linux/spinlock.h>
#include <asm/byteorder.h>
static struct nls_table default_table;
static struct nls_table *tables = &default_table;
static DEFINE_SPINLOCK(nls_lock);
/*
* Sample implementation from Unicode home page.
* http://www.stonehand.com/unicode/standard/fss-utf.html
*/
struct utf8_table {
int cmask;
int cval;
int shift;
long lmask;
long lval;
};
static const struct utf8_table utf8_table[] =
{
{0x80, 0x00, 0*6, 0x7F, 0, /* 1 byte sequence */},
{0xE0, 0xC0, 1*6, 0x7FF, 0x80, /* 2 byte sequence */},
{0xF0, 0xE0, 2*6, 0xFFFF, 0x800, /* 3 byte sequence */},
{0xF8, 0xF0, 3*6, 0x1FFFFF, 0x10000, /* 4 byte sequence */},
{0xFC, 0xF8, 4*6, 0x3FFFFFF, 0x200000, /* 5 byte sequence */},
{0xFE, 0xFC, 5*6, 0x7FFFFFFF, 0x4000000, /* 6 byte sequence */},
{0, /* end of table */}
};
#define UNICODE_MAX 0x0010ffff
#define PLANE_SIZE 0x00010000
#define SURROGATE_MASK 0xfffff800
#define SURROGATE_PAIR 0x0000d800
#define SURROGATE_LOW 0x00000400
#define SURROGATE_BITS 0x000003ff
int utf8_to_utf32(const u8 *s, int len, unicode_t *pu)
{
unsigned long l;
int c0, c, nc;
const struct utf8_table *t;
nc = 0;
c0 = *s;
l = c0;
for (t = utf8_table; t->cmask; t++) {
nc++;
if ((c0 & t->cmask) == t->cval) {
l &= t->lmask;
if (l < t->lval || l > UNICODE_MAX ||
(l & SURROGATE_MASK) == SURROGATE_PAIR)
return -1;
*pu = (unicode_t) l;
return nc;
}
if (len <= nc)
return -1;
s++;
c = (*s ^ 0x80) & 0xFF;
if (c & 0xC0)
return -1;
l = (l << 6) | c;
}
return -1;
}
EXPORT_SYMBOL(utf8_to_utf32);
int utf32_to_utf8(unicode_t u, u8 *s, int maxlen)
{
unsigned long l;
int c, nc;
const struct utf8_table *t;
if (!s)
return 0;
l = u;
if (l > UNICODE_MAX || (l & SURROGATE_MASK) == SURROGATE_PAIR)
return -1;
nc = 0;
for (t = utf8_table; t->cmask && maxlen; t++, maxlen--) {
nc++;
if (l <= t->lmask) {
c = t->shift;
*s = (u8) (t->cval | (l >> c));
while (c > 0) {
c -= 6;
s++;
*s = (u8) (0x80 | ((l >> c) & 0x3F));
}
return nc;
}
}
return -1;
}
EXPORT_SYMBOL(utf32_to_utf8);
int utf8s_to_utf16s(const u8 *s, int len, wchar_t *pwcs)
{
u16 *op;
int size;
unicode_t u;
op = pwcs;
while (*s && len > 0) {
if (*s & 0x80) {
size = utf8_to_utf32(s, len, &u);
if (size < 0)
return -EINVAL;
if (u >= PLANE_SIZE) {
u -= PLANE_SIZE;
*op++ = (wchar_t) (SURROGATE_PAIR |
((u >> 10) & SURROGATE_BITS));
*op++ = (wchar_t) (SURROGATE_PAIR |
SURROGATE_LOW |
(u & SURROGATE_BITS));
} else {
*op++ = (wchar_t) u;
}
s += size;
len -= size;
} else {
*op++ = *s++;
len--;
}
}
return op - pwcs;
}
EXPORT_SYMBOL(utf8s_to_utf16s);
static inline unsigned long get_utf16(unsigned c, enum utf16_endian endian)
{
switch (endian) {
default:
return c;
case UTF16_LITTLE_ENDIAN:
return __le16_to_cpu(c);
case UTF16_BIG_ENDIAN:
return __be16_to_cpu(c);
}
}
int utf16s_to_utf8s(const wchar_t *pwcs, int len, enum utf16_endian endian,
u8 *s, int maxlen)
{
u8 *op;
int size;
unsigned long u, v;
op = s;
while (len > 0 && maxlen > 0) {
u = get_utf16(*pwcs, endian);
if (!u)
break;
pwcs++;
len--;
if (u > 0x7f) {
if ((u & SURROGATE_MASK) == SURROGATE_PAIR) {
if (u & SURROGATE_LOW) {
/* Ignore character and move on */
continue;
}
if (len <= 0)
break;
v = get_utf16(*pwcs, endian);
if ((v & SURROGATE_MASK) != SURROGATE_PAIR ||
!(v & SURROGATE_LOW)) {
/* Ignore character and move on */
continue;
}
u = PLANE_SIZE + ((u & SURROGATE_BITS) << 10)
+ (v & SURROGATE_BITS);
pwcs++;
len--;
}
size = utf32_to_utf8(u, op, maxlen);
if (size == -1) {
/* Ignore character and move on */
} else {
op += size;
maxlen -= size;
}
} else {
*op++ = (u8) u;
maxlen--;
}
}
return op - s;
}
EXPORT_SYMBOL(utf16s_to_utf8s);
int register_nls(struct nls_table * nls)
{
struct nls_table ** tmp = &tables;
if (nls->next)
return -EBUSY;
spin_lock(&nls_lock);
while (*tmp) {
if (nls == *tmp) {
spin_unlock(&nls_lock);
return -EBUSY;
}
tmp = &(*tmp)->next;
}
nls->next = tables;
tables = nls;
spin_unlock(&nls_lock);
return 0;
}
int unregister_nls(struct nls_table * nls)
{
struct nls_table ** tmp = &tables;
spin_lock(&nls_lock);
while (*tmp) {
if (nls == *tmp) {
*tmp = nls->next;
spin_unlock(&nls_lock);
return 0;
}
tmp = &(*tmp)->next;
}
spin_unlock(&nls_lock);
return -EINVAL;
}
static struct nls_table *find_nls(char *charset)
{
struct nls_table *nls;
spin_lock(&nls_lock);
for (nls = tables; nls; nls = nls->next) {
if (!strcmp(nls->charset, charset))
break;
if (nls->alias && !strcmp(nls->alias, charset))
break;
}
if (nls && !try_module_get(nls->owner))
nls = NULL;
spin_unlock(&nls_lock);
return nls;
}
struct nls_table *load_nls(char *charset)
{
return try_then_request_module(find_nls(charset), "nls_%s", charset);
}
void unload_nls(struct nls_table *nls)
{
if (nls)
module_put(nls->owner);
}
static const wchar_t charset2uni[256] = {
/* 0x00*/
0x0000, 0x0001, 0x0002, 0x0003,
0x0004, 0x0005, 0x0006, 0x0007,
0x0008, 0x0009, 0x000a, 0x000b,
0x000c, 0x000d, 0x000e, 0x000f,
/* 0x10*/
0x0010, 0x0011, 0x0012, 0x0013,
0x0014, 0x0015, 0x0016, 0x0017,
0x0018, 0x0019, 0x001a, 0x001b,
0x001c, 0x001d, 0x001e, 0x001f,
/* 0x20*/
0x0020, 0x0021, 0x0022, 0x0023,
0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002a, 0x002b,
0x002c, 0x002d, 0x002e, 0x002f,
/* 0x30*/
0x0030, 0x0031, 0x0032, 0x0033,
0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003a, 0x003b,
0x003c, 0x003d, 0x003e, 0x003f,
/* 0x40*/
0x0040, 0x0041, 0x0042, 0x0043,
0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004a, 0x004b,
0x004c, 0x004d, 0x004e, 0x004f,
/* 0x50*/
0x0050, 0x0051, 0x0052, 0x0053,
0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005a, 0x005b,
0x005c, 0x005d, 0x005e, 0x005f,
/* 0x60*/
0x0060, 0x0061, 0x0062, 0x0063,
0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006a, 0x006b,
0x006c, 0x006d, 0x006e, 0x006f,
/* 0x70*/
0x0070, 0x0071, 0x0072, 0x0073,
0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007a, 0x007b,
0x007c, 0x007d, 0x007e, 0x007f,
/* 0x80*/
0x0080, 0x0081, 0x0082, 0x0083,
0x0084, 0x0085, 0x0086, 0x0087,
0x0088, 0x0089, 0x008a, 0x008b,
0x008c, 0x008d, 0x008e, 0x008f,
/* 0x90*/
0x0090, 0x0091, 0x0092, 0x0093,
0x0094, 0x0095, 0x0096, 0x0097,
0x0098, 0x0099, 0x009a, 0x009b,
0x009c, 0x009d, 0x009e, 0x009f,
/* 0xa0*/
0x00a0, 0x00a1, 0x00a2, 0x00a3,
0x00a4, 0x00a5, 0x00a6, 0x00a7,
0x00a8, 0x00a9, 0x00aa, 0x00ab,
0x00ac, 0x00ad, 0x00ae, 0x00af,
/* 0xb0*/
0x00b0, 0x00b1, 0x00b2, 0x00b3,
0x00b4, 0x00b5, 0x00b6, 0x00b7,
0x00b8, 0x00b9, 0x00ba, 0x00bb,
0x00bc, 0x00bd, 0x00be, 0x00bf,
/* 0xc0*/
0x00c0, 0x00c1, 0x00c2, 0x00c3,
0x00c4, 0x00c5, 0x00c6, 0x00c7,
0x00c8, 0x00c9, 0x00ca, 0x00cb,
0x00cc, 0x00cd, 0x00ce, 0x00cf,
/* 0xd0*/
0x00d0, 0x00d1, 0x00d2, 0x00d3,
0x00d4, 0x00d5, 0x00d6, 0x00d7,
0x00d8, 0x00d9, 0x00da, 0x00db,
0x00dc, 0x00dd, 0x00de, 0x00df,
/* 0xe0*/
0x00e0, 0x00e1, 0x00e2, 0x00e3,
0x00e4, 0x00e5, 0x00e6, 0x00e7,
0x00e8, 0x00e9, 0x00ea, 0x00eb,
0x00ec, 0x00ed, 0x00ee, 0x00ef,
/* 0xf0*/
0x00f0, 0x00f1, 0x00f2, 0x00f3,
0x00f4, 0x00f5, 0x00f6, 0x00f7,
0x00f8, 0x00f9, 0x00fa, 0x00fb,
0x00fc, 0x00fd, 0x00fe, 0x00ff,
};
static const unsigned char page00[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char *const page_uni2charset[256] = {
page00
};
static const unsigned char charset2lower[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x40-0x47 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x48-0x4f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x50-0x57 */
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 0x60-0x67 */
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, /* 0x68-0x6f */
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, /* 0x70-0x77 */
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static const unsigned char charset2upper[256] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 0x00-0x07 */
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 0x08-0x0f */
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 0x10-0x17 */
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 0x18-0x1f */
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, /* 0x20-0x27 */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, /* 0x28-0x2f */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* 0x30-0x37 */
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, /* 0x38-0x3f */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x40-0x47 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x48-0x4f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x50-0x57 */
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, /* 0x58-0x5f */
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* 0x60-0x67 */
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, /* 0x68-0x6f */
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, /* 0x70-0x77 */
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, /* 0x78-0x7f */
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 0x80-0x87 */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 0x88-0x8f */
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 0x90-0x97 */
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 0x98-0x9f */
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* 0xa0-0xa7 */
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* 0xa8-0xaf */
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* 0xb0-0xb7 */
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* 0xb8-0xbf */
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 0xc0-0xc7 */
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, /* 0xc8-0xcf */
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, /* 0xd0-0xd7 */
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, /* 0xd8-0xdf */
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* 0xe0-0xe7 */
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* 0xe8-0xef */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 0xf0-0xf7 */
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* 0xf8-0xff */
};
static int uni2char(wchar_t uni, unsigned char *out, int boundlen)
{
const unsigned char *uni2charset;
unsigned char cl = uni & 0x00ff;
unsigned char ch = (uni & 0xff00) >> 8;
if (boundlen <= 0)
return -ENAMETOOLONG;
uni2charset = page_uni2charset[ch];
if (uni2charset && uni2charset[cl])
out[0] = uni2charset[cl];
else
return -EINVAL;
return 1;
}
static int char2uni(const unsigned char *rawstring, int boundlen, wchar_t *uni)
{
*uni = charset2uni[*rawstring];
if (*uni == 0x0000)
return -EINVAL;
return 1;
}
static struct nls_table default_table = {
.charset = "default",
.uni2char = uni2char,
.char2uni = char2uni,
.charset2lower = charset2lower,
.charset2upper = charset2upper,
};
/* Returns a simple default translation table */
struct nls_table *load_nls_default(void)
{
struct nls_table *default_nls;
default_nls = load_nls(CONFIG_NLS_DEFAULT);
if (default_nls != NULL)
return default_nls;
else
return &default_table;
}
EXPORT_SYMBOL(register_nls);
EXPORT_SYMBOL(unregister_nls);
EXPORT_SYMBOL(unload_nls);
EXPORT_SYMBOL(load_nls);
EXPORT_SYMBOL(load_nls_default);
MODULE_LICENSE("Dual BSD/GPL");
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_5590_2 |
crossvul-cpp_data_bad_4063_2 | /*
* rre.c
*
* Routines to implement Rise-and-Run-length Encoding (RRE). This
* code is based on krw's original javatel rfbserver.
*/
/*
* 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>
/*
* cl->beforeEncBuf contains pixel data in the client's format.
* cl->afterEncBuf contains the RRE encoded version. If the RRE encoded version is
* larger than the raw data or if it exceeds cl->afterEncBufSize then
* raw encoding is used instead.
*/
static int subrectEncode8(rfbClientPtr cl, uint8_t *data, int w, int h);
static int subrectEncode16(rfbClientPtr cl, uint16_t *data, int w, int h);
static int subrectEncode32(rfbClientPtr cl, uint32_t *data, int w, int h);
static uint32_t getBgColour(char *data, int size, int bpp);
/*
* rfbSendRectEncodingRRE - send a given rectangle using RRE encoding.
*/
rfbBool
rfbSendRectEncodingRRE(rfbClientPtr cl,
int x,
int y,
int w,
int h)
{
rfbFramebufferUpdateRectHeader rect;
rfbRREHeader hdr;
int nSubrects;
int i;
char *fbptr = (cl->scaledScreen->frameBuffer + (cl->scaledScreen->paddedWidthInBytes * y)
+ (x * (cl->scaledScreen->bitsPerPixel / 8)));
int maxRawSize = (cl->scaledScreen->width * cl->scaledScreen->height
* (cl->format.bitsPerPixel / 8));
if (cl->beforeEncBufSize < maxRawSize) {
cl->beforeEncBufSize = maxRawSize;
if (cl->beforeEncBuf == NULL)
cl->beforeEncBuf = (char *)malloc(cl->beforeEncBufSize);
else
cl->beforeEncBuf = (char *)realloc(cl->beforeEncBuf, cl->beforeEncBufSize);
}
if (cl->afterEncBufSize < maxRawSize) {
cl->afterEncBufSize = maxRawSize;
if (cl->afterEncBuf == NULL)
cl->afterEncBuf = (char *)malloc(cl->afterEncBufSize);
else
cl->afterEncBuf = (char *)realloc(cl->afterEncBuf, cl->afterEncBufSize);
}
(*cl->translateFn)(cl->translateLookupTable,
&(cl->screen->serverFormat),
&cl->format, fbptr, cl->beforeEncBuf,
cl->scaledScreen->paddedWidthInBytes, w, h);
switch (cl->format.bitsPerPixel) {
case 8:
nSubrects = subrectEncode8(cl, (uint8_t *)cl->beforeEncBuf, w, h);
break;
case 16:
nSubrects = subrectEncode16(cl, (uint16_t *)cl->beforeEncBuf, w, h);
break;
case 32:
nSubrects = subrectEncode32(cl, (uint32_t *)cl->beforeEncBuf, w, h);
break;
default:
rfbLog("getBgColour: bpp %d?\n",cl->format.bitsPerPixel);
return FALSE;
}
if (nSubrects < 0) {
/* RRE encoding was too large, use raw */
return rfbSendRectEncodingRaw(cl, x, y, w, h);
}
rfbStatRecordEncodingSent(cl, rfbEncodingRRE,
sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader + cl->afterEncBufLen,
sz_rfbFramebufferUpdateRectHeader + w * h * (cl->format.bitsPerPixel / 8));
if (cl->ublen + sz_rfbFramebufferUpdateRectHeader + sz_rfbRREHeader
> 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(rfbEncodingRRE);
memcpy(&cl->updateBuf[cl->ublen], (char *)&rect,
sz_rfbFramebufferUpdateRectHeader);
cl->ublen += sz_rfbFramebufferUpdateRectHeader;
hdr.nSubrects = Swap32IfLE(nSubrects);
memcpy(&cl->updateBuf[cl->ublen], (char *)&hdr, sz_rfbRREHeader);
cl->ublen += sz_rfbRREHeader;
for (i = 0; i < cl->afterEncBufLen;) {
int bytesToCopy = UPDATE_BUF_SIZE - cl->ublen;
if (i + bytesToCopy > cl->afterEncBufLen) {
bytesToCopy = cl->afterEncBufLen - i;
}
memcpy(&cl->updateBuf[cl->ublen], &cl->afterEncBuf[i], bytesToCopy);
cl->ublen += bytesToCopy;
i += bytesToCopy;
if (cl->ublen == UPDATE_BUF_SIZE) {
if (!rfbSendUpdateBuf(cl))
return FALSE;
}
}
return TRUE;
}
/*
* subrectEncode() encodes the given multicoloured rectangle as a background
* colour overwritten by single-coloured rectangles. It returns the number
* of subrectangles in the encoded buffer, or -1 if subrect encoding won't
* fit in the buffer. It puts the encoded rectangles in cl->afterEncBuf. The
* single-colour rectangle partition is not optimal, but does find the biggest
* horizontal or vertical rectangle top-left anchored to each consecutive
* coordinate position.
*
* The coding scheme is simply [<bgcolour><subrect><subrect>...] where each
* <subrect> is [<colour><x><y><w><h>].
*/
#define DEFINE_SUBRECT_ENCODE(bpp) \
static int \
subrectEncode##bpp(rfbClientPtr client, uint##bpp##_t *data, int w, int h) { \
uint##bpp##_t cl; \
rfbRectangle subrect; \
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; \
uint##bpp##_t bg = (uint##bpp##_t)getBgColour((char*)data,w*h,bpp); \
\
*((uint##bpp##_t*)client->afterEncBuf) = bg; \
\
client->afterEncBufLen = (bpp/8); \
\
for (y=0; y<h; y++) { \
line = data+(y*w); \
for (x=0; x<w; x++) { \
if (line[x] != bg) { \
cl = line[x]; \
hy = y-1; \
hyflag = 1; \
for (j=y; j<h; j++) { \
seg = data+(j*w); \
if (seg[x] != cl) {break;} \
i = x; \
while ((seg[i] == cl) && (i < w)) 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; \
} \
\
subrect.x = Swap16IfLE(thex); \
subrect.y = Swap16IfLE(they); \
subrect.w = Swap16IfLE(thew); \
subrect.h = Swap16IfLE(theh); \
\
newLen = client->afterEncBufLen + (bpp/8) + sz_rfbRectangle; \
if ((newLen > (w * h * (bpp/8))) || (newLen > client->afterEncBufSize)) \
return -1; \
\
numsubs += 1; \
*((uint##bpp##_t*)(client->afterEncBuf + client->afterEncBufLen)) = cl; \
client->afterEncBufLen += (bpp/8); \
memcpy(&client->afterEncBuf[client->afterEncBufLen],&subrect,sz_rfbRectangle); \
client->afterEncBufLen += sz_rfbRectangle; \
\
/* \
* 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; \
} \
} \
} \
} \
} \
\
return numsubs; \
}
DEFINE_SUBRECT_ENCODE(8)
DEFINE_SUBRECT_ENCODE(16)
DEFINE_SUBRECT_ENCODE(32)
/*
* getBgColour() gets the most prevalent colour in a byte array.
*/
static uint32_t
getBgColour(char *data, int size, int bpp)
{
#define NUMCLRS 256
static int counts[NUMCLRS];
int i,j,k;
int maxcount = 0;
uint8_t maxclr = 0;
if (bpp != 8) {
if (bpp == 16) {
return ((uint16_t *)data)[0];
} else if (bpp == 32) {
return ((uint32_t *)data)[0];
} else {
rfbLog("getBgColour: bpp %d?\n",bpp);
return 0;
}
}
for (i=0; i<NUMCLRS; i++) {
counts[i] = 0;
}
for (j=0; j<size; j++) {
k = (int)(((uint8_t *)data)[j]);
if (k >= NUMCLRS) {
rfbErr("getBgColour: unusual colour = %d\n", k);
return 0;
}
counts[k] += 1;
if (counts[k] > maxcount) {
maxcount = counts[k];
maxclr = ((uint8_t *)data)[j];
}
}
return maxclr;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_4063_2 |
crossvul-cpp_data_bad_346_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_346_6 |
crossvul-cpp_data_bad_1611_1 | /* t1asm -*- c-basic-offset: 2 -*-
*
* This program `assembles' Adobe Type-1 font programs in pseudo-PostScript
* form into either PFB or PFA format. The human readable/editable input is
* charstring- and eexec-encrypted as specified in the `Adobe Type 1 Font
* Format' version 1.1 (the `black book'). There is a companion program,
* t1disasm, which `disassembles' PFB and PFA files into a pseudo-PostScript
* file.
*
* Copyright (c) 1992 by I. Lee Hetherington, all rights reserved.
* Copyright (c) 1998-2013 Eddie Kohler
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, subject to the
* conditions listed in the Click LICENSE file, which is available in full at
* http://github.com/kohler/click/blob/master/LICENSE. The conditions
* include: you must preserve this copyright notice, and you cannot mention
* the copyright holders in advertising related to the Software without
* their permission. The Software is provided WITHOUT ANY WARRANTY, EXPRESS
* OR IMPLIED. This notice is a summary of the Click LICENSE file; the
* license in that file is binding.
*
* New change log in `NEWS'. Old change log:
*
* Revision 1.4 92/07/10 10:53:09 ilh
* Added support for additional PostScript after the closefile command
* (ie., some fonts have {restore}if after the cleartomark).
*
* Revision 1.3 92/06/23 10:58:25 ilh
* MSDOS porting by Kai-Uwe Herbing (herbing@netmbx.netmbx.de)
* incoporated.
*
* Revision 1.2 92/05/22 11:54:45 ilh
* Fixed bug where integers larger than 32000 could not be encoded in
* charstrings. Now integer range is correct for four-byte
* twos-complement integers: -(1<<31) <= i <= (1<<31)-1. Bug detected by
* Piet Tutelaers (rcpt@urc.tue.nl).
*
* Revision 1.1 92/05/22 11:48:46 ilh
* initial version
*
* Ported to Microsoft C/C++ Compiler and MS-DOS operating system by
* Kai-Uwe Herbing (herbing@netmbx.netmbx.de) on June 12, 1992. Code
* specific to the MS-DOS version is encapsulated with #ifdef _MSDOS
* ... #endif, where _MSDOS is an identifier, which is automatically
* defined, if you compile with the Microsoft C/C++ Compiler.
*
*/
/* Note: this is ANSI C. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#if defined(_MSDOS) || defined(_WIN32)
# include <fcntl.h>
# include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <stdarg.h>
#include <errno.h>
#include <lcdf/clp.h>
#include "t1lib.h"
#define LINESIZE 512
#ifdef __cplusplus
extern "C" {
#endif
typedef unsigned char byte;
static FILE *ifp;
static FILE *ofp;
static struct pfb_writer w;
static int blocklen = -1;
/* flags */
static int pfb = 1;
static int active = 0;
static int ever_active = 0;
static int start_charstring = 0;
static int in_eexec = 0;
/* need to add 1 as space for \0 */
static char line[LINESIZE + 1];
/* lenIV and charstring start command */
static int lenIV = 4;
static char cs_start[10];
/* for charstring buffering */
static byte *charstring_buf, *charstring_bp;
static int charstring_bufsiz;
/* decryption stuff */
static uint16_t er, cr;
static uint16_t c1 = 52845, c2 = 22719;
/* table of charstring commands */
static struct command {
const char *name;
int one, two;
} command_table[] = {
{ "abs", 12, 9 }, /* Type 2 */
{ "add", 12, 10 }, /* Type 2 */
{ "and", 12, 3 }, /* Type 2 */
{ "blend", 16, -1 }, /* Type 2 */
{ "callgsubr", 29, -1 }, /* Type 2 */
{ "callother", 12, 16 }, /* Type 1 ONLY */
{ "callothersubr", 12, 16 }, /* Type 1 ONLY */
{ "callsubr", 10, -1 },
{ "closepath", 9, -1 }, /* Type 1 ONLY */
{ "cntrmask", 20, -1 }, /* Type 2 */
{ "div", 12, 12 },
{ "dotsection", 12, 0 }, /* Type 1 ONLY */
{ "drop", 12, 18 }, /* Type 2 */
{ "dup", 12, 27 }, /* Type 2 */
{ "endchar", 14, -1 },
{ "eq", 12, 15 }, /* Type 2 */
{ "error", 0, -1 }, /* special */
{ "escape", 12, -1 }, /* special */
{ "exch", 12, 28 }, /* Type 2 */
{ "flex", 12, 35 }, /* Type 2 */
{ "flex1", 12, 37 }, /* Type 2 */
{ "get", 12, 21 }, /* Type 2 */
{ "hflex", 12, 34 }, /* Type 2 */
{ "hflex1", 12, 36 }, /* Type 2 */
{ "hhcurveto", 27, -1 }, /* Type 2 */
{ "hintmask", 19, -1 }, /* Type 2 */
{ "hlineto", 6, -1 },
{ "hmoveto", 22, -1 },
{ "hsbw", 13, -1 }, /* Type 1 ONLY */
{ "hstem", 1, -1 },
{ "hstem3", 12, 2 }, /* Type 1 ONLY */
{ "hstemhm", 18, -1 }, /* Type 2 */
{ "hvcurveto", 31, -1 },
{ "ifelse", 12, 22 }, /* Type 2 */
{ "index", 12, 29 }, /* Type 2 */
{ "load", 12, 13 }, /* Type 2 */
{ "mul", 12, 24 }, /* Type 2 */
{ "neg", 12, 14 }, /* Type 2 */
{ "not", 12, 5 }, /* Type 2 */
{ "or", 12, 4 }, /* Type 2 */
{ "pop", 12, 17 }, /* Type 1 ONLY */
{ "put", 12, 20 }, /* Type 2 */
{ "random", 12, 23 }, /* Type 2 */
{ "rcurveline", 24, -1 }, /* Type 2 */
{ "return", 11, -1 },
{ "rlinecurve", 25, -1 }, /* Type 2 */
{ "rlineto", 5, -1 },
{ "rmoveto", 21, -1 },
{ "roll", 12, 30 }, /* Type 2 */
{ "rrcurveto", 8, -1 },
{ "sbw", 12, 7 }, /* Type 1 ONLY */
{ "seac", 12, 6 }, /* Type 1 ONLY */
{ "setcurrentpoint", 12, 33 }, /* Type 1 ONLY */
{ "sqrt", 12, 26 }, /* Type 2 */
{ "store", 12, 8 }, /* Type 2 */
{ "sub", 12, 11 }, /* Type 2 */
{ "vhcurveto", 30, -1 },
{ "vlineto", 7, -1 },
{ "vmoveto", 4, -1 },
{ "vstem", 3, -1 },
{ "vstem3", 12, 1 }, /* Type 1 ONLY */
{ "vstemhm", 23, -1 }, /* Type 2 */
{ "vvcurveto", 26, -1 }, /* Type 2 */
}; /* alphabetical */
/* Two separate encryption functions because eexec and charstring encryption
must proceed in parallel. */
static byte eencrypt(byte plain)
{
byte cipher;
cipher = (byte)(plain ^ (er >> 8));
er = (uint16_t)((cipher + er) * c1 + c2);
return cipher;
}
static byte cencrypt(byte plain)
{
byte cipher;
/* Thanks to Tom Kacvinsky <tjk@ams.org> who reported that lenIV == -1 means
unencrypted charstrings. */
if (lenIV < 0) return plain;
cipher = (byte)(plain ^ (cr >> 8));
cr = (uint16_t)((cipher + cr) * c1 + c2);
return cipher;
}
/* This function outputs a single byte. If output is in PFB format then output
is buffered through blockbuf[]. If output is in PFA format, then output
will be hexadecimal if in_eexec is set, ASCII otherwise. */
static void output_byte(byte b)
{
static const char *hexchar = "0123456789abcdef";
static int hexcol = 0;
if (pfb) {
/* PFB */
PFB_OUTPUT_BYTE(&w, b);
} else {
/* PFA */
if (in_eexec) {
/* trim hexadecimal lines to `blocklen' columns */
if (hexcol >= blocklen) {
putc('\n', ofp);
hexcol = 0;
}
putc(hexchar[(b >> 4) & 0xf], ofp);
putc(hexchar[b & 0xf], ofp);
hexcol += 2;
} else {
putc(b, ofp);
}
}
}
/* This function outputs a byte through possible eexec encryption. */
static void eexec_byte(byte b)
{
if (in_eexec)
output_byte(eencrypt(b));
else
output_byte(b);
}
/* This function outputs a null-terminated string through possible eexec
encryption. */
static void eexec_string(const char *string)
{
while (*string)
eexec_byte(*string++);
}
/* This function gets ready for the eexec-encrypted data. If output is in
PFB format then flush current ASCII block and get ready for binary block.
We start encryption with four random (zero) bytes. */
static void eexec_start(char *string)
{
eexec_string("currentfile eexec\n");
if (pfb && w.blocktyp != PFB_BINARY) {
pfb_writer_output_block(&w);
w.blocktyp = PFB_BINARY;
}
in_eexec = 1;
er = 55665;
eexec_byte(0);
eexec_byte(0);
eexec_byte(0);
eexec_byte(0);
eexec_string(string);
}
/* 25.Aug.1999 -- Return 1 if this line actually looks like the start of a
charstring. We use the heuristic that it should start with `/' (a name) or
`dup' (a subroutine). Previous heuristic caused killa bad output. */
static int check_line_charstring(void)
{
char *p = line;
while (isspace(*p))
p++;
return (*p == '/' || (p[0] == 'd' && p[1] == 'u' && p[2] == 'p'));
}
/* This function returns an input line of characters. A line is terminated by
length (including terminating null) greater than LINESIZE, \r, \n, \r\n, or
when active (looking for charstrings) by '{'. When terminated by a newline
the newline is put into line[]. When terminated by '{', the '{' is not put
into line[], and the flag start_charstring is set to 1. */
static void t1utils_getline(void)
{
int c;
char *p = line;
int comment = 0;
start_charstring = 0;
while (p < line + LINESIZE) {
c = getc(ifp);
if (c == EOF)
break;
else if (c == '%')
comment = 1;
else if (active && !comment && c == '{') {
/* 25.Aug.1999 -- new check for whether we should stop be active */
if (check_line_charstring()) {
start_charstring = 1;
break;
} else
active = 0;
}
*p++ = (char) c;
/* end of line processing: change CR or CRLF into LF, and exit */
if (c == '\r') {
c = getc(ifp);
if (c != '\n')
ungetc(c, ifp);
p[-1] = '\n';
break;
} else if (c == '\n')
break;
}
*p = '\0';
}
/* This function wraps-up the eexec-encrypted data and writes ASCII trailer.
If output is in PFB format then this entails flushing binary block and
starting an ASCII block. */
static void eexec_end(void)
{
int i, j;
if (!pfb)
putc('\n', ofp);
else if (w.blocktyp != PFB_ASCII) {
pfb_writer_output_block(&w);
w.blocktyp = PFB_ASCII;
}
in_eexec = active = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 64; j++)
eexec_byte('0');
eexec_byte('\n');
}
}
/* This function is used by the binary search, bsearch(), for command names in
the command table. */
static int CDECL command_compare(const void *key, const void *item)
{
return strcmp((const char *) key, ((const struct command *) item)->name);
}
/* This function returns 1 if the string is an integer and 0 otherwise. */
static int is_integer(char *string)
{
if (isdigit(string[0]) || string[0] == '-' || string[0] == '+') {
while (*++string && isdigit(*string))
; /* deliberately empty */
if (!*string)
return 1;
}
return 0;
}
/* This function initializes charstring encryption. Note that this is called
at the beginning of every charstring. */
static void charstring_start(void)
{
int i;
if (!charstring_buf) {
charstring_bufsiz = 65536;
if (!(charstring_buf = (byte *) malloc(charstring_bufsiz)))
fatal_error("out of memory");
}
charstring_bp = charstring_buf;
cr = 4330;
for (i = 0; i < lenIV; i++)
*charstring_bp++ = cencrypt((byte) 0);
}
/* This function encrypts and buffers a single byte of charstring data. */
static void charstring_byte(int v)
{
byte b = (byte)(v & 0xff);
if (charstring_bp - charstring_buf == charstring_bufsiz) {
charstring_bufsiz *= 2;
if (!(charstring_buf = (byte *) realloc(charstring_buf, charstring_bufsiz)))
fatal_error("out of memory");
charstring_bp = charstring_buf + charstring_bufsiz / 2;
}
*charstring_bp++ = cencrypt(b);
}
/* This function outputs buffered, encrypted charstring data through possible
eexec encryption. */
static void charstring_end(void)
{
byte *bp;
sprintf(line, "%d ", (int) (charstring_bp - charstring_buf));
eexec_string(line);
sprintf(line, "%s ", cs_start);
eexec_string(line);
for (bp = charstring_buf; bp < charstring_bp; bp++)
eexec_byte(*bp);
}
/* This function generates the charstring representation of an integer. */
static void charstring_int(int num)
{
int x;
if (num >= -107 && num <= 107) {
charstring_byte(num + 139);
} else if (num >= 108 && num <= 1131) {
x = num - 108;
charstring_byte(x / 256 + 247);
charstring_byte(x % 256);
} else if (num >= -1131 && num <= -108) {
x = abs(num) - 108;
charstring_byte(x / 256 + 251);
charstring_byte(x % 256);
} else if (num >= (-2147483647-1) && num <= 2147483647) {
charstring_byte(255);
charstring_byte(num >> 24);
charstring_byte(num >> 16);
charstring_byte(num >> 8);
charstring_byte(num);
} else {
error("can't format huge number `%d'", num);
/* output 0 instead */
charstring_byte(139);
}
}
/* This function returns one charstring token. It ignores comments. */
static void get_charstring_token(void)
{
int c = getc(ifp);
while (isspace(c))
c = getc(ifp);
if (c == '%') {
while (c != EOF && c != '\r' && c != '\n')
c = getc(ifp);
get_charstring_token();
} else if (c == '}') {
line[0] = '}';
line[1] = 0;
} else {
char *p = line;
while (p < line + LINESIZE) {
*p++ = c;
c = getc(ifp);
if (c == EOF || isspace(c) || c == '%' || c == '}') {
ungetc(c, ifp);
break;
}
}
*p = 0;
}
}
/* This function parses an entire charstring into integers and commands,
outputting bytes through the charstring buffer. */
static void parse_charstring(void)
{
struct command *cp;
charstring_start();
while (!feof(ifp)) {
get_charstring_token();
if (line[0] == '}')
break;
if (is_integer(line)) {
charstring_int(atoi(line));
} else {
int one;
int two;
int ok = 0;
cp = (struct command *)
bsearch((void *) line, (void *) command_table,
sizeof(command_table) / sizeof(struct command),
sizeof(struct command),
command_compare);
if (cp) {
one = cp->one;
two = cp->two;
ok = 1;
} else if (strncmp(line, "escape_", 7) == 0) {
/* Parse the `escape' keyword requested by Lee Chun-Yu and Werner
Lemberg */
one = 12;
if (sscanf(line + 7, "%d", &two) == 1)
ok = 1;
} else if (strncmp(line, "UNKNOWN_", 8) == 0) {
/* Allow unanticipated UNKNOWN commands. */
one = 12;
if (sscanf(line + 8, "12_%d", &two) == 1)
ok = 1;
else if (sscanf(line + 8, "%d", &one) == 1) {
two = -1;
ok = 1;
}
}
if (!ok)
error("unknown charstring command `%s'", line);
else if (one < 0 || one > 255)
error("bad charstring command number `%d'", one);
else if (two > 255)
error("bad charstring command number `%d'", two);
else if (two < 0)
charstring_byte(one);
else {
charstring_byte(one);
charstring_byte(two);
}
}
}
charstring_end();
}
/*****
* Command line
**/
#define BLOCK_LEN_OPT 300
#define OUTPUT_OPT 301
#define VERSION_OPT 302
#define HELP_OPT 303
#define PFB_OPT 304
#define PFA_OPT 305
static Clp_Option options[] = {
{ "block-length", 'l', BLOCK_LEN_OPT, Clp_ValInt, 0 },
{ "help", 0, HELP_OPT, 0, 0 },
{ "line-length", 0, BLOCK_LEN_OPT, Clp_ValInt, 0 },
{ "output", 'o', OUTPUT_OPT, Clp_ValString, 0 },
{ "pfa", 'a', PFA_OPT, 0, 0 },
{ "pfb", 'b', PFB_OPT, 0, 0 },
{ "version", 0, VERSION_OPT, 0, 0 },
};
static const char *program_name;
void
fatal_error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
putc('\n', stderr);
va_end(val);
exit(1);
}
void
error(const char *message, ...)
{
va_list val;
va_start(val, message);
fprintf(stderr, "%s: ", program_name);
vfprintf(stderr, message, val);
putc('\n', stderr);
va_end(val);
}
static void
short_usage(void)
{
fprintf(stderr, "Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\
Try `%s --help' for more information.\n",
program_name, program_name);
}
static void
usage(void)
{
printf("\
`T1asm' translates a human-readable version of a PostScript Type 1 font into\n\
standard PFB or PFA format. The result is written to the standard output\n\
unless an OUTPUT file is given.\n\
\n\
Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\
\n\
Options:\n\
-a, --pfa Output font in ASCII (PFA) format.\n\
-b, --pfb Output font in binary (PFB) format. This is\n\
the default.\n\
-l, --block-length NUM Set max block length for PFB output.\n\
-l, --line-length NUM Set max encrypted line length for PFA output.\n\
-o, --output=FILE Write output to FILE.\n\
-h, --help Print this message and exit.\n\
--version Print version number and warranty and exit.\n\
\n\
Report bugs to <ekohler@gmail.com>.\n", program_name);
}
#ifdef __cplusplus
}
#endif
int main(int argc, char *argv[])
{
char *p, *q, *r;
Clp_Parser *clp =
Clp_NewParser(argc, (const char * const *)argv, sizeof(options) / sizeof(options[0]), options);
program_name = Clp_ProgramName(clp);
/* interpret command line arguments using CLP */
while (1) {
int opt = Clp_Next(clp);
switch (opt) {
case BLOCK_LEN_OPT:
blocklen = clp->val.i;
break;
output_file:
case OUTPUT_OPT:
if (ofp)
fatal_error("output file already specified");
if (strcmp(clp->vstr, "-") == 0)
ofp = stdout;
else if (!(ofp = fopen(clp->vstr, "w")))
fatal_error("%s: %s", clp->vstr, strerror(errno));
break;
case PFB_OPT:
pfb = 1;
break;
case PFA_OPT:
pfb = 0;
break;
case HELP_OPT:
usage();
exit(0);
break;
case VERSION_OPT:
printf("t1asm (LCDF t1utils) %s\n", VERSION);
printf("Copyright (C) 1992-2010 I. Lee Hetherington, Eddie Kohler et al.\n\
This is free software; see the source for copying conditions.\n\
There is NO warranty, not even for merchantability or fitness for a\n\
particular purpose.\n");
exit(0);
break;
case Clp_NotOption:
if (ifp && ofp)
fatal_error("too many arguments");
else if (ifp)
goto output_file;
if (strcmp(clp->vstr, "-") == 0)
ifp = stdin;
else if (!(ifp = fopen(clp->vstr, "r")))
fatal_error("%s: %s", clp->vstr, strerror(errno));
break;
case Clp_Done:
goto done;
case Clp_BadOption:
short_usage();
exit(1);
break;
}
}
done:
if (!pfb) {
if (blocklen == -1)
blocklen = 64;
else if (blocklen < 8) {
blocklen = 8;
error("warning: line length raised to %d", blocklen);
} else if (blocklen > 1024) {
blocklen = 1024;
error("warning: line length lowered to %d", blocklen);
}
}
if (!ifp) ifp = stdin;
if (!ofp) ofp = stdout;
if (pfb)
init_pfb_writer(&w, blocklen, ofp);
#if defined(_MSDOS) || defined(_WIN32)
/* If we are processing a PFB (binary) output */
/* file, we must set its file mode to binary. */
if (pfb)
_setmode(_fileno(ofp), _O_BINARY);
#endif
/* Finally, we loop until no more input. Some special things to look for are
the `currentfile eexec' line, the beginning of the `/Subrs' or
`/CharStrings' definition, the definition of `/lenIV', and the definition
of the charstring start command which has `...string currentfile...' in
it.
Being careful: Check with `/Subrs' and `/CharStrings' to see that a
number follows the token -- otherwise, the token is probably nested in a
subroutine a la Adobe Jenson, and we shouldn't pay attention to it.
Bugs: Occurrence of `/Subrs 9' in a comment will fool t1asm.
Thanks to Tom Kacvinsky <tjk@ams.org> who reported that some fonts come
without /Subrs sections and provided a patch. */
while (!feof(ifp) && !ferror(ifp)) {
t1utils_getline();
if (!ever_active) {
if (strncmp(line, "currentfile eexec", 17) == 0 && isspace(line[17])) {
/* Allow arbitrary whitespace after "currentfile eexec".
Thanks to Tom Kacvinsky <tjk@ams.org> for reporting this.
Note: strlen("currentfile eexec") == 17. */
for (p = line + 18; isspace(*p); p++)
;
eexec_start(p);
continue;
} else if (strncmp(line, "/lenIV", 6) == 0) {
lenIV = atoi(line + 6);
} else if ((p = strstr(line, "string currentfile"))
&& strstr(line, "readstring")) { /* enforce `readstring' */
/* locate the name of the charstring start command */
*p = '\0'; /* damage line[] */
q = strrchr(line, '/');
if (q) {
r = cs_start;
++q;
while (!isspace(*q) && *q != '{')
*r++ = *q++;
*r = '\0';
}
*p = 's'; /* repair line[] */
}
}
if (!active) {
if ((p = strstr(line, "/Subrs")) && isdigit(p[7]))
ever_active = active = 1;
else if ((p = strstr(line, "/CharStrings")) && isdigit(p[13]))
ever_active = active = 1;
}
if ((p = strstr(line, "currentfile closefile"))) {
/* 2/14/99 -- happy Valentine's day! -- don't look for `mark
currentfile closefile'; the `mark' might be on a different line */
/* 1/3/2002 -- happy new year! -- Luc Devroye reports a failure with
some printers when `currentfile closefile' is followed by space */
p += sizeof("currentfile closefile") - 1;
for (q = p; isspace(*q) && *q != '\n'; q++)
/* nada */;
if (q == p && !*q)
error("warning: `currentfile closefile' line too long");
else if (q != p) {
if (*q != '\n')
error("text after `currentfile closefile' ignored");
*p++ = '\n';
*p++ = '\0';
}
eexec_string(line);
break;
}
eexec_string(line);
/* output line data */
if (start_charstring) {
if (!cs_start[0])
fatal_error("couldn't find charstring start command");
parse_charstring();
}
}
/* Handle remaining PostScript after the eexec section */
if (in_eexec)
eexec_end();
/* There may be additional code. */
while (!feof(ifp) && !ferror(ifp)) {
t1utils_getline();
eexec_string(line);
}
if (pfb)
pfb_writer_end(&w);
/* the end! */
if (!ever_active)
error("warning: no charstrings found in input file");
fclose(ifp);
fclose(ofp);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_1611_1 |
crossvul-cpp_data_good_5675_0 | /*******************************************************************************
* This file contains main functions related to iSCSI Parameter negotiation.
*
* \u00a9 Copyright 2007-2011 RisingTide Systems LLC.
*
* Licensed to the Linux Foundation under the General Public License (GPL) version 2.
*
* Author: Nicholas A. Bellinger <nab@linux-iscsi.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
******************************************************************************/
#include <linux/slab.h>
#include "iscsi_target_core.h"
#include "iscsi_target_util.h"
#include "iscsi_target_parameters.h"
int iscsi_login_rx_data(
struct iscsi_conn *conn,
char *buf,
int length)
{
int rx_got;
struct kvec iov;
memset(&iov, 0, sizeof(struct kvec));
iov.iov_len = length;
iov.iov_base = buf;
/*
* Initial Marker-less Interval.
* Add the values regardless of IFMarker/OFMarker, considering
* it may not be negoitated yet.
*/
conn->of_marker += length;
rx_got = rx_data(conn, &iov, 1, length);
if (rx_got != length) {
pr_err("rx_data returned %d, expecting %d.\n",
rx_got, length);
return -1;
}
return 0 ;
}
int iscsi_login_tx_data(
struct iscsi_conn *conn,
char *pdu_buf,
char *text_buf,
int text_length)
{
int length, tx_sent, iov_cnt = 1;
struct kvec iov[2];
length = (ISCSI_HDR_LEN + text_length);
memset(&iov[0], 0, 2 * sizeof(struct kvec));
iov[0].iov_len = ISCSI_HDR_LEN;
iov[0].iov_base = pdu_buf;
if (text_buf && text_length) {
iov[1].iov_len = text_length;
iov[1].iov_base = text_buf;
iov_cnt++;
}
/*
* Initial Marker-less Interval.
* Add the values regardless of IFMarker/OFMarker, considering
* it may not be negoitated yet.
*/
conn->if_marker += length;
tx_sent = tx_data(conn, &iov[0], iov_cnt, length);
if (tx_sent != length) {
pr_err("tx_data returned %d, expecting %d.\n",
tx_sent, length);
return -1;
}
return 0;
}
void iscsi_dump_conn_ops(struct iscsi_conn_ops *conn_ops)
{
pr_debug("HeaderDigest: %s\n", (conn_ops->HeaderDigest) ?
"CRC32C" : "None");
pr_debug("DataDigest: %s\n", (conn_ops->DataDigest) ?
"CRC32C" : "None");
pr_debug("MaxRecvDataSegmentLength: %u\n",
conn_ops->MaxRecvDataSegmentLength);
pr_debug("OFMarker: %s\n", (conn_ops->OFMarker) ? "Yes" : "No");
pr_debug("IFMarker: %s\n", (conn_ops->IFMarker) ? "Yes" : "No");
if (conn_ops->OFMarker)
pr_debug("OFMarkInt: %u\n", conn_ops->OFMarkInt);
if (conn_ops->IFMarker)
pr_debug("IFMarkInt: %u\n", conn_ops->IFMarkInt);
}
void iscsi_dump_sess_ops(struct iscsi_sess_ops *sess_ops)
{
pr_debug("InitiatorName: %s\n", sess_ops->InitiatorName);
pr_debug("InitiatorAlias: %s\n", sess_ops->InitiatorAlias);
pr_debug("TargetName: %s\n", sess_ops->TargetName);
pr_debug("TargetAlias: %s\n", sess_ops->TargetAlias);
pr_debug("TargetPortalGroupTag: %hu\n",
sess_ops->TargetPortalGroupTag);
pr_debug("MaxConnections: %hu\n", sess_ops->MaxConnections);
pr_debug("InitialR2T: %s\n",
(sess_ops->InitialR2T) ? "Yes" : "No");
pr_debug("ImmediateData: %s\n", (sess_ops->ImmediateData) ?
"Yes" : "No");
pr_debug("MaxBurstLength: %u\n", sess_ops->MaxBurstLength);
pr_debug("FirstBurstLength: %u\n", sess_ops->FirstBurstLength);
pr_debug("DefaultTime2Wait: %hu\n", sess_ops->DefaultTime2Wait);
pr_debug("DefaultTime2Retain: %hu\n",
sess_ops->DefaultTime2Retain);
pr_debug("MaxOutstandingR2T: %hu\n",
sess_ops->MaxOutstandingR2T);
pr_debug("DataPDUInOrder: %s\n",
(sess_ops->DataPDUInOrder) ? "Yes" : "No");
pr_debug("DataSequenceInOrder: %s\n",
(sess_ops->DataSequenceInOrder) ? "Yes" : "No");
pr_debug("ErrorRecoveryLevel: %hu\n",
sess_ops->ErrorRecoveryLevel);
pr_debug("SessionType: %s\n", (sess_ops->SessionType) ?
"Discovery" : "Normal");
}
void iscsi_print_params(struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list)
pr_debug("%s: %s\n", param->name, param->value);
}
static struct iscsi_param *iscsi_set_default_param(struct iscsi_param_list *param_list,
char *name, char *value, u8 phase, u8 scope, u8 sender,
u16 type_range, u8 use)
{
struct iscsi_param *param = NULL;
param = kzalloc(sizeof(struct iscsi_param), GFP_KERNEL);
if (!param) {
pr_err("Unable to allocate memory for parameter.\n");
goto out;
}
INIT_LIST_HEAD(¶m->p_list);
param->name = kstrdup(name, GFP_KERNEL);
if (!param->name) {
pr_err("Unable to allocate memory for parameter name.\n");
goto out;
}
param->value = kstrdup(value, GFP_KERNEL);
if (!param->value) {
pr_err("Unable to allocate memory for parameter value.\n");
goto out;
}
param->phase = phase;
param->scope = scope;
param->sender = sender;
param->use = use;
param->type_range = type_range;
switch (param->type_range) {
case TYPERANGE_BOOL_AND:
param->type = TYPE_BOOL_AND;
break;
case TYPERANGE_BOOL_OR:
param->type = TYPE_BOOL_OR;
break;
case TYPERANGE_0_TO_2:
case TYPERANGE_0_TO_3600:
case TYPERANGE_0_TO_32767:
case TYPERANGE_0_TO_65535:
case TYPERANGE_1_TO_65535:
case TYPERANGE_2_TO_3600:
case TYPERANGE_512_TO_16777215:
param->type = TYPE_NUMBER;
break;
case TYPERANGE_AUTH:
case TYPERANGE_DIGEST:
param->type = TYPE_VALUE_LIST | TYPE_STRING;
break;
case TYPERANGE_MARKINT:
param->type = TYPE_NUMBER_RANGE;
param->type_range |= TYPERANGE_1_TO_65535;
break;
case TYPERANGE_ISCSINAME:
case TYPERANGE_SESSIONTYPE:
case TYPERANGE_TARGETADDRESS:
case TYPERANGE_UTF8:
param->type = TYPE_STRING;
break;
default:
pr_err("Unknown type_range 0x%02x\n",
param->type_range);
goto out;
}
list_add_tail(¶m->p_list, ¶m_list->param_list);
return param;
out:
if (param) {
kfree(param->value);
kfree(param->name);
kfree(param);
}
return NULL;
}
/* #warning Add extension keys */
int iscsi_create_default_params(struct iscsi_param_list **param_list_ptr)
{
struct iscsi_param *param = NULL;
struct iscsi_param_list *pl;
pl = kzalloc(sizeof(struct iscsi_param_list), GFP_KERNEL);
if (!pl) {
pr_err("Unable to allocate memory for"
" struct iscsi_param_list.\n");
return -1 ;
}
INIT_LIST_HEAD(&pl->param_list);
INIT_LIST_HEAD(&pl->extra_response_list);
/*
* The format for setting the initial parameter definitions are:
*
* Parameter name:
* Initial value:
* Allowable phase:
* Scope:
* Allowable senders:
* Typerange:
* Use:
*/
param = iscsi_set_default_param(pl, AUTHMETHOD, INITIAL_AUTHMETHOD,
PHASE_SECURITY, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_AUTH, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, HEADERDIGEST, INITIAL_HEADERDIGEST,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_DIGEST, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATADIGEST, INITIAL_DATADIGEST,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_DIGEST, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXCONNECTIONS,
INITIAL_MAXCONNECTIONS, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_1_TO_65535, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, SENDTARGETS, INITIAL_SENDTARGETS,
PHASE_FFP0, SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_UTF8, 0);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETNAME, INITIAL_TARGETNAME,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_ISCSINAME, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIATORNAME,
INITIAL_INITIATORNAME, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_ISCSINAME, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETALIAS, INITIAL_TARGETALIAS,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_UTF8, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIATORALIAS,
INITIAL_INITIATORALIAS, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_INITIATOR, TYPERANGE_UTF8,
USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETADDRESS,
INITIAL_TARGETADDRESS, PHASE_DECLARATIVE,
SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_TARGETADDRESS, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETPORTALGROUPTAG,
INITIAL_TARGETPORTALGROUPTAG,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_TARGET,
TYPERANGE_0_TO_65535, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIALR2T, INITIAL_INITIALR2T,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_BOOL_OR, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IMMEDIATEDATA,
INITIAL_IMMEDIATEDATA, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_AND,
USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXXMITDATASEGMENTLENGTH,
INITIAL_MAXXMITDATASEGMENTLENGTH,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXRECVDATASEGMENTLENGTH,
INITIAL_MAXRECVDATASEGMENTLENGTH,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXBURSTLENGTH,
INITIAL_MAXBURSTLENGTH, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, FIRSTBURSTLENGTH,
INITIAL_FIRSTBURSTLENGTH,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DEFAULTTIME2WAIT,
INITIAL_DEFAULTTIME2WAIT,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_3600, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DEFAULTTIME2RETAIN,
INITIAL_DEFAULTTIME2RETAIN,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_3600, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, MAXOUTSTANDINGR2T,
INITIAL_MAXOUTSTANDINGR2T,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_1_TO_65535, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATAPDUINORDER,
INITIAL_DATAPDUINORDER, PHASE_OPERATIONAL,
SCOPE_SESSION_WIDE, SENDER_BOTH, TYPERANGE_BOOL_OR,
USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, DATASEQUENCEINORDER,
INITIAL_DATASEQUENCEINORDER,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_BOOL_OR, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, ERRORRECOVERYLEVEL,
INITIAL_ERRORRECOVERYLEVEL,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_0_TO_2, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, SESSIONTYPE, INITIAL_SESSIONTYPE,
PHASE_DECLARATIVE, SCOPE_SESSION_WIDE, SENDER_INITIATOR,
TYPERANGE_SESSIONTYPE, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IFMARKER, INITIAL_IFMARKER,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_BOOL_AND, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, OFMARKER, INITIAL_OFMARKER,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_BOOL_AND, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, IFMARKINT, INITIAL_IFMARKINT,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_MARKINT, USE_INITIAL_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, OFMARKINT, INITIAL_OFMARKINT,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_MARKINT, USE_INITIAL_ONLY);
if (!param)
goto out;
/*
* Extra parameters for ISER from RFC-5046
*/
param = iscsi_set_default_param(pl, RDMAEXTENSIONS, INITIAL_RDMAEXTENSIONS,
PHASE_OPERATIONAL, SCOPE_SESSION_WIDE, SENDER_BOTH,
TYPERANGE_BOOL_AND, USE_LEADING_ONLY);
if (!param)
goto out;
param = iscsi_set_default_param(pl, INITIATORRECVDATASEGMENTLENGTH,
INITIAL_INITIATORRECVDATASEGMENTLENGTH,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_ALL);
if (!param)
goto out;
param = iscsi_set_default_param(pl, TARGETRECVDATASEGMENTLENGTH,
INITIAL_TARGETRECVDATASEGMENTLENGTH,
PHASE_OPERATIONAL, SCOPE_CONNECTION_ONLY, SENDER_BOTH,
TYPERANGE_512_TO_16777215, USE_ALL);
if (!param)
goto out;
*param_list_ptr = pl;
return 0;
out:
iscsi_release_param_list(pl);
return -1;
}
int iscsi_set_keys_to_negotiate(
struct iscsi_param_list *param_list,
bool iser)
{
struct iscsi_param *param;
param_list->iser = iser;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
param->state = 0;
if (!strcmp(param->name, AUTHMETHOD)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, HEADERDIGEST)) {
if (iser == false)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATADIGEST)) {
if (iser == false)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXCONNECTIONS)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, TARGETNAME)) {
continue;
} else if (!strcmp(param->name, INITIATORNAME)) {
continue;
} else if (!strcmp(param->name, TARGETALIAS)) {
if (param->value)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, INITIATORALIAS)) {
continue;
} else if (!strcmp(param->name, TARGETPORTALGROUPTAG)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, INITIALR2T)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IMMEDIATEDATA)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) {
if (iser == false)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXXMITDATASEGMENTLENGTH)) {
continue;
} else if (!strcmp(param->name, MAXBURSTLENGTH)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DEFAULTTIME2RETAIN)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, MAXOUTSTANDINGR2T)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATAPDUINORDER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, DATASEQUENCEINORDER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, ERRORRECOVERYLEVEL)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, SESSIONTYPE)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IFMARKER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, OFMARKER)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, IFMARKINT)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, OFMARKINT)) {
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, RDMAEXTENSIONS)) {
if (iser == true)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, INITIATORRECVDATASEGMENTLENGTH)) {
if (iser == true)
SET_PSTATE_NEGOTIATE(param);
} else if (!strcmp(param->name, TARGETRECVDATASEGMENTLENGTH)) {
if (iser == true)
SET_PSTATE_NEGOTIATE(param);
}
}
return 0;
}
int iscsi_set_keys_irrelevant_for_discovery(
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!strcmp(param->name, MAXCONNECTIONS))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, INITIALR2T))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IMMEDIATEDATA))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, MAXBURSTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, FIRSTBURSTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, MAXOUTSTANDINGR2T))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DATAPDUINORDER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DATASEQUENCEINORDER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, ERRORRECOVERYLEVEL))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DEFAULTTIME2WAIT))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, DEFAULTTIME2RETAIN))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IFMARKER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, OFMARKER))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, IFMARKINT))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, OFMARKINT))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, RDMAEXTENSIONS))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, INITIATORRECVDATASEGMENTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
else if (!strcmp(param->name, TARGETRECVDATASEGMENTLENGTH))
param->state &= ~PSTATE_NEGOTIATE;
}
return 0;
}
int iscsi_copy_param_list(
struct iscsi_param_list **dst_param_list,
struct iscsi_param_list *src_param_list,
int leading)
{
struct iscsi_param *param = NULL;
struct iscsi_param *new_param = NULL;
struct iscsi_param_list *param_list = NULL;
param_list = kzalloc(sizeof(struct iscsi_param_list), GFP_KERNEL);
if (!param_list) {
pr_err("Unable to allocate memory for struct iscsi_param_list.\n");
goto err_out;
}
INIT_LIST_HEAD(¶m_list->param_list);
INIT_LIST_HEAD(¶m_list->extra_response_list);
list_for_each_entry(param, &src_param_list->param_list, p_list) {
if (!leading && (param->scope & SCOPE_SESSION_WIDE)) {
if ((strcmp(param->name, "TargetName") != 0) &&
(strcmp(param->name, "InitiatorName") != 0) &&
(strcmp(param->name, "TargetPortalGroupTag") != 0))
continue;
}
new_param = kzalloc(sizeof(struct iscsi_param), GFP_KERNEL);
if (!new_param) {
pr_err("Unable to allocate memory for struct iscsi_param.\n");
goto err_out;
}
new_param->name = kstrdup(param->name, GFP_KERNEL);
new_param->value = kstrdup(param->value, GFP_KERNEL);
if (!new_param->value || !new_param->name) {
kfree(new_param->value);
kfree(new_param->name);
kfree(new_param);
pr_err("Unable to allocate memory for parameter name/value.\n");
goto err_out;
}
new_param->set_param = param->set_param;
new_param->phase = param->phase;
new_param->scope = param->scope;
new_param->sender = param->sender;
new_param->type = param->type;
new_param->use = param->use;
new_param->type_range = param->type_range;
list_add_tail(&new_param->p_list, ¶m_list->param_list);
}
if (!list_empty(¶m_list->param_list)) {
*dst_param_list = param_list;
} else {
pr_err("No parameters allocated.\n");
goto err_out;
}
return 0;
err_out:
iscsi_release_param_list(param_list);
return -1;
}
static void iscsi_release_extra_responses(struct iscsi_param_list *param_list)
{
struct iscsi_extra_response *er, *er_tmp;
list_for_each_entry_safe(er, er_tmp, ¶m_list->extra_response_list,
er_list) {
list_del(&er->er_list);
kfree(er);
}
}
void iscsi_release_param_list(struct iscsi_param_list *param_list)
{
struct iscsi_param *param, *param_tmp;
list_for_each_entry_safe(param, param_tmp, ¶m_list->param_list,
p_list) {
list_del(¶m->p_list);
kfree(param->name);
kfree(param->value);
kfree(param);
}
iscsi_release_extra_responses(param_list);
kfree(param_list);
}
struct iscsi_param *iscsi_find_param_from_key(
char *key,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
if (!key || !param_list) {
pr_err("Key or parameter list pointer is NULL.\n");
return NULL;
}
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!strcmp(key, param->name))
return param;
}
pr_err("Unable to locate key \"%s\".\n", key);
return NULL;
}
int iscsi_extract_key_value(char *textbuf, char **key, char **value)
{
*value = strchr(textbuf, '=');
if (!*value) {
pr_err("Unable to locate \"=\" separator for key,"
" ignoring request.\n");
return -1;
}
*key = textbuf;
**value = '\0';
*value = *value + 1;
return 0;
}
int iscsi_update_param_value(struct iscsi_param *param, char *value)
{
kfree(param->value);
param->value = kstrdup(value, GFP_KERNEL);
if (!param->value) {
pr_err("Unable to allocate memory for value.\n");
return -ENOMEM;
}
pr_debug("iSCSI Parameter updated to %s=%s\n",
param->name, param->value);
return 0;
}
static int iscsi_add_notunderstood_response(
char *key,
char *value,
struct iscsi_param_list *param_list)
{
struct iscsi_extra_response *extra_response;
if (strlen(value) > VALUE_MAXLEN) {
pr_err("Value for notunderstood key \"%s\" exceeds %d,"
" protocol error.\n", key, VALUE_MAXLEN);
return -1;
}
extra_response = kzalloc(sizeof(struct iscsi_extra_response), GFP_KERNEL);
if (!extra_response) {
pr_err("Unable to allocate memory for"
" struct iscsi_extra_response.\n");
return -1;
}
INIT_LIST_HEAD(&extra_response->er_list);
strlcpy(extra_response->key, key, sizeof(extra_response->key));
strlcpy(extra_response->value, NOTUNDERSTOOD,
sizeof(extra_response->value));
list_add_tail(&extra_response->er_list,
¶m_list->extra_response_list);
return 0;
}
static int iscsi_check_for_auth_key(char *key)
{
/*
* RFC 1994
*/
if (!strcmp(key, "CHAP_A") || !strcmp(key, "CHAP_I") ||
!strcmp(key, "CHAP_C") || !strcmp(key, "CHAP_N") ||
!strcmp(key, "CHAP_R"))
return 1;
/*
* RFC 2945
*/
if (!strcmp(key, "SRP_U") || !strcmp(key, "SRP_N") ||
!strcmp(key, "SRP_g") || !strcmp(key, "SRP_s") ||
!strcmp(key, "SRP_A") || !strcmp(key, "SRP_B") ||
!strcmp(key, "SRP_M") || !strcmp(key, "SRP_HM"))
return 1;
return 0;
}
static void iscsi_check_proposer_for_optional_reply(struct iscsi_param *param)
{
if (IS_TYPE_BOOL_AND(param)) {
if (!strcmp(param->value, NO))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_TYPE_BOOL_OR(param)) {
if (!strcmp(param->value, YES))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* Required for gPXE iSCSI boot client
*/
if (!strcmp(param->name, IMMEDIATEDATA))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_TYPE_NUMBER(param)) {
if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* The GlobalSAN iSCSI Initiator for MacOSX does
* not respond to MaxBurstLength, FirstBurstLength,
* DefaultTime2Wait or DefaultTime2Retain parameter keys.
* So, we set them to 'reply optional' here, and assume the
* the defaults from iscsi_parameters.h if the initiator
* is not RFC compliant and the keys are not negotiated.
*/
if (!strcmp(param->name, MAXBURSTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, FIRSTBURSTLENGTH))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, DEFAULTTIME2WAIT))
SET_PSTATE_REPLY_OPTIONAL(param);
if (!strcmp(param->name, DEFAULTTIME2RETAIN))
SET_PSTATE_REPLY_OPTIONAL(param);
/*
* Required for gPXE iSCSI boot client
*/
if (!strcmp(param->name, MAXCONNECTIONS))
SET_PSTATE_REPLY_OPTIONAL(param);
} else if (IS_PHASE_DECLARATIVE(param))
SET_PSTATE_REPLY_OPTIONAL(param);
}
static int iscsi_check_boolean_value(struct iscsi_param *param, char *value)
{
if (strcmp(value, YES) && strcmp(value, NO)) {
pr_err("Illegal value for \"%s\", must be either"
" \"%s\" or \"%s\".\n", param->name, YES, NO);
return -1;
}
return 0;
}
static int iscsi_check_numerical_value(struct iscsi_param *param, char *value_ptr)
{
char *tmpptr;
int value = 0;
value = simple_strtoul(value_ptr, &tmpptr, 0);
if (IS_TYPERANGE_0_TO_2(param)) {
if ((value < 0) || (value > 2)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 2.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_3600(param)) {
if ((value < 0) || (value > 3600)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 3600.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_32767(param)) {
if ((value < 0) || (value > 32767)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 32767.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_0_TO_65535(param)) {
if ((value < 0) || (value > 65535)) {
pr_err("Illegal value for \"%s\", must be"
" between 0 and 65535.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_1_TO_65535(param)) {
if ((value < 1) || (value > 65535)) {
pr_err("Illegal value for \"%s\", must be"
" between 1 and 65535.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_2_TO_3600(param)) {
if ((value < 2) || (value > 3600)) {
pr_err("Illegal value for \"%s\", must be"
" between 2 and 3600.\n", param->name);
return -1;
}
return 0;
}
if (IS_TYPERANGE_512_TO_16777215(param)) {
if ((value < 512) || (value > 16777215)) {
pr_err("Illegal value for \"%s\", must be"
" between 512 and 16777215.\n", param->name);
return -1;
}
return 0;
}
return 0;
}
static int iscsi_check_numerical_range_value(struct iscsi_param *param, char *value)
{
char *left_val_ptr = NULL, *right_val_ptr = NULL;
char *tilde_ptr = NULL;
u32 left_val, right_val, local_left_val;
if (strcmp(param->name, IFMARKINT) &&
strcmp(param->name, OFMARKINT)) {
pr_err("Only parameters \"%s\" or \"%s\" may contain a"
" numerical range value.\n", IFMARKINT, OFMARKINT);
return -1;
}
if (IS_PSTATE_PROPOSER(param))
return 0;
tilde_ptr = strchr(value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range indicator"
" \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = value;
right_val_ptr = value + strlen(left_val_ptr) + 1;
if (iscsi_check_numerical_value(param, left_val_ptr) < 0)
return -1;
if (iscsi_check_numerical_value(param, right_val_ptr) < 0)
return -1;
left_val = simple_strtoul(left_val_ptr, NULL, 0);
right_val = simple_strtoul(right_val_ptr, NULL, 0);
*tilde_ptr = '~';
if (right_val < left_val) {
pr_err("Numerical range for parameter \"%s\" contains"
" a right value which is less than the left.\n",
param->name);
return -1;
}
/*
* For now, enforce reasonable defaults for [I,O]FMarkInt.
*/
tilde_ptr = strchr(param->value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range indicator"
" \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = param->value;
right_val_ptr = param->value + strlen(left_val_ptr) + 1;
local_left_val = simple_strtoul(left_val_ptr, NULL, 0);
*tilde_ptr = '~';
if (param->set_param) {
if ((left_val < local_left_val) ||
(right_val < local_left_val)) {
pr_err("Passed value range \"%u~%u\" is below"
" minimum left value \"%u\" for key \"%s\","
" rejecting.\n", left_val, right_val,
local_left_val, param->name);
return -1;
}
} else {
if ((left_val < local_left_val) &&
(right_val < local_left_val)) {
pr_err("Received value range \"%u~%u\" is"
" below minimum left value \"%u\" for key"
" \"%s\", rejecting.\n", left_val, right_val,
local_left_val, param->name);
SET_PSTATE_REJECT(param);
if (iscsi_update_param_value(param, REJECT) < 0)
return -1;
}
}
return 0;
}
static int iscsi_check_string_or_list_value(struct iscsi_param *param, char *value)
{
if (IS_PSTATE_PROPOSER(param))
return 0;
if (IS_TYPERANGE_AUTH_PARAM(param)) {
if (strcmp(value, KRB5) && strcmp(value, SPKM1) &&
strcmp(value, SPKM2) && strcmp(value, SRP) &&
strcmp(value, CHAP) && strcmp(value, NONE)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\", \"%s\", \"%s\", \"%s\", \"%s\""
" or \"%s\".\n", param->name, KRB5,
SPKM1, SPKM2, SRP, CHAP, NONE);
return -1;
}
}
if (IS_TYPERANGE_DIGEST_PARAM(param)) {
if (strcmp(value, CRC32C) && strcmp(value, NONE)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\" or \"%s\".\n", param->name,
CRC32C, NONE);
return -1;
}
}
if (IS_TYPERANGE_SESSIONTYPE(param)) {
if (strcmp(value, DISCOVERY) && strcmp(value, NORMAL)) {
pr_err("Illegal value for \"%s\", must be"
" \"%s\" or \"%s\".\n", param->name,
DISCOVERY, NORMAL);
return -1;
}
}
return 0;
}
/*
* This function is used to pick a value range number, currently just
* returns the lesser of both right values.
*/
static char *iscsi_get_value_from_number_range(
struct iscsi_param *param,
char *value)
{
char *end_ptr, *tilde_ptr1 = NULL, *tilde_ptr2 = NULL;
u32 acceptor_right_value, proposer_right_value;
tilde_ptr1 = strchr(value, '~');
if (!tilde_ptr1)
return NULL;
*tilde_ptr1++ = '\0';
proposer_right_value = simple_strtoul(tilde_ptr1, &end_ptr, 0);
tilde_ptr2 = strchr(param->value, '~');
if (!tilde_ptr2)
return NULL;
*tilde_ptr2++ = '\0';
acceptor_right_value = simple_strtoul(tilde_ptr2, &end_ptr, 0);
return (acceptor_right_value >= proposer_right_value) ?
tilde_ptr1 : tilde_ptr2;
}
static char *iscsi_check_valuelist_for_support(
struct iscsi_param *param,
char *value)
{
char *tmp1 = NULL, *tmp2 = NULL;
char *acceptor_values = NULL, *proposer_values = NULL;
acceptor_values = param->value;
proposer_values = value;
do {
if (!proposer_values)
return NULL;
tmp1 = strchr(proposer_values, ',');
if (tmp1)
*tmp1 = '\0';
acceptor_values = param->value;
do {
if (!acceptor_values) {
if (tmp1)
*tmp1 = ',';
return NULL;
}
tmp2 = strchr(acceptor_values, ',');
if (tmp2)
*tmp2 = '\0';
if (!strcmp(acceptor_values, proposer_values)) {
if (tmp2)
*tmp2 = ',';
goto out;
}
if (tmp2)
*tmp2++ = ',';
acceptor_values = tmp2;
} while (acceptor_values);
if (tmp1)
*tmp1++ = ',';
proposer_values = tmp1;
} while (proposer_values);
out:
return proposer_values;
}
static int iscsi_check_acceptor_state(struct iscsi_param *param, char *value,
struct iscsi_conn *conn)
{
u8 acceptor_boolean_value = 0, proposer_boolean_value = 0;
char *negoitated_value = NULL;
if (IS_PSTATE_ACCEPTOR(param)) {
pr_err("Received key \"%s\" twice, protocol error.\n",
param->name);
return -1;
}
if (IS_PSTATE_REJECT(param))
return 0;
if (IS_TYPE_BOOL_AND(param)) {
if (!strcmp(value, YES))
proposer_boolean_value = 1;
if (!strcmp(param->value, YES))
acceptor_boolean_value = 1;
if (acceptor_boolean_value && proposer_boolean_value)
do {} while (0);
else {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
if (!proposer_boolean_value)
SET_PSTATE_REPLY_OPTIONAL(param);
}
} else if (IS_TYPE_BOOL_OR(param)) {
if (!strcmp(value, YES))
proposer_boolean_value = 1;
if (!strcmp(param->value, YES))
acceptor_boolean_value = 1;
if (acceptor_boolean_value || proposer_boolean_value) {
if (iscsi_update_param_value(param, YES) < 0)
return -1;
if (proposer_boolean_value)
SET_PSTATE_REPLY_OPTIONAL(param);
}
} else if (IS_TYPE_NUMBER(param)) {
char *tmpptr, buf[11];
u32 acceptor_value = simple_strtoul(param->value, &tmpptr, 0);
u32 proposer_value = simple_strtoul(value, &tmpptr, 0);
memset(buf, 0, sizeof(buf));
if (!strcmp(param->name, MAXCONNECTIONS) ||
!strcmp(param->name, MAXBURSTLENGTH) ||
!strcmp(param->name, FIRSTBURSTLENGTH) ||
!strcmp(param->name, MAXOUTSTANDINGR2T) ||
!strcmp(param->name, DEFAULTTIME2RETAIN) ||
!strcmp(param->name, ERRORRECOVERYLEVEL)) {
if (proposer_value > acceptor_value) {
sprintf(buf, "%u", acceptor_value);
if (iscsi_update_param_value(param,
&buf[0]) < 0)
return -1;
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
if (acceptor_value > proposer_value) {
sprintf(buf, "%u", acceptor_value);
if (iscsi_update_param_value(param,
&buf[0]) < 0)
return -1;
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
} else {
if (iscsi_update_param_value(param, value) < 0)
return -1;
}
if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) {
struct iscsi_param *param_mxdsl;
unsigned long long tmp;
int rc;
rc = strict_strtoull(param->value, 0, &tmp);
if (rc < 0)
return -1;
conn->conn_ops->MaxRecvDataSegmentLength = tmp;
pr_debug("Saving op->MaxRecvDataSegmentLength from"
" original initiator received value: %u\n",
conn->conn_ops->MaxRecvDataSegmentLength);
param_mxdsl = iscsi_find_param_from_key(
MAXXMITDATASEGMENTLENGTH,
conn->param_list);
if (!param_mxdsl)
return -1;
rc = iscsi_update_param_value(param,
param_mxdsl->value);
if (rc < 0)
return -1;
pr_debug("Updated %s to target MXDSL value: %s\n",
param->name, param->value);
}
} else if (IS_TYPE_NUMBER_RANGE(param)) {
negoitated_value = iscsi_get_value_from_number_range(
param, value);
if (!negoitated_value)
return -1;
if (iscsi_update_param_value(param, negoitated_value) < 0)
return -1;
} else if (IS_TYPE_VALUE_LIST(param)) {
negoitated_value = iscsi_check_valuelist_for_support(
param, value);
if (!negoitated_value) {
pr_err("Proposer's value list \"%s\" contains"
" no valid values from Acceptor's value list"
" \"%s\".\n", value, param->value);
return -1;
}
if (iscsi_update_param_value(param, negoitated_value) < 0)
return -1;
} else if (IS_PHASE_DECLARATIVE(param)) {
if (iscsi_update_param_value(param, value) < 0)
return -1;
SET_PSTATE_REPLY_OPTIONAL(param);
}
return 0;
}
static int iscsi_check_proposer_state(struct iscsi_param *param, char *value)
{
if (IS_PSTATE_RESPONSE_GOT(param)) {
pr_err("Received key \"%s\" twice, protocol error.\n",
param->name);
return -1;
}
if (IS_TYPE_NUMBER_RANGE(param)) {
u32 left_val = 0, right_val = 0, recieved_value = 0;
char *left_val_ptr = NULL, *right_val_ptr = NULL;
char *tilde_ptr = NULL;
if (!strcmp(value, IRRELEVANT) || !strcmp(value, REJECT)) {
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
tilde_ptr = strchr(value, '~');
if (tilde_ptr) {
pr_err("Illegal \"~\" in response for \"%s\".\n",
param->name);
return -1;
}
tilde_ptr = strchr(param->value, '~');
if (!tilde_ptr) {
pr_err("Unable to locate numerical range"
" indicator \"~\" for \"%s\".\n", param->name);
return -1;
}
*tilde_ptr = '\0';
left_val_ptr = param->value;
right_val_ptr = param->value + strlen(left_val_ptr) + 1;
left_val = simple_strtoul(left_val_ptr, NULL, 0);
right_val = simple_strtoul(right_val_ptr, NULL, 0);
recieved_value = simple_strtoul(value, NULL, 0);
*tilde_ptr = '~';
if ((recieved_value < left_val) ||
(recieved_value > right_val)) {
pr_err("Illegal response \"%s=%u\", value must"
" be between %u and %u.\n", param->name,
recieved_value, left_val, right_val);
return -1;
}
} else if (IS_TYPE_VALUE_LIST(param)) {
char *comma_ptr = NULL, *tmp_ptr = NULL;
comma_ptr = strchr(value, ',');
if (comma_ptr) {
pr_err("Illegal \",\" in response for \"%s\".\n",
param->name);
return -1;
}
tmp_ptr = iscsi_check_valuelist_for_support(param, value);
if (!tmp_ptr)
return -1;
}
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
static int iscsi_check_value(struct iscsi_param *param, char *value)
{
char *comma_ptr = NULL;
if (!strcmp(value, REJECT)) {
if (!strcmp(param->name, IFMARKINT) ||
!strcmp(param->name, OFMARKINT)) {
/*
* Reject is not fatal for [I,O]FMarkInt, and causes
* [I,O]FMarker to be reset to No. (See iSCSI v20 A.3.2)
*/
SET_PSTATE_REJECT(param);
return 0;
}
pr_err("Received %s=%s\n", param->name, value);
return -1;
}
if (!strcmp(value, IRRELEVANT)) {
pr_debug("Received %s=%s\n", param->name, value);
SET_PSTATE_IRRELEVANT(param);
return 0;
}
if (!strcmp(value, NOTUNDERSTOOD)) {
if (!IS_PSTATE_PROPOSER(param)) {
pr_err("Received illegal offer %s=%s\n",
param->name, value);
return -1;
}
/* #warning FIXME: Add check for X-ExtensionKey here */
pr_err("Standard iSCSI key \"%s\" cannot be answered"
" with \"%s\", protocol error.\n", param->name, value);
return -1;
}
do {
comma_ptr = NULL;
comma_ptr = strchr(value, ',');
if (comma_ptr && !IS_TYPE_VALUE_LIST(param)) {
pr_err("Detected value separator \",\", but"
" key \"%s\" does not allow a value list,"
" protocol error.\n", param->name);
return -1;
}
if (comma_ptr)
*comma_ptr = '\0';
if (strlen(value) > VALUE_MAXLEN) {
pr_err("Value for key \"%s\" exceeds %d,"
" protocol error.\n", param->name,
VALUE_MAXLEN);
return -1;
}
if (IS_TYPE_BOOL_AND(param) || IS_TYPE_BOOL_OR(param)) {
if (iscsi_check_boolean_value(param, value) < 0)
return -1;
} else if (IS_TYPE_NUMBER(param)) {
if (iscsi_check_numerical_value(param, value) < 0)
return -1;
} else if (IS_TYPE_NUMBER_RANGE(param)) {
if (iscsi_check_numerical_range_value(param, value) < 0)
return -1;
} else if (IS_TYPE_STRING(param) || IS_TYPE_VALUE_LIST(param)) {
if (iscsi_check_string_or_list_value(param, value) < 0)
return -1;
} else {
pr_err("Huh? 0x%02x\n", param->type);
return -1;
}
if (comma_ptr)
*comma_ptr++ = ',';
value = comma_ptr;
} while (value);
return 0;
}
static struct iscsi_param *__iscsi_check_key(
char *key,
int sender,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
if (strlen(key) > KEY_MAXLEN) {
pr_err("Length of key name \"%s\" exceeds %d.\n",
key, KEY_MAXLEN);
return NULL;
}
param = iscsi_find_param_from_key(key, param_list);
if (!param)
return NULL;
if ((sender & SENDER_INITIATOR) && !IS_SENDER_INITIATOR(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "target" : "initiator");
return NULL;
}
if ((sender & SENDER_TARGET) && !IS_SENDER_TARGET(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "initiator" : "target");
return NULL;
}
return param;
}
static struct iscsi_param *iscsi_check_key(
char *key,
int phase,
int sender,
struct iscsi_param_list *param_list)
{
struct iscsi_param *param;
/*
* Key name length must not exceed 63 bytes. (See iSCSI v20 5.1)
*/
if (strlen(key) > KEY_MAXLEN) {
pr_err("Length of key name \"%s\" exceeds %d.\n",
key, KEY_MAXLEN);
return NULL;
}
param = iscsi_find_param_from_key(key, param_list);
if (!param)
return NULL;
if ((sender & SENDER_INITIATOR) && !IS_SENDER_INITIATOR(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "target" : "initiator");
return NULL;
}
if ((sender & SENDER_TARGET) && !IS_SENDER_TARGET(param)) {
pr_err("Key \"%s\" may not be sent to %s,"
" protocol error.\n", param->name,
(sender & SENDER_RECEIVER) ? "initiator" : "target");
return NULL;
}
if (IS_PSTATE_ACCEPTOR(param)) {
pr_err("Key \"%s\" received twice, protocol error.\n",
key);
return NULL;
}
if (!phase)
return param;
if (!(param->phase & phase)) {
pr_err("Key \"%s\" may not be negotiated during ",
param->name);
switch (phase) {
case PHASE_SECURITY:
pr_debug("Security phase.\n");
break;
case PHASE_OPERATIONAL:
pr_debug("Operational phase.\n");
break;
default:
pr_debug("Unknown phase.\n");
}
return NULL;
}
return param;
}
static int iscsi_enforce_integrity_rules(
u8 phase,
struct iscsi_param_list *param_list)
{
char *tmpptr;
u8 DataSequenceInOrder = 0;
u8 ErrorRecoveryLevel = 0, SessionType = 0;
u8 IFMarker = 0, OFMarker = 0;
u8 IFMarkInt_Reject = 1, OFMarkInt_Reject = 1;
u32 FirstBurstLength = 0, MaxBurstLength = 0;
struct iscsi_param *param = NULL;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->phase & phase))
continue;
if (!strcmp(param->name, SESSIONTYPE))
if (!strcmp(param->value, NORMAL))
SessionType = 1;
if (!strcmp(param->name, ERRORRECOVERYLEVEL))
ErrorRecoveryLevel = simple_strtoul(param->value,
&tmpptr, 0);
if (!strcmp(param->name, DATASEQUENCEINORDER))
if (!strcmp(param->value, YES))
DataSequenceInOrder = 1;
if (!strcmp(param->name, MAXBURSTLENGTH))
MaxBurstLength = simple_strtoul(param->value,
&tmpptr, 0);
if (!strcmp(param->name, IFMARKER))
if (!strcmp(param->value, YES))
IFMarker = 1;
if (!strcmp(param->name, OFMARKER))
if (!strcmp(param->value, YES))
OFMarker = 1;
if (!strcmp(param->name, IFMARKINT))
if (!strcmp(param->value, REJECT))
IFMarkInt_Reject = 1;
if (!strcmp(param->name, OFMARKINT))
if (!strcmp(param->value, REJECT))
OFMarkInt_Reject = 1;
}
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->phase & phase))
continue;
if (!SessionType && (!IS_PSTATE_ACCEPTOR(param) &&
(strcmp(param->name, IFMARKER) &&
strcmp(param->name, OFMARKER) &&
strcmp(param->name, IFMARKINT) &&
strcmp(param->name, OFMARKINT))))
continue;
if (!strcmp(param->name, MAXOUTSTANDINGR2T) &&
DataSequenceInOrder && (ErrorRecoveryLevel > 0)) {
if (strcmp(param->value, "1")) {
if (iscsi_update_param_value(param, "1") < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, MAXCONNECTIONS) && !SessionType) {
if (strcmp(param->value, "1")) {
if (iscsi_update_param_value(param, "1") < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
FirstBurstLength = simple_strtoul(param->value,
&tmpptr, 0);
if (FirstBurstLength > MaxBurstLength) {
char tmpbuf[11];
memset(tmpbuf, 0, sizeof(tmpbuf));
sprintf(tmpbuf, "%u", MaxBurstLength);
if (iscsi_update_param_value(param, tmpbuf))
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
if (!strcmp(param->name, IFMARKER) && IFMarkInt_Reject) {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
IFMarker = 0;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, OFMARKER) && OFMarkInt_Reject) {
if (iscsi_update_param_value(param, NO) < 0)
return -1;
OFMarker = 0;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, IFMARKINT) && !IFMarker) {
if (!strcmp(param->value, REJECT))
continue;
param->state &= ~PSTATE_NEGOTIATE;
if (iscsi_update_param_value(param, IRRELEVANT) < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
if (!strcmp(param->name, OFMARKINT) && !OFMarker) {
if (!strcmp(param->value, REJECT))
continue;
param->state &= ~PSTATE_NEGOTIATE;
if (iscsi_update_param_value(param, IRRELEVANT) < 0)
return -1;
pr_debug("Reset \"%s\" to \"%s\".\n",
param->name, param->value);
}
}
return 0;
}
int iscsi_decode_text_input(
u8 phase,
u8 sender,
char *textbuf,
u32 length,
struct iscsi_conn *conn)
{
struct iscsi_param_list *param_list = conn->param_list;
char *tmpbuf, *start = NULL, *end = NULL;
tmpbuf = kzalloc(length + 1, GFP_KERNEL);
if (!tmpbuf) {
pr_err("Unable to allocate memory for tmpbuf.\n");
return -1;
}
memcpy(tmpbuf, textbuf, length);
tmpbuf[length] = '\0';
start = tmpbuf;
end = (start + length);
while (start < end) {
char *key, *value;
struct iscsi_param *param;
if (iscsi_extract_key_value(start, &key, &value) < 0) {
kfree(tmpbuf);
return -1;
}
pr_debug("Got key: %s=%s\n", key, value);
if (phase & PHASE_SECURITY) {
if (iscsi_check_for_auth_key(key) > 0) {
kfree(tmpbuf);
return 1;
}
}
param = iscsi_check_key(key, phase, sender, param_list);
if (!param) {
if (iscsi_add_notunderstood_response(key,
value, param_list) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
continue;
}
if (iscsi_check_value(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
start += strlen(key) + strlen(value) + 2;
if (IS_PSTATE_PROPOSER(param)) {
if (iscsi_check_proposer_state(param, value) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_RESPONSE_GOT(param);
} else {
if (iscsi_check_acceptor_state(param, value, conn) < 0) {
kfree(tmpbuf);
return -1;
}
SET_PSTATE_ACCEPTOR(param);
}
}
kfree(tmpbuf);
return 0;
}
int iscsi_encode_text_output(
u8 phase,
u8 sender,
char *textbuf,
u32 *length,
struct iscsi_param_list *param_list)
{
char *output_buf = NULL;
struct iscsi_extra_response *er;
struct iscsi_param *param;
output_buf = textbuf + *length;
if (iscsi_enforce_integrity_rules(phase, param_list) < 0)
return -1;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!(param->sender & sender))
continue;
if (IS_PSTATE_ACCEPTOR(param) &&
!IS_PSTATE_RESPONSE_SENT(param) &&
!IS_PSTATE_REPLY_OPTIONAL(param) &&
(param->phase & phase)) {
*length += sprintf(output_buf, "%s=%s",
param->name, param->value);
*length += 1;
output_buf = textbuf + *length;
SET_PSTATE_RESPONSE_SENT(param);
pr_debug("Sending key: %s=%s\n",
param->name, param->value);
continue;
}
if (IS_PSTATE_NEGOTIATE(param) &&
!IS_PSTATE_ACCEPTOR(param) &&
!IS_PSTATE_PROPOSER(param) &&
(param->phase & phase)) {
*length += sprintf(output_buf, "%s=%s",
param->name, param->value);
*length += 1;
output_buf = textbuf + *length;
SET_PSTATE_PROPOSER(param);
iscsi_check_proposer_for_optional_reply(param);
pr_debug("Sending key: %s=%s\n",
param->name, param->value);
}
}
list_for_each_entry(er, ¶m_list->extra_response_list, er_list) {
*length += sprintf(output_buf, "%s=%s", er->key, er->value);
*length += 1;
output_buf = textbuf + *length;
pr_debug("Sending key: %s=%s\n", er->key, er->value);
}
iscsi_release_extra_responses(param_list);
return 0;
}
int iscsi_check_negotiated_keys(struct iscsi_param_list *param_list)
{
int ret = 0;
struct iscsi_param *param;
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (IS_PSTATE_NEGOTIATE(param) &&
IS_PSTATE_PROPOSER(param) &&
!IS_PSTATE_RESPONSE_GOT(param) &&
!IS_PSTATE_REPLY_OPTIONAL(param) &&
!IS_PHASE_DECLARATIVE(param)) {
pr_err("No response for proposed key \"%s\".\n",
param->name);
ret = -1;
}
}
return ret;
}
int iscsi_change_param_value(
char *keyvalue,
struct iscsi_param_list *param_list,
int check_key)
{
char *key = NULL, *value = NULL;
struct iscsi_param *param;
int sender = 0;
if (iscsi_extract_key_value(keyvalue, &key, &value) < 0)
return -1;
if (!check_key) {
param = __iscsi_check_key(keyvalue, sender, param_list);
if (!param)
return -1;
} else {
param = iscsi_check_key(keyvalue, 0, sender, param_list);
if (!param)
return -1;
param->set_param = 1;
if (iscsi_check_value(param, value) < 0) {
param->set_param = 0;
return -1;
}
param->set_param = 0;
}
if (iscsi_update_param_value(param, value) < 0)
return -1;
return 0;
}
void iscsi_set_connection_parameters(
struct iscsi_conn_ops *ops,
struct iscsi_param_list *param_list)
{
char *tmpptr;
struct iscsi_param *param;
pr_debug("---------------------------------------------------"
"---------------\n");
list_for_each_entry(param, ¶m_list->param_list, p_list) {
/*
* Special case to set MAXXMITDATASEGMENTLENGTH from the
* target requested MaxRecvDataSegmentLength, even though
* this key is not sent over the wire.
*/
if (!strcmp(param->name, MAXXMITDATASEGMENTLENGTH)) {
if (param_list->iser == true)
continue;
ops->MaxXmitDataSegmentLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxXmitDataSegmentLength: %s\n",
param->value);
}
if (!IS_PSTATE_ACCEPTOR(param) && !IS_PSTATE_PROPOSER(param))
continue;
if (!strcmp(param->name, AUTHMETHOD)) {
pr_debug("AuthMethod: %s\n",
param->value);
} else if (!strcmp(param->name, HEADERDIGEST)) {
ops->HeaderDigest = !strcmp(param->value, CRC32C);
pr_debug("HeaderDigest: %s\n",
param->value);
} else if (!strcmp(param->name, DATADIGEST)) {
ops->DataDigest = !strcmp(param->value, CRC32C);
pr_debug("DataDigest: %s\n",
param->value);
} else if (!strcmp(param->name, MAXRECVDATASEGMENTLENGTH)) {
/*
* At this point iscsi_check_acceptor_state() will have
* set ops->MaxRecvDataSegmentLength from the original
* initiator provided value.
*/
pr_debug("MaxRecvDataSegmentLength: %u\n",
ops->MaxRecvDataSegmentLength);
} else if (!strcmp(param->name, OFMARKER)) {
ops->OFMarker = !strcmp(param->value, YES);
pr_debug("OFMarker: %s\n",
param->value);
} else if (!strcmp(param->name, IFMARKER)) {
ops->IFMarker = !strcmp(param->value, YES);
pr_debug("IFMarker: %s\n",
param->value);
} else if (!strcmp(param->name, OFMARKINT)) {
ops->OFMarkInt =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("OFMarkInt: %s\n",
param->value);
} else if (!strcmp(param->name, IFMARKINT)) {
ops->IFMarkInt =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("IFMarkInt: %s\n",
param->value);
} else if (!strcmp(param->name, INITIATORRECVDATASEGMENTLENGTH)) {
ops->InitiatorRecvDataSegmentLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("InitiatorRecvDataSegmentLength: %s\n",
param->value);
ops->MaxRecvDataSegmentLength =
ops->InitiatorRecvDataSegmentLength;
pr_debug("Set MRDSL from InitiatorRecvDataSegmentLength\n");
} else if (!strcmp(param->name, TARGETRECVDATASEGMENTLENGTH)) {
ops->TargetRecvDataSegmentLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("TargetRecvDataSegmentLength: %s\n",
param->value);
ops->MaxXmitDataSegmentLength =
ops->TargetRecvDataSegmentLength;
pr_debug("Set MXDSL from TargetRecvDataSegmentLength\n");
}
}
pr_debug("----------------------------------------------------"
"--------------\n");
}
void iscsi_set_session_parameters(
struct iscsi_sess_ops *ops,
struct iscsi_param_list *param_list,
int leading)
{
char *tmpptr;
struct iscsi_param *param;
pr_debug("----------------------------------------------------"
"--------------\n");
list_for_each_entry(param, ¶m_list->param_list, p_list) {
if (!IS_PSTATE_ACCEPTOR(param) && !IS_PSTATE_PROPOSER(param))
continue;
if (!strcmp(param->name, INITIATORNAME)) {
if (!param->value)
continue;
if (leading)
snprintf(ops->InitiatorName,
sizeof(ops->InitiatorName),
"%s", param->value);
pr_debug("InitiatorName: %s\n",
param->value);
} else if (!strcmp(param->name, INITIATORALIAS)) {
if (!param->value)
continue;
snprintf(ops->InitiatorAlias,
sizeof(ops->InitiatorAlias),
"%s", param->value);
pr_debug("InitiatorAlias: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETNAME)) {
if (!param->value)
continue;
if (leading)
snprintf(ops->TargetName,
sizeof(ops->TargetName),
"%s", param->value);
pr_debug("TargetName: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETALIAS)) {
if (!param->value)
continue;
snprintf(ops->TargetAlias, sizeof(ops->TargetAlias),
"%s", param->value);
pr_debug("TargetAlias: %s\n",
param->value);
} else if (!strcmp(param->name, TARGETPORTALGROUPTAG)) {
ops->TargetPortalGroupTag =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("TargetPortalGroupTag: %s\n",
param->value);
} else if (!strcmp(param->name, MAXCONNECTIONS)) {
ops->MaxConnections =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxConnections: %s\n",
param->value);
} else if (!strcmp(param->name, INITIALR2T)) {
ops->InitialR2T = !strcmp(param->value, YES);
pr_debug("InitialR2T: %s\n",
param->value);
} else if (!strcmp(param->name, IMMEDIATEDATA)) {
ops->ImmediateData = !strcmp(param->value, YES);
pr_debug("ImmediateData: %s\n",
param->value);
} else if (!strcmp(param->name, MAXBURSTLENGTH)) {
ops->MaxBurstLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxBurstLength: %s\n",
param->value);
} else if (!strcmp(param->name, FIRSTBURSTLENGTH)) {
ops->FirstBurstLength =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("FirstBurstLength: %s\n",
param->value);
} else if (!strcmp(param->name, DEFAULTTIME2WAIT)) {
ops->DefaultTime2Wait =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("DefaultTime2Wait: %s\n",
param->value);
} else if (!strcmp(param->name, DEFAULTTIME2RETAIN)) {
ops->DefaultTime2Retain =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("DefaultTime2Retain: %s\n",
param->value);
} else if (!strcmp(param->name, MAXOUTSTANDINGR2T)) {
ops->MaxOutstandingR2T =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("MaxOutstandingR2T: %s\n",
param->value);
} else if (!strcmp(param->name, DATAPDUINORDER)) {
ops->DataPDUInOrder = !strcmp(param->value, YES);
pr_debug("DataPDUInOrder: %s\n",
param->value);
} else if (!strcmp(param->name, DATASEQUENCEINORDER)) {
ops->DataSequenceInOrder = !strcmp(param->value, YES);
pr_debug("DataSequenceInOrder: %s\n",
param->value);
} else if (!strcmp(param->name, ERRORRECOVERYLEVEL)) {
ops->ErrorRecoveryLevel =
simple_strtoul(param->value, &tmpptr, 0);
pr_debug("ErrorRecoveryLevel: %s\n",
param->value);
} else if (!strcmp(param->name, SESSIONTYPE)) {
ops->SessionType = !strcmp(param->value, DISCOVERY);
pr_debug("SessionType: %s\n",
param->value);
} else if (!strcmp(param->name, RDMAEXTENSIONS)) {
ops->RDMAExtensions = !strcmp(param->value, YES);
pr_debug("RDMAExtensions: %s\n",
param->value);
}
}
pr_debug("----------------------------------------------------"
"--------------\n");
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5675_0 |
crossvul-cpp_data_bad_340_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_340_2 |
crossvul-cpp_data_good_5079_0 | /*
* Packet matching code for ARP packets.
*
* Based heavily, if not almost entirely, upon ip_tables.c framework.
*
* Some ARP specific bits are:
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
* Copyright (C) 2006-2009 Patrick McHardy <kaber@trash.net>
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/capability.h>
#include <linux/if_arp.h>
#include <linux/kmod.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <net/compat.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_arp/arp_tables.h>
#include "../../netfilter/xt_repldata.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David S. Miller <davem@redhat.com>");
MODULE_DESCRIPTION("arptables core");
/*#define DEBUG_ARP_TABLES*/
/*#define DEBUG_ARP_TABLES_USER*/
#ifdef DEBUG_ARP_TABLES
#define dprintf(format, args...) pr_debug(format, ## args)
#else
#define dprintf(format, args...)
#endif
#ifdef DEBUG_ARP_TABLES_USER
#define duprintf(format, args...) pr_debug(format, ## args)
#else
#define duprintf(format, args...)
#endif
#ifdef CONFIG_NETFILTER_DEBUG
#define ARP_NF_ASSERT(x) WARN_ON(!(x))
#else
#define ARP_NF_ASSERT(x)
#endif
void *arpt_alloc_initial_table(const struct xt_table *info)
{
return xt_alloc_initial_table(arpt, ARPT);
}
EXPORT_SYMBOL_GPL(arpt_alloc_initial_table);
static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap,
const char *hdr_addr, int len)
{
int i, ret;
if (len > ARPT_DEV_ADDR_LEN_MAX)
len = ARPT_DEV_ADDR_LEN_MAX;
ret = 0;
for (i = 0; i < len; i++)
ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i];
return ret != 0;
}
/*
* Unfortunately, _b and _mask are not aligned to an int (or long int)
* Some arches dont care, unrolling the loop is a win on them.
* For other arches, we only have a 16bit alignement.
*/
static unsigned long ifname_compare(const char *_a, const char *_b, const char *_mask)
{
#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
unsigned long ret = ifname_compare_aligned(_a, _b, _mask);
#else
unsigned long ret = 0;
const u16 *a = (const u16 *)_a;
const u16 *b = (const u16 *)_b;
const u16 *mask = (const u16 *)_mask;
int i;
for (i = 0; i < IFNAMSIZ/sizeof(u16); i++)
ret |= (a[i] ^ b[i]) & mask[i];
#endif
return ret;
}
/* Returns whether packet matches rule or not. */
static inline int arp_packet_match(const struct arphdr *arphdr,
struct net_device *dev,
const char *indev,
const char *outdev,
const struct arpt_arp *arpinfo)
{
const char *arpptr = (char *)(arphdr + 1);
const char *src_devaddr, *tgt_devaddr;
__be32 src_ipaddr, tgt_ipaddr;
long ret;
#define FWINV(bool, invflg) ((bool) ^ !!(arpinfo->invflags & (invflg)))
if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop,
ARPT_INV_ARPOP)) {
dprintf("ARP operation field mismatch.\n");
dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n",
arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask);
return 0;
}
if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd,
ARPT_INV_ARPHRD)) {
dprintf("ARP hardware address format mismatch.\n");
dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n",
arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask);
return 0;
}
if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro,
ARPT_INV_ARPPRO)) {
dprintf("ARP protocol address format mismatch.\n");
dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n",
arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask);
return 0;
}
if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln,
ARPT_INV_ARPHLN)) {
dprintf("ARP hardware address length mismatch.\n");
dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n",
arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask);
return 0;
}
src_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&src_ipaddr, arpptr, sizeof(u32));
arpptr += sizeof(u32);
tgt_devaddr = arpptr;
arpptr += dev->addr_len;
memcpy(&tgt_ipaddr, arpptr, sizeof(u32));
if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len),
ARPT_INV_SRCDEVADDR) ||
FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len),
ARPT_INV_TGTDEVADDR)) {
dprintf("Source or target device address mismatch.\n");
return 0;
}
if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr,
ARPT_INV_SRCIP) ||
FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr),
ARPT_INV_TGTIP)) {
dprintf("Source or target IP address mismatch.\n");
dprintf("SRC: %pI4. Mask: %pI4. Target: %pI4.%s\n",
&src_ipaddr,
&arpinfo->smsk.s_addr,
&arpinfo->src.s_addr,
arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : "");
dprintf("TGT: %pI4 Mask: %pI4 Target: %pI4.%s\n",
&tgt_ipaddr,
&arpinfo->tmsk.s_addr,
&arpinfo->tgt.s_addr,
arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : "");
return 0;
}
/* Look for ifname matches. */
ret = ifname_compare(indev, arpinfo->iniface, arpinfo->iniface_mask);
if (FWINV(ret != 0, ARPT_INV_VIA_IN)) {
dprintf("VIA in mismatch (%s vs %s).%s\n",
indev, arpinfo->iniface,
arpinfo->invflags & ARPT_INV_VIA_IN ? " (INV)" : "");
return 0;
}
ret = ifname_compare(outdev, arpinfo->outiface, arpinfo->outiface_mask);
if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) {
dprintf("VIA out mismatch (%s vs %s).%s\n",
outdev, arpinfo->outiface,
arpinfo->invflags & ARPT_INV_VIA_OUT ? " (INV)" : "");
return 0;
}
return 1;
#undef FWINV
}
static inline int arp_checkentry(const struct arpt_arp *arp)
{
if (arp->flags & ~ARPT_F_MASK) {
duprintf("Unknown flag bits set: %08X\n",
arp->flags & ~ARPT_F_MASK);
return 0;
}
if (arp->invflags & ~ARPT_INV_MASK) {
duprintf("Unknown invflag bits set: %08X\n",
arp->invflags & ~ARPT_INV_MASK);
return 0;
}
return 1;
}
static unsigned int
arpt_error(struct sk_buff *skb, const struct xt_action_param *par)
{
net_err_ratelimited("arp_tables: error: '%s'\n",
(const char *)par->targinfo);
return NF_DROP;
}
static inline const struct xt_entry_target *
arpt_get_target_c(const struct arpt_entry *e)
{
return arpt_get_target((struct arpt_entry *)e);
}
static inline struct arpt_entry *
get_entry(const void *base, unsigned int offset)
{
return (struct arpt_entry *)(base + offset);
}
static inline
struct arpt_entry *arpt_next_entry(const struct arpt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
unsigned int arpt_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))));
unsigned int verdict = NF_DROP;
const struct arphdr *arp;
struct arpt_entry *e, **jumpstack;
const char *indev, *outdev;
const void *table_base;
unsigned int cpu, stackidx = 0;
const struct xt_table_info *private;
struct xt_action_param acpar;
unsigned int addend;
if (!pskb_may_pull(skb, arp_hdr_len(skb->dev)))
return NF_DROP;
indev = state->in ? state->in->name : nulldevname;
outdev = state->out ? state->out->name : nulldevname;
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 arpt_entry **)private->jumpstack[cpu];
/* No TEE support for arptables, so no need to switch to alternate
* stack. All targets that reenter must return absolute verdicts.
*/
e = get_entry(table_base, private->hook_entry[hook]);
acpar.net = state->net;
acpar.in = state->in;
acpar.out = state->out;
acpar.hooknum = hook;
acpar.family = NFPROTO_ARP;
acpar.hotdrop = false;
arp = arp_hdr(skb);
do {
const struct xt_entry_target *t;
struct xt_counters *counter;
if (!arp_packet_match(arp, skb->dev, indev, outdev, &e->arp)) {
e = arpt_next_entry(e);
continue;
}
counter = xt_get_this_cpu_counter(&e->counters);
ADD_COUNTER(*counter, arp_hdr_len(skb->dev), 1);
t = arpt_get_target_c(e);
/* 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]);
} else {
e = jumpstack[--stackidx];
e = arpt_next_entry(e);
}
continue;
}
if (table_base + v
!= arpt_next_entry(e)) {
jumpstack[stackidx++] = e;
}
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. */
arp = arp_hdr(skb);
if (verdict == XT_CONTINUE)
e = arpt_next_entry(e);
else
/* Verdict */
break;
} while (!acpar.hotdrop);
xt_write_recseq_end(addend);
local_bh_enable();
if (acpar.hotdrop)
return NF_DROP;
else
return verdict;
}
/* All zeroes == unconditional rule. */
static inline bool unconditional(const struct arpt_arp *arp)
{
static const struct arpt_arp uncond;
return memcmp(arp, &uncond, sizeof(uncond)) == 0;
}
/* 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_ARP_NUMHOOKS; hook++) {
unsigned int pos = newinfo->hook_entry[hook];
struct arpt_entry *e
= (struct arpt_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 *)arpt_get_target_c(e);
int visited = e->comefrom & (1 << hook);
if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) {
pr_notice("arptables: loop hook %u pos %u %08X.\n",
hook, pos, e->comefrom);
return 0;
}
e->comefrom
|= ((1 << hook) | (1 << NF_ARP_NUMHOOKS));
/* Unconditional return/END. */
if ((e->target_offset == sizeof(struct arpt_entry) &&
(strcmp(t->target.u.user.name,
XT_STANDARD_TARGET) == 0) &&
t->verdict < 0 && unconditional(&e->arp)) ||
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_ARP_NUMHOOKS);
oldpos = pos;
pos = e->counters.pcnt;
e->counters.pcnt = 0;
/* We're at the start. */
if (pos == oldpos)
goto next;
e = (struct arpt_entry *)
(entry0 + pos);
} while (oldpos == pos + e->next_offset);
/* Move along one */
size = e->next_offset;
e = (struct arpt_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 arpt_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 arpt_entry *)
(entry0 + newpos);
e->counters.pcnt = pos;
pos = newpos;
}
}
next:
duprintf("Finished chain %u\n", hook);
}
return 1;
}
static inline int check_entry(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
if (!arp_checkentry(&e->arp))
return -EINVAL;
if (e->target_offset + sizeof(struct xt_entry_target) > e->next_offset)
return -EINVAL;
t = arpt_get_target_c(e);
if (e->target_offset + t->u.target_size > e->next_offset)
return -EINVAL;
return 0;
}
static inline int check_target(struct arpt_entry *e, const char *name)
{
struct xt_entry_target *t = arpt_get_target(e);
int ret;
struct xt_tgchk_param par = {
.table = name,
.entryinfo = e,
.target = t->u.kernel.target,
.targinfo = t->data,
.hook_mask = e->comefrom,
.family = NFPROTO_ARP,
};
ret = xt_check_target(&par, t->u.target_size - sizeof(*t), 0, false);
if (ret < 0) {
duprintf("arp_tables: check failed for `%s'.\n",
t->u.kernel.target->name);
return ret;
}
return 0;
}
static inline int
find_check_entry(struct arpt_entry *e, const char *name, unsigned int size)
{
struct xt_entry_target *t;
struct xt_target *target;
int ret;
e->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(e->counters.pcnt))
return -ENOMEM;
t = arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, 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 out;
}
t->u.kernel.target = target;
ret = check_target(e, name);
if (ret)
goto err;
return 0;
err:
module_put(t->u.kernel.target->me);
out:
xt_percpu_counter_free(e->counters.pcnt);
return ret;
}
static bool check_underflow(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(&e->arp))
return false;
t = arpt_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 inline int check_entry_size_and_hooks(struct arpt_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 arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct arpt_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_ARP_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 inline void cleanup_entry(struct arpt_entry *e)
{
struct xt_tgdtor_param par;
struct xt_entry_target *t;
t = arpt_get_target(e);
par.target = t->u.kernel.target;
par.targinfo = t->data;
par.family = NFPROTO_ARP;
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 xt_table_info *newinfo, void *entry0,
const struct arpt_replace *repl)
{
struct arpt_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_ARP_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)
break;
++i;
if (strcmp(arpt_get_target(iter)->u.user.name,
XT_ERROR_TARGET) == 0)
++newinfo->stacksize;
}
duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret);
if (ret != 0)
return ret;
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_ARP_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)) {
duprintf("Looping hook\n");
return -ELOOP;
}
/* Finally, each sanity check must pass */
i = 0;
xt_entry_foreach(iter, entry0, newinfo->size) {
ret = find_check_entry(iter, 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);
}
return ret;
}
return ret;
}
static void get_counters(const struct xt_table_info *t,
struct xt_counters counters[])
{
struct arpt_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;
}
}
}
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 arpt_entry *e;
struct xt_counters *counters;
struct xt_table_info *private = table->private;
int ret = 0;
void *loc_cpu_entry;
counters = alloc_counters(table);
if (IS_ERR(counters))
return PTR_ERR(counters);
loc_cpu_entry = private->entries;
/* ... then copy entire thing ... */
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++){
const struct xt_entry_target *t;
e = (struct arpt_entry *)(loc_cpu_entry + off);
if (copy_to_user(userptr + off
+ offsetof(struct arpt_entry, counters),
&counters[num],
sizeof(counters[num])) != 0) {
ret = -EFAULT;
goto free_counters;
}
t = arpt_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(NFPROTO_ARP, 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(NFPROTO_ARP, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
static int compat_calc_entry(const struct arpt_entry *e,
const struct xt_table_info *info,
const void *base, struct xt_table_info *newinfo)
{
const struct xt_entry_target *t;
unsigned int entry_offset;
int off, i, ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - base;
t = arpt_get_target_c(e);
off += xt_compat_target_offset(t->u.kernel.target);
newinfo->size -= off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
if (info->hook_entry[i] &&
(e < (struct arpt_entry *)(base + info->hook_entry[i])))
newinfo->hook_entry[i] -= off;
if (info->underflow[i] &&
(e < (struct arpt_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 arpt_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(NFPROTO_ARP, 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 arpt_getinfo)) {
duprintf("length %u != %Zu\n", *len,
sizeof(struct arpt_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(NFPROTO_ARP);
#endif
t = try_then_request_module(xt_find_table_lock(net, NFPROTO_ARP, name),
"arptable_%s", name);
if (!IS_ERR_OR_NULL(t)) {
struct arpt_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(NFPROTO_ARP);
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(NFPROTO_ARP);
#endif
return ret;
}
static int get_entries(struct net *net, struct arpt_get_entries __user *uptr,
const int *len)
{
int ret;
struct arpt_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 arpt_get_entries) + get.size) {
duprintf("get_entries: %u != %Zu\n", *len,
sizeof(struct arpt_get_entries) + get.size);
return -EINVAL;
}
t = xt_find_table_lock(net, NFPROTO_ARP, 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;
void *loc_cpu_old_entry;
struct arpt_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, NFPROTO_ARP, name),
"arptable_%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 */
loc_cpu_old_entry = oldinfo->entries;
xt_entry_foreach(iter, loc_cpu_old_entry, oldinfo->size)
cleanup_entry(iter);
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("arptables: 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 arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_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(newinfo, loc_cpu_entry, &tmp);
if (ret != 0)
goto free_newinfo;
duprintf("arp_tables: 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);
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 arpt_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, NFPROTO_ARP, 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
static inline void compat_release_entry(struct compat_arpt_entry *e)
{
struct xt_entry_target *t;
t = compat_arpt_get_target(e);
module_put(t->u.kernel.target->me);
}
static inline int
check_compat_entry_size_and_hooks(struct compat_arpt_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_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_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_arpt_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 arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, 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 out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_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;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
static int
compat_copy_entry_from_user(struct compat_arpt_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 arpt_entry *de;
unsigned int origsize;
int ret, h;
ret = 0;
origsize = *size;
de = (struct arpt_entry *)*dstptr;
memcpy(de, e, sizeof(struct arpt_entry));
memcpy(&de->counters, &e->counters, sizeof(e->counters));
*dstptr += sizeof(struct arpt_entry);
*size += sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
de->target_offset = e->target_offset - (origsize - *size);
t = compat_arpt_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_ARP_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 translate_compat_table(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_arpt_entry *iter0;
struct arpt_entry *iter1;
unsigned int size;
int ret = 0;
info = *pinfo;
entry0 = *pentry0;
size = total_size;
info->number = number;
/* Init all hooks to impossible value. */
for (i = 0; i < NF_ARP_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(NFPROTO_ARP);
xt_compat_init_offsets(NFPROTO_ARP, 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_ARP_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_ARP_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(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
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) {
iter1->counters.pcnt = xt_percpu_counter_alloc();
if (IS_ERR_VALUE(iter1->counters.pcnt)) {
ret = -ENOMEM;
break;
}
ret = check_target(iter1, name);
if (ret != 0) {
xt_percpu_counter_free(iter1->counters.pcnt);
break;
}
++i;
if (strcmp(arpt_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);
}
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(NFPROTO_ARP);
xt_compat_unlock(NFPROTO_ARP);
goto out;
}
struct compat_arpt_replace {
char name[XT_TABLE_MAXNAMELEN];
u32 valid_hooks;
u32 num_entries;
u32 size;
u32 hook_entry[NF_ARP_NUMHOOKS];
u32 underflow[NF_ARP_NUMHOOKS];
u32 num_counters;
compat_uptr_t counters;
struct compat_arpt_entry entries[0];
};
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret;
struct compat_arpt_replace tmp;
struct xt_table_info *newinfo;
void *loc_cpu_entry;
struct arpt_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(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);
free_newinfo:
xt_free_table_info(newinfo);
return ret;
}
static int compat_do_arpt_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 ARPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
duprintf("do_arpt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int compat_copy_entry_to_user(struct arpt_entry *e, void __user **dstptr,
compat_uint_t *size,
struct xt_counters *counters,
unsigned int i)
{
struct xt_entry_target *t;
struct compat_arpt_entry __user *ce;
u_int16_t target_offset, next_offset;
compat_uint_t origsize;
int ret;
origsize = *size;
ce = (struct compat_arpt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(struct arpt_entry)) != 0 ||
copy_to_user(&ce->counters, &counters[i],
sizeof(counters[i])) != 0)
return -EFAULT;
*dstptr += sizeof(struct compat_arpt_entry);
*size -= sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
target_offset = e->target_offset - (origsize - *size);
t = arpt_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_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 arpt_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;
}
struct compat_arpt_get_entries {
char name[XT_TABLE_MAXNAMELEN];
compat_uint_t size;
struct compat_arpt_entry entrytable[0];
};
static int compat_get_entries(struct net *net,
struct compat_arpt_get_entries __user *uptr,
int *len)
{
int ret;
struct compat_arpt_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_arpt_get_entries) + get.size) {
duprintf("compat_get_entries: %u != %zu\n",
*len, sizeof(get) + get.size);
return -EINVAL;
}
xt_compat_lock(NFPROTO_ARP);
t = xt_find_table_lock(net, NFPROTO_ARP, 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(NFPROTO_ARP);
module_put(t->me);
xt_table_unlock(t);
} else
ret = t ? PTR_ERR(t) : -ENOENT;
xt_compat_unlock(NFPROTO_ARP);
return ret;
}
static int do_arpt_get_ctl(struct sock *, int, void __user *, int *);
static int compat_do_arpt_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 ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 1);
break;
case ARPT_SO_GET_ENTRIES:
ret = compat_get_entries(sock_net(sk), user, len);
break;
default:
ret = do_arpt_get_ctl(sk, cmd, user, len);
}
return ret;
}
#endif
static int do_arpt_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 ARPT_SO_SET_REPLACE:
ret = do_replace(sock_net(sk), user, len);
break;
case ARPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 0);
break;
default:
duprintf("do_arpt_set_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static int do_arpt_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 ARPT_SO_GET_INFO:
ret = get_info(sock_net(sk), user, len, 0);
break;
case ARPT_SO_GET_ENTRIES:
ret = get_entries(sock_net(sk), user, len);
break;
case ARPT_SO_GET_REVISION_TARGET: {
struct xt_get_revision rev;
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;
try_then_request_module(xt_find_revision(NFPROTO_ARP, rev.name,
rev.revision, 1, &ret),
"arpt_%s", rev.name);
break;
}
default:
duprintf("do_arpt_get_ctl: unknown request %i\n", cmd);
ret = -EINVAL;
}
return ret;
}
static void __arpt_unregister_table(struct xt_table *table)
{
struct xt_table_info *private;
void *loc_cpu_entry;
struct module *table_owner = table->me;
struct arpt_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);
if (private->number > private->initial_entries)
module_put(table_owner);
xt_free_table_info(private);
}
int arpt_register_table(struct net *net,
const struct xt_table *table,
const struct arpt_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(newinfo, loc_cpu_entry, repl);
duprintf("arpt_register_table: translate table gives %d\n", ret);
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) {
__arpt_unregister_table(new_table);
*res = NULL;
}
return ret;
out_free:
xt_free_table_info(newinfo);
return ret;
}
void arpt_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));
__arpt_unregister_table(table);
}
/* The built-in targets: standard (NULL) and error. */
static struct xt_target arpt_builtin_tg[] __read_mostly = {
{
.name = XT_STANDARD_TARGET,
.targetsize = sizeof(int),
.family = NFPROTO_ARP,
#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 = arpt_error,
.targetsize = XT_FUNCTION_MAXNAMELEN,
.family = NFPROTO_ARP,
},
};
static struct nf_sockopt_ops arpt_sockopts = {
.pf = PF_INET,
.set_optmin = ARPT_BASE_CTL,
.set_optmax = ARPT_SO_SET_MAX+1,
.set = do_arpt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_arpt_set_ctl,
#endif
.get_optmin = ARPT_BASE_CTL,
.get_optmax = ARPT_SO_GET_MAX+1,
.get = do_arpt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_arpt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __net_init arp_tables_net_init(struct net *net)
{
return xt_proto_init(net, NFPROTO_ARP);
}
static void __net_exit arp_tables_net_exit(struct net *net)
{
xt_proto_fini(net, NFPROTO_ARP);
}
static struct pernet_operations arp_tables_net_ops = {
.init = arp_tables_net_init,
.exit = arp_tables_net_exit,
};
static int __init arp_tables_init(void)
{
int ret;
ret = register_pernet_subsys(&arp_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(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
if (ret < 0)
goto err2;
/* Register setsockopt */
ret = nf_register_sockopt(&arpt_sockopts);
if (ret < 0)
goto err4;
pr_info("arp_tables: (C) 2002 David S. Miller\n");
return 0;
err4:
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
err2:
unregister_pernet_subsys(&arp_tables_net_ops);
err1:
return ret;
}
static void __exit arp_tables_fini(void)
{
nf_unregister_sockopt(&arpt_sockopts);
xt_unregister_targets(arpt_builtin_tg, ARRAY_SIZE(arpt_builtin_tg));
unregister_pernet_subsys(&arp_tables_net_ops);
}
EXPORT_SYMBOL(arpt_register_table);
EXPORT_SYMBOL(arpt_unregister_table);
EXPORT_SYMBOL(arpt_do_table);
module_init(arp_tables_init);
module_exit(arp_tables_fini);
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_5079_0 |
crossvul-cpp_data_good_3519_0 | /*
* linux/fs/jbd2/transaction.c
*
* Written by Stephen C. Tweedie <sct@redhat.com>, 1998
*
* Copyright 1998 Red Hat corp --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Generic filesystem transaction handling code; part of the ext2fs
* journaling system.
*
* This file manages transactions (compound commits managed by the
* journaling code) and handles (individual atomic operations by the
* filesystem).
*/
#include <linux/time.h>
#include <linux/fs.h>
#include <linux/jbd2.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/hrtimer.h>
#include <linux/backing-dev.h>
#include <linux/bug.h>
#include <linux/module.h>
static void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh);
static void __jbd2_journal_unfile_buffer(struct journal_head *jh);
/*
* jbd2_get_transaction: obtain a new transaction_t object.
*
* Simply allocate and initialise a new transaction. Create it in
* RUNNING state and add it to the current journal (which should not
* have an existing running transaction: we only make a new transaction
* once we have started to commit the old one).
*
* Preconditions:
* The journal MUST be locked. We don't perform atomic mallocs on the
* new transaction and we can't block without protecting against other
* processes trying to touch the journal while it is in transition.
*
*/
static transaction_t *
jbd2_get_transaction(journal_t *journal, transaction_t *transaction)
{
transaction->t_journal = journal;
transaction->t_state = T_RUNNING;
transaction->t_start_time = ktime_get();
transaction->t_tid = journal->j_transaction_sequence++;
transaction->t_expires = jiffies + journal->j_commit_interval;
spin_lock_init(&transaction->t_handle_lock);
atomic_set(&transaction->t_updates, 0);
atomic_set(&transaction->t_outstanding_credits, 0);
atomic_set(&transaction->t_handle_count, 0);
INIT_LIST_HEAD(&transaction->t_inode_list);
INIT_LIST_HEAD(&transaction->t_private_list);
/* Set up the commit timer for the new transaction. */
journal->j_commit_timer.expires = round_jiffies_up(transaction->t_expires);
add_timer(&journal->j_commit_timer);
J_ASSERT(journal->j_running_transaction == NULL);
journal->j_running_transaction = transaction;
transaction->t_max_wait = 0;
transaction->t_start = jiffies;
return transaction;
}
/*
* Handle management.
*
* A handle_t is an object which represents a single atomic update to a
* filesystem, and which tracks all of the modifications which form part
* of that one update.
*/
/*
* Update transaction's maximum wait time, if debugging is enabled.
*
* In order for t_max_wait to be reliable, it must be protected by a
* lock. But doing so will mean that start_this_handle() can not be
* run in parallel on SMP systems, which limits our scalability. So
* unless debugging is enabled, we no longer update t_max_wait, which
* means that maximum wait time reported by the jbd2_run_stats
* tracepoint will always be zero.
*/
static inline void update_t_max_wait(transaction_t *transaction,
unsigned long ts)
{
#ifdef CONFIG_JBD2_DEBUG
if (jbd2_journal_enable_debug &&
time_after(transaction->t_start, ts)) {
ts = jbd2_time_diff(ts, transaction->t_start);
spin_lock(&transaction->t_handle_lock);
if (ts > transaction->t_max_wait)
transaction->t_max_wait = ts;
spin_unlock(&transaction->t_handle_lock);
}
#endif
}
/*
* start_this_handle: Given a handle, deal with any locking or stalling
* needed to make sure that there is enough journal space for the handle
* to begin. Attach the handle to a transaction and set up the
* transaction's buffer credits.
*/
static int start_this_handle(journal_t *journal, handle_t *handle,
gfp_t gfp_mask)
{
transaction_t *transaction, *new_transaction = NULL;
tid_t tid;
int needed, need_to_start;
int nblocks = handle->h_buffer_credits;
unsigned long ts = jiffies;
if (nblocks > journal->j_max_transaction_buffers) {
printk(KERN_ERR "JBD2: %s wants too many credits (%d > %d)\n",
current->comm, nblocks,
journal->j_max_transaction_buffers);
return -ENOSPC;
}
alloc_transaction:
if (!journal->j_running_transaction) {
new_transaction = kzalloc(sizeof(*new_transaction), gfp_mask);
if (!new_transaction) {
/*
* If __GFP_FS is not present, then we may be
* being called from inside the fs writeback
* layer, so we MUST NOT fail. Since
* __GFP_NOFAIL is going away, we will arrange
* to retry the allocation ourselves.
*/
if ((gfp_mask & __GFP_FS) == 0) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
goto alloc_transaction;
}
return -ENOMEM;
}
}
jbd_debug(3, "New handle %p going live.\n", handle);
/*
* We need to hold j_state_lock until t_updates has been incremented,
* for proper journal barrier handling
*/
repeat:
read_lock(&journal->j_state_lock);
BUG_ON(journal->j_flags & JBD2_UNMOUNT);
if (is_journal_aborted(journal) ||
(journal->j_errno != 0 && !(journal->j_flags & JBD2_ACK_ERR))) {
read_unlock(&journal->j_state_lock);
kfree(new_transaction);
return -EROFS;
}
/* Wait on the journal's transaction barrier if necessary */
if (journal->j_barrier_count) {
read_unlock(&journal->j_state_lock);
wait_event(journal->j_wait_transaction_locked,
journal->j_barrier_count == 0);
goto repeat;
}
if (!journal->j_running_transaction) {
read_unlock(&journal->j_state_lock);
if (!new_transaction)
goto alloc_transaction;
write_lock(&journal->j_state_lock);
if (!journal->j_running_transaction) {
jbd2_get_transaction(journal, new_transaction);
new_transaction = NULL;
}
write_unlock(&journal->j_state_lock);
goto repeat;
}
transaction = journal->j_running_transaction;
/*
* If the current transaction is locked down for commit, wait for the
* lock to be released.
*/
if (transaction->t_state == T_LOCKED) {
DEFINE_WAIT(wait);
prepare_to_wait(&journal->j_wait_transaction_locked,
&wait, TASK_UNINTERRUPTIBLE);
read_unlock(&journal->j_state_lock);
schedule();
finish_wait(&journal->j_wait_transaction_locked, &wait);
goto repeat;
}
/*
* If there is not enough space left in the log to write all potential
* buffers requested by this operation, we need to stall pending a log
* checkpoint to free some more log space.
*/
needed = atomic_add_return(nblocks,
&transaction->t_outstanding_credits);
if (needed > journal->j_max_transaction_buffers) {
/*
* If the current transaction is already too large, then start
* to commit it: we can then go back and attach this handle to
* a new transaction.
*/
DEFINE_WAIT(wait);
jbd_debug(2, "Handle %p starting new commit...\n", handle);
atomic_sub(nblocks, &transaction->t_outstanding_credits);
prepare_to_wait(&journal->j_wait_transaction_locked, &wait,
TASK_UNINTERRUPTIBLE);
tid = transaction->t_tid;
need_to_start = !tid_geq(journal->j_commit_request, tid);
read_unlock(&journal->j_state_lock);
if (need_to_start)
jbd2_log_start_commit(journal, tid);
schedule();
finish_wait(&journal->j_wait_transaction_locked, &wait);
goto repeat;
}
/*
* The commit code assumes that it can get enough log space
* without forcing a checkpoint. This is *critical* for
* correctness: a checkpoint of a buffer which is also
* associated with a committing transaction creates a deadlock,
* so commit simply cannot force through checkpoints.
*
* We must therefore ensure the necessary space in the journal
* *before* starting to dirty potentially checkpointed buffers
* in the new transaction.
*
* The worst part is, any transaction currently committing can
* reduce the free space arbitrarily. Be careful to account for
* those buffers when checkpointing.
*/
/*
* @@@ AKPM: This seems rather over-defensive. We're giving commit
* a _lot_ of headroom: 1/4 of the journal plus the size of
* the committing transaction. Really, we only need to give it
* committing_transaction->t_outstanding_credits plus "enough" for
* the log control blocks.
* Also, this test is inconsistent with the matching one in
* jbd2_journal_extend().
*/
if (__jbd2_log_space_left(journal) < jbd_space_needed(journal)) {
jbd_debug(2, "Handle %p waiting for checkpoint...\n", handle);
atomic_sub(nblocks, &transaction->t_outstanding_credits);
read_unlock(&journal->j_state_lock);
write_lock(&journal->j_state_lock);
if (__jbd2_log_space_left(journal) < jbd_space_needed(journal))
__jbd2_log_wait_for_space(journal);
write_unlock(&journal->j_state_lock);
goto repeat;
}
/* OK, account for the buffers that this operation expects to
* use and add the handle to the running transaction.
*/
update_t_max_wait(transaction, ts);
handle->h_transaction = transaction;
atomic_inc(&transaction->t_updates);
atomic_inc(&transaction->t_handle_count);
jbd_debug(4, "Handle %p given %d credits (total %d, free %d)\n",
handle, nblocks,
atomic_read(&transaction->t_outstanding_credits),
__jbd2_log_space_left(journal));
read_unlock(&journal->j_state_lock);
lock_map_acquire(&handle->h_lockdep_map);
kfree(new_transaction);
return 0;
}
static struct lock_class_key jbd2_handle_key;
/* Allocate a new handle. This should probably be in a slab... */
static handle_t *new_handle(int nblocks)
{
handle_t *handle = jbd2_alloc_handle(GFP_NOFS);
if (!handle)
return NULL;
memset(handle, 0, sizeof(*handle));
handle->h_buffer_credits = nblocks;
handle->h_ref = 1;
lockdep_init_map(&handle->h_lockdep_map, "jbd2_handle",
&jbd2_handle_key, 0);
return handle;
}
/**
* handle_t *jbd2_journal_start() - Obtain a new handle.
* @journal: Journal to start transaction on.
* @nblocks: number of block buffer we might modify
*
* We make sure that the transaction can guarantee at least nblocks of
* modified buffers in the log. We block until the log can guarantee
* that much space.
*
* This function is visible to journal users (like ext3fs), so is not
* called with the journal already locked.
*
* Return a pointer to a newly allocated handle, or an ERR_PTR() value
* on failure.
*/
handle_t *jbd2__journal_start(journal_t *journal, int nblocks, gfp_t gfp_mask)
{
handle_t *handle = journal_current_handle();
int err;
if (!journal)
return ERR_PTR(-EROFS);
if (handle) {
J_ASSERT(handle->h_transaction->t_journal == journal);
handle->h_ref++;
return handle;
}
handle = new_handle(nblocks);
if (!handle)
return ERR_PTR(-ENOMEM);
current->journal_info = handle;
err = start_this_handle(journal, handle, gfp_mask);
if (err < 0) {
jbd2_free_handle(handle);
current->journal_info = NULL;
handle = ERR_PTR(err);
}
return handle;
}
EXPORT_SYMBOL(jbd2__journal_start);
handle_t *jbd2_journal_start(journal_t *journal, int nblocks)
{
return jbd2__journal_start(journal, nblocks, GFP_NOFS);
}
EXPORT_SYMBOL(jbd2_journal_start);
/**
* int jbd2_journal_extend() - extend buffer credits.
* @handle: handle to 'extend'
* @nblocks: nr blocks to try to extend by.
*
* Some transactions, such as large extends and truncates, can be done
* atomically all at once or in several stages. The operation requests
* a credit for a number of buffer modications in advance, but can
* extend its credit if it needs more.
*
* jbd2_journal_extend tries to give the running handle more buffer credits.
* It does not guarantee that allocation - this is a best-effort only.
* The calling process MUST be able to deal cleanly with a failure to
* extend here.
*
* Return 0 on success, non-zero on failure.
*
* return code < 0 implies an error
* return code > 0 implies normal transaction-full status.
*/
int jbd2_journal_extend(handle_t *handle, int nblocks)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
int result;
int wanted;
result = -EIO;
if (is_handle_aborted(handle))
goto out;
result = 1;
read_lock(&journal->j_state_lock);
/* Don't extend a locked-down transaction! */
if (handle->h_transaction->t_state != T_RUNNING) {
jbd_debug(3, "denied handle %p %d blocks: "
"transaction not running\n", handle, nblocks);
goto error_out;
}
spin_lock(&transaction->t_handle_lock);
wanted = atomic_read(&transaction->t_outstanding_credits) + nblocks;
if (wanted > journal->j_max_transaction_buffers) {
jbd_debug(3, "denied handle %p %d blocks: "
"transaction too large\n", handle, nblocks);
goto unlock;
}
if (wanted > __jbd2_log_space_left(journal)) {
jbd_debug(3, "denied handle %p %d blocks: "
"insufficient log space\n", handle, nblocks);
goto unlock;
}
handle->h_buffer_credits += nblocks;
atomic_add(nblocks, &transaction->t_outstanding_credits);
result = 0;
jbd_debug(3, "extended handle %p by %d\n", handle, nblocks);
unlock:
spin_unlock(&transaction->t_handle_lock);
error_out:
read_unlock(&journal->j_state_lock);
out:
return result;
}
/**
* int jbd2_journal_restart() - restart a handle .
* @handle: handle to restart
* @nblocks: nr credits requested
*
* Restart a handle for a multi-transaction filesystem
* operation.
*
* If the jbd2_journal_extend() call above fails to grant new buffer credits
* to a running handle, a call to jbd2_journal_restart will commit the
* handle's transaction so far and reattach the handle to a new
* transaction capabable of guaranteeing the requested number of
* credits.
*/
int jbd2__journal_restart(handle_t *handle, int nblocks, gfp_t gfp_mask)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
tid_t tid;
int need_to_start, ret;
/* If we've had an abort of any type, don't even think about
* actually doing the restart! */
if (is_handle_aborted(handle))
return 0;
/*
* First unlink the handle from its current transaction, and start the
* commit on that.
*/
J_ASSERT(atomic_read(&transaction->t_updates) > 0);
J_ASSERT(journal_current_handle() == handle);
read_lock(&journal->j_state_lock);
spin_lock(&transaction->t_handle_lock);
atomic_sub(handle->h_buffer_credits,
&transaction->t_outstanding_credits);
if (atomic_dec_and_test(&transaction->t_updates))
wake_up(&journal->j_wait_updates);
spin_unlock(&transaction->t_handle_lock);
jbd_debug(2, "restarting handle %p\n", handle);
tid = transaction->t_tid;
need_to_start = !tid_geq(journal->j_commit_request, tid);
read_unlock(&journal->j_state_lock);
if (need_to_start)
jbd2_log_start_commit(journal, tid);
lock_map_release(&handle->h_lockdep_map);
handle->h_buffer_credits = nblocks;
ret = start_this_handle(journal, handle, gfp_mask);
return ret;
}
EXPORT_SYMBOL(jbd2__journal_restart);
int jbd2_journal_restart(handle_t *handle, int nblocks)
{
return jbd2__journal_restart(handle, nblocks, GFP_NOFS);
}
EXPORT_SYMBOL(jbd2_journal_restart);
/**
* void jbd2_journal_lock_updates () - establish a transaction barrier.
* @journal: Journal to establish a barrier on.
*
* This locks out any further updates from being started, and blocks
* until all existing updates have completed, returning only once the
* journal is in a quiescent state with no updates running.
*
* The journal lock should not be held on entry.
*/
void jbd2_journal_lock_updates(journal_t *journal)
{
DEFINE_WAIT(wait);
write_lock(&journal->j_state_lock);
++journal->j_barrier_count;
/* Wait until there are no running updates */
while (1) {
transaction_t *transaction = journal->j_running_transaction;
if (!transaction)
break;
spin_lock(&transaction->t_handle_lock);
prepare_to_wait(&journal->j_wait_updates, &wait,
TASK_UNINTERRUPTIBLE);
if (!atomic_read(&transaction->t_updates)) {
spin_unlock(&transaction->t_handle_lock);
finish_wait(&journal->j_wait_updates, &wait);
break;
}
spin_unlock(&transaction->t_handle_lock);
write_unlock(&journal->j_state_lock);
schedule();
finish_wait(&journal->j_wait_updates, &wait);
write_lock(&journal->j_state_lock);
}
write_unlock(&journal->j_state_lock);
/*
* We have now established a barrier against other normal updates, but
* we also need to barrier against other jbd2_journal_lock_updates() calls
* to make sure that we serialise special journal-locked operations
* too.
*/
mutex_lock(&journal->j_barrier);
}
/**
* void jbd2_journal_unlock_updates (journal_t* journal) - release barrier
* @journal: Journal to release the barrier on.
*
* Release a transaction barrier obtained with jbd2_journal_lock_updates().
*
* Should be called without the journal lock held.
*/
void jbd2_journal_unlock_updates (journal_t *journal)
{
J_ASSERT(journal->j_barrier_count != 0);
mutex_unlock(&journal->j_barrier);
write_lock(&journal->j_state_lock);
--journal->j_barrier_count;
write_unlock(&journal->j_state_lock);
wake_up(&journal->j_wait_transaction_locked);
}
static void warn_dirty_buffer(struct buffer_head *bh)
{
char b[BDEVNAME_SIZE];
printk(KERN_WARNING
"JBD2: Spotted dirty metadata buffer (dev = %s, blocknr = %llu). "
"There's a risk of filesystem corruption in case of system "
"crash.\n",
bdevname(bh->b_bdev, b), (unsigned long long)bh->b_blocknr);
}
/*
* If the buffer is already part of the current transaction, then there
* is nothing we need to do. If it is already part of a prior
* transaction which we are still committing to disk, then we need to
* make sure that we do not overwrite the old copy: we do copy-out to
* preserve the copy going to disk. We also account the buffer against
* the handle's metadata buffer credits (unless the buffer is already
* part of the transaction, that is).
*
*/
static int
do_get_write_access(handle_t *handle, struct journal_head *jh,
int force_copy)
{
struct buffer_head *bh;
transaction_t *transaction;
journal_t *journal;
int error;
char *frozen_buffer = NULL;
int need_copy = 0;
if (is_handle_aborted(handle))
return -EROFS;
transaction = handle->h_transaction;
journal = transaction->t_journal;
jbd_debug(5, "journal_head %p, force_copy %d\n", jh, force_copy);
JBUFFER_TRACE(jh, "entry");
repeat:
bh = jh2bh(jh);
/* @@@ Need to check for errors here at some point. */
lock_buffer(bh);
jbd_lock_bh_state(bh);
/* We now hold the buffer lock so it is safe to query the buffer
* state. Is the buffer dirty?
*
* If so, there are two possibilities. The buffer may be
* non-journaled, and undergoing a quite legitimate writeback.
* Otherwise, it is journaled, and we don't expect dirty buffers
* in that state (the buffers should be marked JBD_Dirty
* instead.) So either the IO is being done under our own
* control and this is a bug, or it's a third party IO such as
* dump(8) (which may leave the buffer scheduled for read ---
* ie. locked but not dirty) or tune2fs (which may actually have
* the buffer dirtied, ugh.) */
if (buffer_dirty(bh)) {
/*
* First question: is this buffer already part of the current
* transaction or the existing committing transaction?
*/
if (jh->b_transaction) {
J_ASSERT_JH(jh,
jh->b_transaction == transaction ||
jh->b_transaction ==
journal->j_committing_transaction);
if (jh->b_next_transaction)
J_ASSERT_JH(jh, jh->b_next_transaction ==
transaction);
warn_dirty_buffer(bh);
}
/*
* In any case we need to clean the dirty flag and we must
* do it under the buffer lock to be sure we don't race
* with running write-out.
*/
JBUFFER_TRACE(jh, "Journalling dirty buffer");
clear_buffer_dirty(bh);
set_buffer_jbddirty(bh);
}
unlock_buffer(bh);
error = -EROFS;
if (is_handle_aborted(handle)) {
jbd_unlock_bh_state(bh);
goto out;
}
error = 0;
/*
* The buffer is already part of this transaction if b_transaction or
* b_next_transaction points to it
*/
if (jh->b_transaction == transaction ||
jh->b_next_transaction == transaction)
goto done;
/*
* this is the first time this transaction is touching this buffer,
* reset the modified flag
*/
jh->b_modified = 0;
/*
* If there is already a copy-out version of this buffer, then we don't
* need to make another one
*/
if (jh->b_frozen_data) {
JBUFFER_TRACE(jh, "has frozen data");
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
jh->b_next_transaction = transaction;
goto done;
}
/* Is there data here we need to preserve? */
if (jh->b_transaction && jh->b_transaction != transaction) {
JBUFFER_TRACE(jh, "owned by older transaction");
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
J_ASSERT_JH(jh, jh->b_transaction ==
journal->j_committing_transaction);
/* There is one case we have to be very careful about.
* If the committing transaction is currently writing
* this buffer out to disk and has NOT made a copy-out,
* then we cannot modify the buffer contents at all
* right now. The essence of copy-out is that it is the
* extra copy, not the primary copy, which gets
* journaled. If the primary copy is already going to
* disk then we cannot do copy-out here. */
if (jh->b_jlist == BJ_Shadow) {
DEFINE_WAIT_BIT(wait, &bh->b_state, BH_Unshadow);
wait_queue_head_t *wqh;
wqh = bit_waitqueue(&bh->b_state, BH_Unshadow);
JBUFFER_TRACE(jh, "on shadow: sleep");
jbd_unlock_bh_state(bh);
/* commit wakes up all shadow buffers after IO */
for ( ; ; ) {
prepare_to_wait(wqh, &wait.wait,
TASK_UNINTERRUPTIBLE);
if (jh->b_jlist != BJ_Shadow)
break;
schedule();
}
finish_wait(wqh, &wait.wait);
goto repeat;
}
/* Only do the copy if the currently-owning transaction
* still needs it. If it is on the Forget list, the
* committing transaction is past that stage. The
* buffer had better remain locked during the kmalloc,
* but that should be true --- we hold the journal lock
* still and the buffer is already on the BUF_JOURNAL
* list so won't be flushed.
*
* Subtle point, though: if this is a get_undo_access,
* then we will be relying on the frozen_data to contain
* the new value of the committed_data record after the
* transaction, so we HAVE to force the frozen_data copy
* in that case. */
if (jh->b_jlist != BJ_Forget || force_copy) {
JBUFFER_TRACE(jh, "generate frozen data");
if (!frozen_buffer) {
JBUFFER_TRACE(jh, "allocate memory for buffer");
jbd_unlock_bh_state(bh);
frozen_buffer =
jbd2_alloc(jh2bh(jh)->b_size,
GFP_NOFS);
if (!frozen_buffer) {
printk(KERN_EMERG
"%s: OOM for frozen_buffer\n",
__func__);
JBUFFER_TRACE(jh, "oom!");
error = -ENOMEM;
jbd_lock_bh_state(bh);
goto done;
}
goto repeat;
}
jh->b_frozen_data = frozen_buffer;
frozen_buffer = NULL;
need_copy = 1;
}
jh->b_next_transaction = transaction;
}
/*
* Finally, if the buffer is not journaled right now, we need to make
* sure it doesn't get written to disk before the caller actually
* commits the new data
*/
if (!jh->b_transaction) {
JBUFFER_TRACE(jh, "no transaction");
J_ASSERT_JH(jh, !jh->b_next_transaction);
JBUFFER_TRACE(jh, "file as BJ_Reserved");
spin_lock(&journal->j_list_lock);
__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
spin_unlock(&journal->j_list_lock);
}
done:
if (need_copy) {
struct page *page;
int offset;
char *source;
J_EXPECT_JH(jh, buffer_uptodate(jh2bh(jh)),
"Possible IO failure.\n");
page = jh2bh(jh)->b_page;
offset = offset_in_page(jh2bh(jh)->b_data);
source = kmap_atomic(page, KM_USER0);
/* Fire data frozen trigger just before we copy the data */
jbd2_buffer_frozen_trigger(jh, source + offset,
jh->b_triggers);
memcpy(jh->b_frozen_data, source+offset, jh2bh(jh)->b_size);
kunmap_atomic(source, KM_USER0);
/*
* Now that the frozen data is saved off, we need to store
* any matching triggers.
*/
jh->b_frozen_triggers = jh->b_triggers;
}
jbd_unlock_bh_state(bh);
/*
* If we are about to journal a buffer, then any revoke pending on it is
* no longer valid
*/
jbd2_journal_cancel_revoke(handle, jh);
out:
if (unlikely(frozen_buffer)) /* It's usually NULL */
jbd2_free(frozen_buffer, bh->b_size);
JBUFFER_TRACE(jh, "exit");
return error;
}
/**
* int jbd2_journal_get_write_access() - notify intent to modify a buffer for metadata (not data) update.
* @handle: transaction to add buffer modifications to
* @bh: bh to be used for metadata writes
*
* Returns an error code or 0 on success.
*
* In full data journalling mode the buffer may be of type BJ_AsyncData,
* because we're write()ing a buffer which is also part of a shared mapping.
*/
int jbd2_journal_get_write_access(handle_t *handle, struct buffer_head *bh)
{
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
int rc;
/* We do not want to get caught playing with fields which the
* log thread also manipulates. Make sure that the buffer
* completes any outstanding IO before proceeding. */
rc = do_get_write_access(handle, jh, 0);
jbd2_journal_put_journal_head(jh);
return rc;
}
/*
* When the user wants to journal a newly created buffer_head
* (ie. getblk() returned a new buffer and we are going to populate it
* manually rather than reading off disk), then we need to keep the
* buffer_head locked until it has been completely filled with new
* data. In this case, we should be able to make the assertion that
* the bh is not already part of an existing transaction.
*
* The buffer should already be locked by the caller by this point.
* There is no lock ranking violation: it was a newly created,
* unlocked buffer beforehand. */
/**
* int jbd2_journal_get_create_access () - notify intent to use newly created bh
* @handle: transaction to new buffer to
* @bh: new buffer.
*
* Call this if you create a new bh.
*/
int jbd2_journal_get_create_access(handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
int err;
jbd_debug(5, "journal_head %p\n", jh);
err = -EROFS;
if (is_handle_aborted(handle))
goto out;
err = 0;
JBUFFER_TRACE(jh, "entry");
/*
* The buffer may already belong to this transaction due to pre-zeroing
* in the filesystem's new_block code. It may also be on the previous,
* committing transaction's lists, but it HAS to be in Forget state in
* that case: the transaction must have deleted the buffer for it to be
* reused here.
*/
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
J_ASSERT_JH(jh, (jh->b_transaction == transaction ||
jh->b_transaction == NULL ||
(jh->b_transaction == journal->j_committing_transaction &&
jh->b_jlist == BJ_Forget)));
J_ASSERT_JH(jh, jh->b_next_transaction == NULL);
J_ASSERT_JH(jh, buffer_locked(jh2bh(jh)));
if (jh->b_transaction == NULL) {
/*
* Previous jbd2_journal_forget() could have left the buffer
* with jbddirty bit set because it was being committed. When
* the commit finished, we've filed the buffer for
* checkpointing and marked it dirty. Now we are reallocating
* the buffer so the transaction freeing it must have
* committed and so it's safe to clear the dirty bit.
*/
clear_buffer_dirty(jh2bh(jh));
/* first access by this transaction */
jh->b_modified = 0;
JBUFFER_TRACE(jh, "file as BJ_Reserved");
__jbd2_journal_file_buffer(jh, transaction, BJ_Reserved);
} else if (jh->b_transaction == journal->j_committing_transaction) {
/* first access by this transaction */
jh->b_modified = 0;
JBUFFER_TRACE(jh, "set next transaction");
jh->b_next_transaction = transaction;
}
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
/*
* akpm: I added this. ext3_alloc_branch can pick up new indirect
* blocks which contain freed but then revoked metadata. We need
* to cancel the revoke in case we end up freeing it yet again
* and the reallocating as data - this would cause a second revoke,
* which hits an assertion error.
*/
JBUFFER_TRACE(jh, "cancelling revoke");
jbd2_journal_cancel_revoke(handle, jh);
out:
jbd2_journal_put_journal_head(jh);
return err;
}
/**
* int jbd2_journal_get_undo_access() - Notify intent to modify metadata with
* non-rewindable consequences
* @handle: transaction
* @bh: buffer to undo
*
* Sometimes there is a need to distinguish between metadata which has
* been committed to disk and that which has not. The ext3fs code uses
* this for freeing and allocating space, we have to make sure that we
* do not reuse freed space until the deallocation has been committed,
* since if we overwrote that space we would make the delete
* un-rewindable in case of a crash.
*
* To deal with that, jbd2_journal_get_undo_access requests write access to a
* buffer for parts of non-rewindable operations such as delete
* operations on the bitmaps. The journaling code must keep a copy of
* the buffer's contents prior to the undo_access call until such time
* as we know that the buffer has definitely been committed to disk.
*
* We never need to know which transaction the committed data is part
* of, buffers touched here are guaranteed to be dirtied later and so
* will be committed to a new transaction in due course, at which point
* we can discard the old committed data pointer.
*
* Returns error number or 0 on success.
*/
int jbd2_journal_get_undo_access(handle_t *handle, struct buffer_head *bh)
{
int err;
struct journal_head *jh = jbd2_journal_add_journal_head(bh);
char *committed_data = NULL;
JBUFFER_TRACE(jh, "entry");
/*
* Do this first --- it can drop the journal lock, so we want to
* make sure that obtaining the committed_data is done
* atomically wrt. completion of any outstanding commits.
*/
err = do_get_write_access(handle, jh, 1);
if (err)
goto out;
repeat:
if (!jh->b_committed_data) {
committed_data = jbd2_alloc(jh2bh(jh)->b_size, GFP_NOFS);
if (!committed_data) {
printk(KERN_EMERG "%s: No memory for committed data\n",
__func__);
err = -ENOMEM;
goto out;
}
}
jbd_lock_bh_state(bh);
if (!jh->b_committed_data) {
/* Copy out the current buffer contents into the
* preserved, committed copy. */
JBUFFER_TRACE(jh, "generate b_committed data");
if (!committed_data) {
jbd_unlock_bh_state(bh);
goto repeat;
}
jh->b_committed_data = committed_data;
committed_data = NULL;
memcpy(jh->b_committed_data, bh->b_data, bh->b_size);
}
jbd_unlock_bh_state(bh);
out:
jbd2_journal_put_journal_head(jh);
if (unlikely(committed_data))
jbd2_free(committed_data, bh->b_size);
return err;
}
/**
* void jbd2_journal_set_triggers() - Add triggers for commit writeout
* @bh: buffer to trigger on
* @type: struct jbd2_buffer_trigger_type containing the trigger(s).
*
* Set any triggers on this journal_head. This is always safe, because
* triggers for a committing buffer will be saved off, and triggers for
* a running transaction will match the buffer in that transaction.
*
* Call with NULL to clear the triggers.
*/
void jbd2_journal_set_triggers(struct buffer_head *bh,
struct jbd2_buffer_trigger_type *type)
{
struct journal_head *jh = bh2jh(bh);
jh->b_triggers = type;
}
void jbd2_buffer_frozen_trigger(struct journal_head *jh, void *mapped_data,
struct jbd2_buffer_trigger_type *triggers)
{
struct buffer_head *bh = jh2bh(jh);
if (!triggers || !triggers->t_frozen)
return;
triggers->t_frozen(triggers, bh, mapped_data, bh->b_size);
}
void jbd2_buffer_abort_trigger(struct journal_head *jh,
struct jbd2_buffer_trigger_type *triggers)
{
if (!triggers || !triggers->t_abort)
return;
triggers->t_abort(triggers, jh2bh(jh));
}
/**
* int jbd2_journal_dirty_metadata() - mark a buffer as containing dirty metadata
* @handle: transaction to add buffer to.
* @bh: buffer to mark
*
* mark dirty metadata which needs to be journaled as part of the current
* transaction.
*
* The buffer must have previously had jbd2_journal_get_write_access()
* called so that it has a valid journal_head attached to the buffer
* head.
*
* The buffer is placed on the transaction's metadata list and is marked
* as belonging to the transaction.
*
* Returns error number or 0 on success.
*
* Special care needs to be taken if the buffer already belongs to the
* current committing transaction (in which case we should have frozen
* data present for that commit). In that case, we don't relink the
* buffer: that only gets done when the old transaction finally
* completes its commit.
*/
int jbd2_journal_dirty_metadata(handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh = bh2jh(bh);
int ret = 0;
jbd_debug(5, "journal_head %p\n", jh);
JBUFFER_TRACE(jh, "entry");
if (is_handle_aborted(handle))
goto out;
if (!buffer_jbd(bh)) {
ret = -EUCLEAN;
goto out;
}
jbd_lock_bh_state(bh);
if (jh->b_modified == 0) {
/*
* This buffer's got modified and becoming part
* of the transaction. This needs to be done
* once a transaction -bzzz
*/
jh->b_modified = 1;
J_ASSERT_JH(jh, handle->h_buffer_credits > 0);
handle->h_buffer_credits--;
}
/*
* fastpath, to avoid expensive locking. If this buffer is already
* on the running transaction's metadata list there is nothing to do.
* Nobody can take it off again because there is a handle open.
* I _think_ we're OK here with SMP barriers - a mistaken decision will
* result in this test being false, so we go in and take the locks.
*/
if (jh->b_transaction == transaction && jh->b_jlist == BJ_Metadata) {
JBUFFER_TRACE(jh, "fastpath");
if (unlikely(jh->b_transaction !=
journal->j_running_transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_transaction (%llu, %p, %u) != "
"journal->j_running_transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_transaction,
jh->b_transaction ? jh->b_transaction->t_tid : 0,
journal->j_running_transaction,
journal->j_running_transaction ?
journal->j_running_transaction->t_tid : 0);
ret = -EINVAL;
}
goto out_unlock_bh;
}
set_buffer_jbddirty(bh);
/*
* Metadata already on the current transaction list doesn't
* need to be filed. Metadata on another transaction's list must
* be committing, and will be refiled once the commit completes:
* leave it alone for now.
*/
if (jh->b_transaction != transaction) {
JBUFFER_TRACE(jh, "already on other transaction");
if (unlikely(jh->b_transaction !=
journal->j_committing_transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_transaction (%llu, %p, %u) != "
"journal->j_committing_transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_transaction,
jh->b_transaction ? jh->b_transaction->t_tid : 0,
journal->j_committing_transaction,
journal->j_committing_transaction ?
journal->j_committing_transaction->t_tid : 0);
ret = -EINVAL;
}
if (unlikely(jh->b_next_transaction != transaction)) {
printk(KERN_EMERG "JBD: %s: "
"jh->b_next_transaction (%llu, %p, %u) != "
"transaction (%p, %u)",
journal->j_devname,
(unsigned long long) bh->b_blocknr,
jh->b_next_transaction,
jh->b_next_transaction ?
jh->b_next_transaction->t_tid : 0,
transaction, transaction->t_tid);
ret = -EINVAL;
}
/* And this case is illegal: we can't reuse another
* transaction's data buffer, ever. */
goto out_unlock_bh;
}
/* That test should have eliminated the following case: */
J_ASSERT_JH(jh, jh->b_frozen_data == NULL);
JBUFFER_TRACE(jh, "file as BJ_Metadata");
spin_lock(&journal->j_list_lock);
__jbd2_journal_file_buffer(jh, handle->h_transaction, BJ_Metadata);
spin_unlock(&journal->j_list_lock);
out_unlock_bh:
jbd_unlock_bh_state(bh);
out:
JBUFFER_TRACE(jh, "exit");
WARN_ON(ret); /* All errors are bugs, so dump the stack */
return ret;
}
/*
* jbd2_journal_release_buffer: undo a get_write_access without any buffer
* updates, if the update decided in the end that it didn't need access.
*
*/
void
jbd2_journal_release_buffer(handle_t *handle, struct buffer_head *bh)
{
BUFFER_TRACE(bh, "entry");
}
/**
* void jbd2_journal_forget() - bforget() for potentially-journaled buffers.
* @handle: transaction handle
* @bh: bh to 'forget'
*
* We can only do the bforget if there are no commits pending against the
* buffer. If the buffer is dirty in the current running transaction we
* can safely unlink it.
*
* bh may not be a journalled buffer at all - it may be a non-JBD
* buffer which came off the hashtable. Check for this.
*
* Decrements bh->b_count by one.
*
* Allow this call even if the handle has aborted --- it may be part of
* the caller's cleanup after an abort.
*/
int jbd2_journal_forget (handle_t *handle, struct buffer_head *bh)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
struct journal_head *jh;
int drop_reserve = 0;
int err = 0;
int was_modified = 0;
BUFFER_TRACE(bh, "entry");
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
if (!buffer_jbd(bh))
goto not_jbd;
jh = bh2jh(bh);
/* Critical error: attempting to delete a bitmap buffer, maybe?
* Don't do any jbd operations, and return an error. */
if (!J_EXPECT_JH(jh, !jh->b_committed_data,
"inconsistent data on disk")) {
err = -EIO;
goto not_jbd;
}
/* keep track of wether or not this transaction modified us */
was_modified = jh->b_modified;
/*
* The buffer's going from the transaction, we must drop
* all references -bzzz
*/
jh->b_modified = 0;
if (jh->b_transaction == handle->h_transaction) {
J_ASSERT_JH(jh, !jh->b_frozen_data);
/* If we are forgetting a buffer which is already part
* of this transaction, then we can just drop it from
* the transaction immediately. */
clear_buffer_dirty(bh);
clear_buffer_jbddirty(bh);
JBUFFER_TRACE(jh, "belongs to current transaction: unfile");
/*
* we only want to drop a reference if this transaction
* modified the buffer
*/
if (was_modified)
drop_reserve = 1;
/*
* We are no longer going to journal this buffer.
* However, the commit of this transaction is still
* important to the buffer: the delete that we are now
* processing might obsolete an old log entry, so by
* committing, we can satisfy the buffer's checkpoint.
*
* So, if we have a checkpoint on the buffer, we should
* now refile the buffer on our BJ_Forget list so that
* we know to remove the checkpoint after we commit.
*/
if (jh->b_cp_transaction) {
__jbd2_journal_temp_unlink_buffer(jh);
__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
} else {
__jbd2_journal_unfile_buffer(jh);
if (!buffer_jbd(bh)) {
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__bforget(bh);
goto drop;
}
}
} else if (jh->b_transaction) {
J_ASSERT_JH(jh, (jh->b_transaction ==
journal->j_committing_transaction));
/* However, if the buffer is still owned by a prior
* (committing) transaction, we can't drop it yet... */
JBUFFER_TRACE(jh, "belongs to older transaction");
/* ... but we CAN drop it from the new transaction if we
* have also modified it since the original commit. */
if (jh->b_next_transaction) {
J_ASSERT(jh->b_next_transaction == transaction);
jh->b_next_transaction = NULL;
/*
* only drop a reference if this transaction modified
* the buffer
*/
if (was_modified)
drop_reserve = 1;
}
}
not_jbd:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__brelse(bh);
drop:
if (drop_reserve) {
/* no need to reserve log space for this block -bzzz */
handle->h_buffer_credits++;
}
return err;
}
/**
* int jbd2_journal_stop() - complete a transaction
* @handle: tranaction to complete.
*
* All done for a particular handle.
*
* There is not much action needed here. We just return any remaining
* buffer credits to the transaction and remove the handle. The only
* complication is that we need to start a commit operation if the
* filesystem is marked for synchronous update.
*
* jbd2_journal_stop itself will not usually return an error, but it may
* do so in unusual circumstances. In particular, expect it to
* return -EIO if a jbd2_journal_abort has been executed since the
* transaction began.
*/
int jbd2_journal_stop(handle_t *handle)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
int err, wait_for_commit = 0;
tid_t tid;
pid_t pid;
J_ASSERT(journal_current_handle() == handle);
if (is_handle_aborted(handle))
err = -EIO;
else {
J_ASSERT(atomic_read(&transaction->t_updates) > 0);
err = 0;
}
if (--handle->h_ref > 0) {
jbd_debug(4, "h_ref %d -> %d\n", handle->h_ref + 1,
handle->h_ref);
return err;
}
jbd_debug(4, "Handle %p going down\n", handle);
/*
* Implement synchronous transaction batching. If the handle
* was synchronous, don't force a commit immediately. Let's
* yield and let another thread piggyback onto this
* transaction. Keep doing that while new threads continue to
* arrive. It doesn't cost much - we're about to run a commit
* and sleep on IO anyway. Speeds up many-threaded, many-dir
* operations by 30x or more...
*
* We try and optimize the sleep time against what the
* underlying disk can do, instead of having a static sleep
* time. This is useful for the case where our storage is so
* fast that it is more optimal to go ahead and force a flush
* and wait for the transaction to be committed than it is to
* wait for an arbitrary amount of time for new writers to
* join the transaction. We achieve this by measuring how
* long it takes to commit a transaction, and compare it with
* how long this transaction has been running, and if run time
* < commit time then we sleep for the delta and commit. This
* greatly helps super fast disks that would see slowdowns as
* more threads started doing fsyncs.
*
* But don't do this if this process was the most recent one
* to perform a synchronous write. We do this to detect the
* case where a single process is doing a stream of sync
* writes. No point in waiting for joiners in that case.
*/
pid = current->pid;
if (handle->h_sync && journal->j_last_sync_writer != pid) {
u64 commit_time, trans_time;
journal->j_last_sync_writer = pid;
read_lock(&journal->j_state_lock);
commit_time = journal->j_average_commit_time;
read_unlock(&journal->j_state_lock);
trans_time = ktime_to_ns(ktime_sub(ktime_get(),
transaction->t_start_time));
commit_time = max_t(u64, commit_time,
1000*journal->j_min_batch_time);
commit_time = min_t(u64, commit_time,
1000*journal->j_max_batch_time);
if (trans_time < commit_time) {
ktime_t expires = ktime_add_ns(ktime_get(),
commit_time);
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_hrtimeout(&expires, HRTIMER_MODE_ABS);
}
}
if (handle->h_sync)
transaction->t_synchronous_commit = 1;
current->journal_info = NULL;
atomic_sub(handle->h_buffer_credits,
&transaction->t_outstanding_credits);
/*
* If the handle is marked SYNC, we need to set another commit
* going! We also want to force a commit if the current
* transaction is occupying too much of the log, or if the
* transaction is too old now.
*/
if (handle->h_sync ||
(atomic_read(&transaction->t_outstanding_credits) >
journal->j_max_transaction_buffers) ||
time_after_eq(jiffies, transaction->t_expires)) {
/* Do this even for aborted journals: an abort still
* completes the commit thread, it just doesn't write
* anything to disk. */
jbd_debug(2, "transaction too old, requesting commit for "
"handle %p\n", handle);
/* This is non-blocking */
jbd2_log_start_commit(journal, transaction->t_tid);
/*
* Special case: JBD2_SYNC synchronous updates require us
* to wait for the commit to complete.
*/
if (handle->h_sync && !(current->flags & PF_MEMALLOC))
wait_for_commit = 1;
}
/*
* Once we drop t_updates, if it goes to zero the transaction
* could start committing on us and eventually disappear. So
* once we do this, we must not dereference transaction
* pointer again.
*/
tid = transaction->t_tid;
if (atomic_dec_and_test(&transaction->t_updates)) {
wake_up(&journal->j_wait_updates);
if (journal->j_barrier_count)
wake_up(&journal->j_wait_transaction_locked);
}
if (wait_for_commit)
err = jbd2_log_wait_commit(journal, tid);
lock_map_release(&handle->h_lockdep_map);
jbd2_free_handle(handle);
return err;
}
/**
* int jbd2_journal_force_commit() - force any uncommitted transactions
* @journal: journal to force
*
* For synchronous operations: force any uncommitted transactions
* to disk. May seem kludgy, but it reuses all the handle batching
* code in a very simple manner.
*/
int jbd2_journal_force_commit(journal_t *journal)
{
handle_t *handle;
int ret;
handle = jbd2_journal_start(journal, 1);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
} else {
handle->h_sync = 1;
ret = jbd2_journal_stop(handle);
}
return ret;
}
/*
*
* List management code snippets: various functions for manipulating the
* transaction buffer lists.
*
*/
/*
* Append a buffer to a transaction list, given the transaction's list head
* pointer.
*
* j_list_lock is held.
*
* jbd_lock_bh_state(jh2bh(jh)) is held.
*/
static inline void
__blist_add_buffer(struct journal_head **list, struct journal_head *jh)
{
if (!*list) {
jh->b_tnext = jh->b_tprev = jh;
*list = jh;
} else {
/* Insert at the tail of the list to preserve order */
struct journal_head *first = *list, *last = first->b_tprev;
jh->b_tprev = last;
jh->b_tnext = first;
last->b_tnext = first->b_tprev = jh;
}
}
/*
* Remove a buffer from a transaction list, given the transaction's list
* head pointer.
*
* Called with j_list_lock held, and the journal may not be locked.
*
* jbd_lock_bh_state(jh2bh(jh)) is held.
*/
static inline void
__blist_del_buffer(struct journal_head **list, struct journal_head *jh)
{
if (*list == jh) {
*list = jh->b_tnext;
if (*list == jh)
*list = NULL;
}
jh->b_tprev->b_tnext = jh->b_tnext;
jh->b_tnext->b_tprev = jh->b_tprev;
}
/*
* Remove a buffer from the appropriate transaction list.
*
* Note that this function can *change* the value of
* bh->b_transaction->t_buffers, t_forget, t_iobuf_list, t_shadow_list,
* t_log_list or t_reserved_list. If the caller is holding onto a copy of one
* of these pointers, it could go bad. Generally the caller needs to re-read
* the pointer from the transaction_t.
*
* Called under j_list_lock. The journal may not be locked.
*/
void __jbd2_journal_temp_unlink_buffer(struct journal_head *jh)
{
struct journal_head **list = NULL;
transaction_t *transaction;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
transaction = jh->b_transaction;
if (transaction)
assert_spin_locked(&transaction->t_journal->j_list_lock);
J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
if (jh->b_jlist != BJ_None)
J_ASSERT_JH(jh, transaction != NULL);
switch (jh->b_jlist) {
case BJ_None:
return;
case BJ_Metadata:
transaction->t_nr_buffers--;
J_ASSERT_JH(jh, transaction->t_nr_buffers >= 0);
list = &transaction->t_buffers;
break;
case BJ_Forget:
list = &transaction->t_forget;
break;
case BJ_IO:
list = &transaction->t_iobuf_list;
break;
case BJ_Shadow:
list = &transaction->t_shadow_list;
break;
case BJ_LogCtl:
list = &transaction->t_log_list;
break;
case BJ_Reserved:
list = &transaction->t_reserved_list;
break;
}
__blist_del_buffer(list, jh);
jh->b_jlist = BJ_None;
if (test_clear_buffer_jbddirty(bh))
mark_buffer_dirty(bh); /* Expose it to the VM */
}
/*
* Remove buffer from all transactions.
*
* Called with bh_state lock and j_list_lock
*
* jh and bh may be already freed when this function returns.
*/
static void __jbd2_journal_unfile_buffer(struct journal_head *jh)
{
__jbd2_journal_temp_unlink_buffer(jh);
jh->b_transaction = NULL;
jbd2_journal_put_journal_head(jh);
}
void jbd2_journal_unfile_buffer(journal_t *journal, struct journal_head *jh)
{
struct buffer_head *bh = jh2bh(jh);
/* Get reference so that buffer cannot be freed before we unlock it */
get_bh(bh);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
__jbd2_journal_unfile_buffer(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
__brelse(bh);
}
/*
* Called from jbd2_journal_try_to_free_buffers().
*
* Called under jbd_lock_bh_state(bh)
*/
static void
__journal_try_to_free_buffer(journal_t *journal, struct buffer_head *bh)
{
struct journal_head *jh;
jh = bh2jh(bh);
if (buffer_locked(bh) || buffer_dirty(bh))
goto out;
if (jh->b_next_transaction != NULL)
goto out;
spin_lock(&journal->j_list_lock);
if (jh->b_cp_transaction != NULL && jh->b_transaction == NULL) {
/* written-back checkpointed metadata buffer */
if (jh->b_jlist == BJ_None) {
JBUFFER_TRACE(jh, "remove from checkpoint list");
__jbd2_journal_remove_checkpoint(jh);
}
}
spin_unlock(&journal->j_list_lock);
out:
return;
}
/**
* int jbd2_journal_try_to_free_buffers() - try to free page buffers.
* @journal: journal for operation
* @page: to try and free
* @gfp_mask: we use the mask to detect how hard should we try to release
* buffers. If __GFP_WAIT and __GFP_FS is set, we wait for commit code to
* release the buffers.
*
*
* For all the buffers on this page,
* if they are fully written out ordered data, move them onto BUF_CLEAN
* so try_to_free_buffers() can reap them.
*
* This function returns non-zero if we wish try_to_free_buffers()
* to be called. We do this if the page is releasable by try_to_free_buffers().
* We also do it if the page has locked or dirty buffers and the caller wants
* us to perform sync or async writeout.
*
* This complicates JBD locking somewhat. We aren't protected by the
* BKL here. We wish to remove the buffer from its committing or
* running transaction's ->t_datalist via __jbd2_journal_unfile_buffer.
*
* This may *change* the value of transaction_t->t_datalist, so anyone
* who looks at t_datalist needs to lock against this function.
*
* Even worse, someone may be doing a jbd2_journal_dirty_data on this
* buffer. So we need to lock against that. jbd2_journal_dirty_data()
* will come out of the lock with the buffer dirty, which makes it
* ineligible for release here.
*
* Who else is affected by this? hmm... Really the only contender
* is do_get_write_access() - it could be looking at the buffer while
* journal_try_to_free_buffer() is changing its state. But that
* cannot happen because we never reallocate freed data as metadata
* while the data is part of a transaction. Yes?
*
* Return 0 on failure, 1 on success
*/
int jbd2_journal_try_to_free_buffers(journal_t *journal,
struct page *page, gfp_t gfp_mask)
{
struct buffer_head *head;
struct buffer_head *bh;
int ret = 0;
J_ASSERT(PageLocked(page));
head = page_buffers(page);
bh = head;
do {
struct journal_head *jh;
/*
* We take our own ref against the journal_head here to avoid
* having to add tons of locking around each instance of
* jbd2_journal_put_journal_head().
*/
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
continue;
jbd_lock_bh_state(bh);
__journal_try_to_free_buffer(journal, bh);
jbd2_journal_put_journal_head(jh);
jbd_unlock_bh_state(bh);
if (buffer_jbd(bh))
goto busy;
} while ((bh = bh->b_this_page) != head);
ret = try_to_free_buffers(page);
busy:
return ret;
}
/*
* This buffer is no longer needed. If it is on an older transaction's
* checkpoint list we need to record it on this transaction's forget list
* to pin this buffer (and hence its checkpointing transaction) down until
* this transaction commits. If the buffer isn't on a checkpoint list, we
* release it.
* Returns non-zero if JBD no longer has an interest in the buffer.
*
* Called under j_list_lock.
*
* Called under jbd_lock_bh_state(bh).
*/
static int __dispose_buffer(struct journal_head *jh, transaction_t *transaction)
{
int may_free = 1;
struct buffer_head *bh = jh2bh(jh);
if (jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "on running+cp transaction");
__jbd2_journal_temp_unlink_buffer(jh);
/*
* We don't want to write the buffer anymore, clear the
* bit so that we don't confuse checks in
* __journal_file_buffer
*/
clear_buffer_dirty(bh);
__jbd2_journal_file_buffer(jh, transaction, BJ_Forget);
may_free = 0;
} else {
JBUFFER_TRACE(jh, "on running transaction");
__jbd2_journal_unfile_buffer(jh);
}
return may_free;
}
/*
* jbd2_journal_invalidatepage
*
* This code is tricky. It has a number of cases to deal with.
*
* There are two invariants which this code relies on:
*
* i_size must be updated on disk before we start calling invalidatepage on the
* data.
*
* This is done in ext3 by defining an ext3_setattr method which
* updates i_size before truncate gets going. By maintaining this
* invariant, we can be sure that it is safe to throw away any buffers
* attached to the current transaction: once the transaction commits,
* we know that the data will not be needed.
*
* Note however that we can *not* throw away data belonging to the
* previous, committing transaction!
*
* Any disk blocks which *are* part of the previous, committing
* transaction (and which therefore cannot be discarded immediately) are
* not going to be reused in the new running transaction
*
* The bitmap committed_data images guarantee this: any block which is
* allocated in one transaction and removed in the next will be marked
* as in-use in the committed_data bitmap, so cannot be reused until
* the next transaction to delete the block commits. This means that
* leaving committing buffers dirty is quite safe: the disk blocks
* cannot be reallocated to a different file and so buffer aliasing is
* not possible.
*
*
* The above applies mainly to ordered data mode. In writeback mode we
* don't make guarantees about the order in which data hits disk --- in
* particular we don't guarantee that new dirty data is flushed before
* transaction commit --- so it is always safe just to discard data
* immediately in that mode. --sct
*/
/*
* The journal_unmap_buffer helper function returns zero if the buffer
* concerned remains pinned as an anonymous buffer belonging to an older
* transaction.
*
* We're outside-transaction here. Either or both of j_running_transaction
* and j_committing_transaction may be NULL.
*/
static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)
{
transaction_t *transaction;
struct journal_head *jh;
int may_free = 1;
int ret;
BUFFER_TRACE(bh, "entry");
/*
* It is safe to proceed here without the j_list_lock because the
* buffers cannot be stolen by try_to_free_buffers as long as we are
* holding the page lock. --sct
*/
if (!buffer_jbd(bh))
goto zap_buffer_unlocked;
/* OK, we have data buffer in journaled mode */
write_lock(&journal->j_state_lock);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
goto zap_buffer_no_jh;
/*
* We cannot remove the buffer from checkpoint lists until the
* transaction adding inode to orphan list (let's call it T)
* is committed. Otherwise if the transaction changing the
* buffer would be cleaned from the journal before T is
* committed, a crash will cause that the correct contents of
* the buffer will be lost. On the other hand we have to
* clear the buffer dirty bit at latest at the moment when the
* transaction marking the buffer as freed in the filesystem
* structures is committed because from that moment on the
* buffer can be reallocated and used by a different page.
* Since the block hasn't been freed yet but the inode has
* already been added to orphan list, it is safe for us to add
* the buffer to BJ_Forget list of the newest transaction.
*/
transaction = jh->b_transaction;
if (transaction == NULL) {
/* First case: not on any transaction. If it
* has no checkpoint link, then we can zap it:
* it's a writeback-mode buffer so we don't care
* if it hits disk safely. */
if (!jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "not on any transaction: zap");
goto zap_buffer;
}
if (!buffer_dirty(bh)) {
/* bdflush has written it. We can drop it now */
goto zap_buffer;
}
/* OK, it must be in the journal but still not
* written fully to disk: it's metadata or
* journaled data... */
if (journal->j_running_transaction) {
/* ... and once the current transaction has
* committed, the buffer won't be needed any
* longer. */
JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
ret = __dispose_buffer(jh,
journal->j_running_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* There is no currently-running transaction. So the
* orphan record which we wrote for this file must have
* passed into commit. We must attach this buffer to
* the committing transaction, if it exists. */
if (journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "give to committing trans");
ret = __dispose_buffer(jh,
journal->j_committing_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* The orphan record's transaction has
* committed. We can cleanse this buffer */
clear_buffer_jbddirty(bh);
goto zap_buffer;
}
}
} else if (transaction == journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "on committing transaction");
/*
* The buffer is committing, we simply cannot touch
* it. So we just set j_next_transaction to the
* running transaction (if there is one) and mark
* buffer as freed so that commit code knows it should
* clear dirty bits when it is done with the buffer.
*/
set_buffer_freed(bh);
if (journal->j_running_transaction && buffer_jbddirty(bh))
jh->b_next_transaction = journal->j_running_transaction;
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return 0;
} else {
/* Good, the buffer belongs to the running transaction.
* We are writing our own transaction's data, not any
* previous one's, so it is safe to throw it away
* (remember that we expect the filesystem to have set
* i_size already for this truncate so recovery will not
* expose the disk blocks we are discarding here.) */
J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
JBUFFER_TRACE(jh, "on running transaction");
may_free = __dispose_buffer(jh, transaction);
}
zap_buffer:
jbd2_journal_put_journal_head(jh);
zap_buffer_no_jh:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
zap_buffer_unlocked:
clear_buffer_dirty(bh);
J_ASSERT_BH(bh, !buffer_jbddirty(bh));
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
clear_buffer_delay(bh);
clear_buffer_unwritten(bh);
bh->b_bdev = NULL;
return may_free;
}
/**
* void jbd2_journal_invalidatepage()
* @journal: journal to use for flush...
* @page: page to flush
* @offset: length of page to invalidate.
*
* Reap page buffers containing data after offset in page.
*
*/
void jbd2_journal_invalidatepage(journal_t *journal,
struct page *page,
unsigned long offset)
{
struct buffer_head *head, *bh, *next;
unsigned int curr_off = 0;
int may_free = 1;
if (!PageLocked(page))
BUG();
if (!page_has_buffers(page))
return;
/* We will potentially be playing with lists other than just the
* data lists (especially for journaled data mode), so be
* cautious in our locking. */
head = bh = page_buffers(page);
do {
unsigned int next_off = curr_off + bh->b_size;
next = bh->b_this_page;
if (offset <= curr_off) {
/* This block is wholly outside the truncation point */
lock_buffer(bh);
may_free &= journal_unmap_buffer(journal, bh);
unlock_buffer(bh);
}
curr_off = next_off;
bh = next;
} while (bh != head);
if (!offset) {
if (may_free && try_to_free_buffers(page))
J_ASSERT(!page_has_buffers(page));
}
}
/*
* File a buffer on the given transaction list.
*/
void __jbd2_journal_file_buffer(struct journal_head *jh,
transaction_t *transaction, int jlist)
{
struct journal_head **list = NULL;
int was_dirty = 0;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
assert_spin_locked(&transaction->t_journal->j_list_lock);
J_ASSERT_JH(jh, jh->b_jlist < BJ_Types);
J_ASSERT_JH(jh, jh->b_transaction == transaction ||
jh->b_transaction == NULL);
if (jh->b_transaction && jh->b_jlist == jlist)
return;
if (jlist == BJ_Metadata || jlist == BJ_Reserved ||
jlist == BJ_Shadow || jlist == BJ_Forget) {
/*
* For metadata buffers, we track dirty bit in buffer_jbddirty
* instead of buffer_dirty. We should not see a dirty bit set
* here because we clear it in do_get_write_access but e.g.
* tune2fs can modify the sb and set the dirty bit at any time
* so we try to gracefully handle that.
*/
if (buffer_dirty(bh))
warn_dirty_buffer(bh);
if (test_clear_buffer_dirty(bh) ||
test_clear_buffer_jbddirty(bh))
was_dirty = 1;
}
if (jh->b_transaction)
__jbd2_journal_temp_unlink_buffer(jh);
else
jbd2_journal_grab_journal_head(bh);
jh->b_transaction = transaction;
switch (jlist) {
case BJ_None:
J_ASSERT_JH(jh, !jh->b_committed_data);
J_ASSERT_JH(jh, !jh->b_frozen_data);
return;
case BJ_Metadata:
transaction->t_nr_buffers++;
list = &transaction->t_buffers;
break;
case BJ_Forget:
list = &transaction->t_forget;
break;
case BJ_IO:
list = &transaction->t_iobuf_list;
break;
case BJ_Shadow:
list = &transaction->t_shadow_list;
break;
case BJ_LogCtl:
list = &transaction->t_log_list;
break;
case BJ_Reserved:
list = &transaction->t_reserved_list;
break;
}
__blist_add_buffer(list, jh);
jh->b_jlist = jlist;
if (was_dirty)
set_buffer_jbddirty(bh);
}
void jbd2_journal_file_buffer(struct journal_head *jh,
transaction_t *transaction, int jlist)
{
jbd_lock_bh_state(jh2bh(jh));
spin_lock(&transaction->t_journal->j_list_lock);
__jbd2_journal_file_buffer(jh, transaction, jlist);
spin_unlock(&transaction->t_journal->j_list_lock);
jbd_unlock_bh_state(jh2bh(jh));
}
/*
* Remove a buffer from its current buffer list in preparation for
* dropping it from its current transaction entirely. If the buffer has
* already started to be used by a subsequent transaction, refile the
* buffer on that transaction's metadata list.
*
* Called under j_list_lock
* Called under jbd_lock_bh_state(jh2bh(jh))
*
* jh and bh may be already free when this function returns
*/
void __jbd2_journal_refile_buffer(struct journal_head *jh)
{
int was_dirty, jlist;
struct buffer_head *bh = jh2bh(jh);
J_ASSERT_JH(jh, jbd_is_locked_bh_state(bh));
if (jh->b_transaction)
assert_spin_locked(&jh->b_transaction->t_journal->j_list_lock);
/* If the buffer is now unused, just drop it. */
if (jh->b_next_transaction == NULL) {
__jbd2_journal_unfile_buffer(jh);
return;
}
/*
* It has been modified by a later transaction: add it to the new
* transaction's metadata list.
*/
was_dirty = test_clear_buffer_jbddirty(bh);
__jbd2_journal_temp_unlink_buffer(jh);
/*
* We set b_transaction here because b_next_transaction will inherit
* our jh reference and thus __jbd2_journal_file_buffer() must not
* take a new one.
*/
jh->b_transaction = jh->b_next_transaction;
jh->b_next_transaction = NULL;
if (buffer_freed(bh))
jlist = BJ_Forget;
else if (jh->b_modified)
jlist = BJ_Metadata;
else
jlist = BJ_Reserved;
__jbd2_journal_file_buffer(jh, jh->b_transaction, jlist);
J_ASSERT_JH(jh, jh->b_transaction->t_state == T_RUNNING);
if (was_dirty)
set_buffer_jbddirty(bh);
}
/*
* __jbd2_journal_refile_buffer() with necessary locking added. We take our
* bh reference so that we can safely unlock bh.
*
* The jh and bh may be freed by this call.
*/
void jbd2_journal_refile_buffer(journal_t *journal, struct journal_head *jh)
{
struct buffer_head *bh = jh2bh(jh);
/* Get reference so that buffer cannot be freed before we unlock it */
get_bh(bh);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
__jbd2_journal_refile_buffer(jh);
jbd_unlock_bh_state(bh);
spin_unlock(&journal->j_list_lock);
__brelse(bh);
}
/*
* File inode in the inode list of the handle's transaction
*/
int jbd2_journal_file_inode(handle_t *handle, struct jbd2_inode *jinode)
{
transaction_t *transaction = handle->h_transaction;
journal_t *journal = transaction->t_journal;
if (is_handle_aborted(handle))
return -EIO;
jbd_debug(4, "Adding inode %lu, tid:%d\n", jinode->i_vfs_inode->i_ino,
transaction->t_tid);
/*
* First check whether inode isn't already on the transaction's
* lists without taking the lock. Note that this check is safe
* without the lock as we cannot race with somebody removing inode
* from the transaction. The reason is that we remove inode from the
* transaction only in journal_release_jbd_inode() and when we commit
* the transaction. We are guarded from the first case by holding
* a reference to the inode. We are safe against the second case
* because if jinode->i_transaction == transaction, commit code
* cannot touch the transaction because we hold reference to it,
* and if jinode->i_next_transaction == transaction, commit code
* will only file the inode where we want it.
*/
if (jinode->i_transaction == transaction ||
jinode->i_next_transaction == transaction)
return 0;
spin_lock(&journal->j_list_lock);
if (jinode->i_transaction == transaction ||
jinode->i_next_transaction == transaction)
goto done;
/*
* We only ever set this variable to 1 so the test is safe. Since
* t_need_data_flush is likely to be set, we do the test to save some
* cacheline bouncing
*/
if (!transaction->t_need_data_flush)
transaction->t_need_data_flush = 1;
/* On some different transaction's list - should be
* the committing one */
if (jinode->i_transaction) {
J_ASSERT(jinode->i_next_transaction == NULL);
J_ASSERT(jinode->i_transaction ==
journal->j_committing_transaction);
jinode->i_next_transaction = transaction;
goto done;
}
/* Not on any transaction list... */
J_ASSERT(!jinode->i_next_transaction);
jinode->i_transaction = transaction;
list_add(&jinode->i_list, &transaction->t_inode_list);
done:
spin_unlock(&journal->j_list_lock);
return 0;
}
/*
* File truncate and transaction commit interact with each other in a
* non-trivial way. If a transaction writing data block A is
* committing, we cannot discard the data by truncate until we have
* written them. Otherwise if we crashed after the transaction with
* write has committed but before the transaction with truncate has
* committed, we could see stale data in block A. This function is a
* helper to solve this problem. It starts writeout of the truncated
* part in case it is in the committing transaction.
*
* Filesystem code must call this function when inode is journaled in
* ordered mode before truncation happens and after the inode has been
* placed on orphan list with the new inode size. The second condition
* avoids the race that someone writes new data and we start
* committing the transaction after this function has been called but
* before a transaction for truncate is started (and furthermore it
* allows us to optimize the case where the addition to orphan list
* happens in the same transaction as write --- we don't have to write
* any data in such case).
*/
int jbd2_journal_begin_ordered_truncate(journal_t *journal,
struct jbd2_inode *jinode,
loff_t new_size)
{
transaction_t *inode_trans, *commit_trans;
int ret = 0;
/* This is a quick check to avoid locking if not necessary */
if (!jinode->i_transaction)
goto out;
/* Locks are here just to force reading of recent values, it is
* enough that the transaction was not committing before we started
* a transaction adding the inode to orphan list */
read_lock(&journal->j_state_lock);
commit_trans = journal->j_committing_transaction;
read_unlock(&journal->j_state_lock);
spin_lock(&journal->j_list_lock);
inode_trans = jinode->i_transaction;
spin_unlock(&journal->j_list_lock);
if (inode_trans == commit_trans) {
ret = filemap_fdatawrite_range(jinode->i_vfs_inode->i_mapping,
new_size, LLONG_MAX);
if (ret)
jbd2_journal_abort(journal, ret);
}
out:
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/good_3519_0 |
crossvul-cpp_data_bad_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 );
free(szSepLine);
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/bad_634_5 |
crossvul-cpp_data_bad_2912_0 | /*
* Released under the GPLv2 only.
* SPDX-License-Identifier: GPL-2.0
*/
#include <linux/usb.h>
#include <linux/usb/ch9.h>
#include <linux/usb/hcd.h>
#include <linux/usb/quirks.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <asm/byteorder.h>
#include "usb.h"
#define USB_MAXALTSETTING 128 /* Hard limit */
#define USB_MAXCONFIG 8 /* Arbitrary limit */
static inline const char *plural(int n)
{
return (n == 1 ? "" : "s");
}
static int find_next_descriptor(unsigned char *buffer, int size,
int dt1, int dt2, int *num_skipped)
{
struct usb_descriptor_header *h;
int n = 0;
unsigned char *buffer0 = buffer;
/* Find the next descriptor of type dt1 or dt2 */
while (size > 0) {
h = (struct usb_descriptor_header *) buffer;
if (h->bDescriptorType == dt1 || h->bDescriptorType == dt2)
break;
buffer += h->bLength;
size -= h->bLength;
++n;
}
/* Store the number of descriptors skipped and return the
* number of bytes skipped */
if (num_skipped)
*num_skipped = n;
return buffer - buffer0;
}
static void usb_parse_ssp_isoc_endpoint_companion(struct device *ddev,
int cfgno, int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ssp_isoc_ep_comp_descriptor *desc;
/*
* The SuperSpeedPlus Isoc endpoint companion descriptor immediately
* follows the SuperSpeed Endpoint Companion descriptor
*/
desc = (struct usb_ssp_isoc_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SSP_ISOC_ENDPOINT_COMP ||
size < USB_DT_SSP_ISOC_EP_COMP_SIZE) {
dev_warn(ddev, "Invalid SuperSpeedPlus isoc endpoint companion"
"for config %d interface %d altsetting %d ep %d.\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
return;
}
memcpy(&ep->ssp_isoc_ep_comp, desc, USB_DT_SSP_ISOC_EP_COMP_SIZE);
}
static void usb_parse_ss_endpoint_companion(struct device *ddev, int cfgno,
int inum, int asnum, struct usb_host_endpoint *ep,
unsigned char *buffer, int size)
{
struct usb_ss_ep_comp_descriptor *desc;
int max_tx;
/* The SuperSpeed endpoint companion descriptor is supposed to
* be the first thing immediately following the endpoint descriptor.
*/
desc = (struct usb_ss_ep_comp_descriptor *) buffer;
if (desc->bDescriptorType != USB_DT_SS_ENDPOINT_COMP ||
size < USB_DT_SS_EP_COMP_SIZE) {
dev_warn(ddev, "No SuperSpeed endpoint companion for config %d "
" interface %d altsetting %d ep %d: "
"using minimum values\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
/* Fill in some default values.
* Leave bmAttributes as zero, which will mean no streams for
* bulk, and isoc won't support multiple bursts of packets.
* With bursts of only one packet, and a Mult of 1, the max
* amount of data moved per endpoint service interval is one
* packet.
*/
ep->ss_ep_comp.bLength = USB_DT_SS_EP_COMP_SIZE;
ep->ss_ep_comp.bDescriptorType = USB_DT_SS_ENDPOINT_COMP;
if (usb_endpoint_xfer_isoc(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc))
ep->ss_ep_comp.wBytesPerInterval =
ep->desc.wMaxPacketSize;
return;
}
buffer += desc->bLength;
size -= desc->bLength;
memcpy(&ep->ss_ep_comp, desc, USB_DT_SS_EP_COMP_SIZE);
/* Check the various values */
if (usb_endpoint_xfer_control(&ep->desc) && desc->bMaxBurst != 0) {
dev_warn(ddev, "Control endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 0;
} else if (desc->bMaxBurst > 15) {
dev_warn(ddev, "Endpoint with bMaxBurst = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 15\n", desc->bMaxBurst,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bMaxBurst = 15;
}
if ((usb_endpoint_xfer_control(&ep->desc) ||
usb_endpoint_xfer_int(&ep->desc)) &&
desc->bmAttributes != 0) {
dev_warn(ddev, "%s endpoint with bmAttributes = %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to zero\n",
usb_endpoint_xfer_control(&ep->desc) ? "Control" : "Bulk",
desc->bmAttributes,
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 0;
} else if (usb_endpoint_xfer_bulk(&ep->desc) &&
desc->bmAttributes > 16) {
dev_warn(ddev, "Bulk endpoint with more than 65536 streams in "
"config %d interface %d altsetting %d ep %d: "
"setting to max\n",
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 16;
} else if (usb_endpoint_xfer_isoc(&ep->desc) &&
!USB_SS_SSP_ISOC_COMP(desc->bmAttributes) &&
USB_SS_MULT(desc->bmAttributes) > 3) {
dev_warn(ddev, "Isoc endpoint has Mult of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to 3\n",
USB_SS_MULT(desc->bmAttributes),
cfgno, inum, asnum, ep->desc.bEndpointAddress);
ep->ss_ep_comp.bmAttributes = 2;
}
if (usb_endpoint_xfer_isoc(&ep->desc))
max_tx = (desc->bMaxBurst + 1) *
(USB_SS_MULT(desc->bmAttributes)) *
usb_endpoint_maxp(&ep->desc);
else if (usb_endpoint_xfer_int(&ep->desc))
max_tx = usb_endpoint_maxp(&ep->desc) *
(desc->bMaxBurst + 1);
else
max_tx = 999999;
if (le16_to_cpu(desc->wBytesPerInterval) > max_tx) {
dev_warn(ddev, "%s endpoint with wBytesPerInterval of %d in "
"config %d interface %d altsetting %d ep %d: "
"setting to %d\n",
usb_endpoint_xfer_isoc(&ep->desc) ? "Isoc" : "Int",
le16_to_cpu(desc->wBytesPerInterval),
cfgno, inum, asnum, ep->desc.bEndpointAddress,
max_tx);
ep->ss_ep_comp.wBytesPerInterval = cpu_to_le16(max_tx);
}
/* Parse a possible SuperSpeedPlus isoc ep companion descriptor */
if (usb_endpoint_xfer_isoc(&ep->desc) &&
USB_SS_SSP_ISOC_COMP(desc->bmAttributes))
usb_parse_ssp_isoc_endpoint_companion(ddev, cfgno, inum, asnum,
ep, buffer, size);
}
static const unsigned short low_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 8,
[USB_ENDPOINT_XFER_ISOC] = 0,
[USB_ENDPOINT_XFER_BULK] = 0,
[USB_ENDPOINT_XFER_INT] = 8,
};
static const unsigned short full_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1023,
[USB_ENDPOINT_XFER_BULK] = 64,
[USB_ENDPOINT_XFER_INT] = 64,
};
static const unsigned short high_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 64,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 512,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static const unsigned short super_speed_maxpacket_maxes[4] = {
[USB_ENDPOINT_XFER_CONTROL] = 512,
[USB_ENDPOINT_XFER_ISOC] = 1024,
[USB_ENDPOINT_XFER_BULK] = 1024,
[USB_ENDPOINT_XFER_INT] = 1024,
};
static int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
int asnum, struct usb_host_interface *ifp, int num_ep,
unsigned char *buffer, int size)
{
unsigned char *buffer0 = buffer;
struct usb_endpoint_descriptor *d;
struct usb_host_endpoint *endpoint;
int n, i, j, retval;
unsigned int maxp;
const unsigned short *maxpacket_maxes;
d = (struct usb_endpoint_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
n = USB_DT_ENDPOINT_AUDIO_SIZE;
else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
n = USB_DT_ENDPOINT_SIZE;
else {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint descriptor of length %d, skipping\n",
cfgno, inum, asnum, d->bLength);
goto skip_to_next_endpoint_or_interface_descriptor;
}
i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
if (i >= 16 || i == 0) {
dev_warn(ddev, "config %d interface %d altsetting %d has an "
"invalid endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
/* Only store as many endpoints as we have room for */
if (ifp->desc.bNumEndpoints >= num_ep)
goto skip_to_next_endpoint_or_interface_descriptor;
/* Check for duplicate endpoint addresses */
for (i = 0; i < ifp->desc.bNumEndpoints; ++i) {
if (ifp->endpoint[i].desc.bEndpointAddress ==
d->bEndpointAddress) {
dev_warn(ddev, "config %d interface %d altsetting %d has a duplicate endpoint with address 0x%X, skipping\n",
cfgno, inum, asnum, d->bEndpointAddress);
goto skip_to_next_endpoint_or_interface_descriptor;
}
}
endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
++ifp->desc.bNumEndpoints;
memcpy(&endpoint->desc, d, n);
INIT_LIST_HEAD(&endpoint->urb_list);
/*
* Fix up bInterval values outside the legal range.
* Use 10 or 8 ms if no proper value can be guessed.
*/
i = 0; /* i = min, j = max, n = default */
j = 255;
if (usb_endpoint_xfer_int(d)) {
i = 1;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_SUPER_PLUS:
case USB_SPEED_SUPER:
case USB_SPEED_HIGH:
/*
* Many device manufacturers are using full-speed
* bInterval values in high-speed interrupt endpoint
* descriptors. Try to fix those and fall back to an
* 8-ms default value otherwise.
*/
n = fls(d->bInterval*8);
if (n == 0)
n = 7; /* 8 ms = 2^(7-1) uframes */
j = 16;
/*
* Adjust bInterval for quirked devices.
*/
/*
* This quirk fixes bIntervals reported in ms.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval) + 3, i, j);
i = j = n;
}
/*
* This quirk fixes bIntervals reported in
* linear microframes.
*/
if (to_usb_device(ddev)->quirks &
USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL) {
n = clamp(fls(d->bInterval), i, j);
i = j = n;
}
break;
default: /* USB_SPEED_FULL or _LOW */
/*
* For low-speed, 10 ms is the official minimum.
* But some "overclocked" devices might want faster
* polling so we'll allow it.
*/
n = 10;
break;
}
} else if (usb_endpoint_xfer_isoc(d)) {
i = 1;
j = 16;
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_HIGH:
n = 7; /* 8 ms = 2^(7-1) uframes */
break;
default: /* USB_SPEED_FULL */
n = 4; /* 8 ms = 2^(4-1) frames */
break;
}
}
if (d->bInterval < i || d->bInterval > j) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X has an invalid bInterval %d, "
"changing to %d\n",
cfgno, inum, asnum,
d->bEndpointAddress, d->bInterval, n);
endpoint->desc.bInterval = n;
}
/* Some buggy low-speed devices have Bulk endpoints, which is
* explicitly forbidden by the USB spec. In an attempt to make
* them usable, we will try treating them as Interrupt endpoints.
*/
if (to_usb_device(ddev)->speed == USB_SPEED_LOW &&
usb_endpoint_xfer_bulk(d)) {
dev_warn(ddev, "config %d interface %d altsetting %d "
"endpoint 0x%X is Bulk; changing to Interrupt\n",
cfgno, inum, asnum, d->bEndpointAddress);
endpoint->desc.bmAttributes = USB_ENDPOINT_XFER_INT;
endpoint->desc.bInterval = 1;
if (usb_endpoint_maxp(&endpoint->desc) > 8)
endpoint->desc.wMaxPacketSize = cpu_to_le16(8);
}
/* Validate the wMaxPacketSize field */
maxp = usb_endpoint_maxp(&endpoint->desc);
/* Find the highest legal maxpacket size for this endpoint */
i = 0; /* additional transactions per microframe */
switch (to_usb_device(ddev)->speed) {
case USB_SPEED_LOW:
maxpacket_maxes = low_speed_maxpacket_maxes;
break;
case USB_SPEED_FULL:
maxpacket_maxes = full_speed_maxpacket_maxes;
break;
case USB_SPEED_HIGH:
/* Bits 12..11 are allowed only for HS periodic endpoints */
if (usb_endpoint_xfer_int(d) || usb_endpoint_xfer_isoc(d)) {
i = maxp & (BIT(12) | BIT(11));
maxp &= ~i;
}
/* fallthrough */
default:
maxpacket_maxes = high_speed_maxpacket_maxes;
break;
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
maxpacket_maxes = super_speed_maxpacket_maxes;
break;
}
j = maxpacket_maxes[usb_endpoint_type(&endpoint->desc)];
if (maxp > j) {
dev_warn(ddev, "config %d interface %d altsetting %d endpoint 0x%X has invalid maxpacket %d, setting to %d\n",
cfgno, inum, asnum, d->bEndpointAddress, maxp, j);
maxp = j;
endpoint->desc.wMaxPacketSize = cpu_to_le16(i | maxp);
}
/*
* Some buggy high speed devices have bulk endpoints using
* maxpacket sizes other than 512. High speed HCDs may not
* be able to handle that particular bug, so let's warn...
*/
if (to_usb_device(ddev)->speed == USB_SPEED_HIGH
&& usb_endpoint_xfer_bulk(d)) {
if (maxp != 512)
dev_warn(ddev, "config %d interface %d altsetting %d "
"bulk endpoint 0x%X has invalid maxpacket %d\n",
cfgno, inum, asnum, d->bEndpointAddress,
maxp);
}
/* Parse a possible SuperSpeed endpoint companion descriptor */
if (to_usb_device(ddev)->speed >= USB_SPEED_SUPER)
usb_parse_ss_endpoint_companion(ddev, cfgno,
inum, asnum, endpoint, buffer, size);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the next endpoint or interface descriptor */
endpoint->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
endpoint->extralen = i;
retval = buffer - buffer0 + i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "endpoint");
return retval;
skip_to_next_endpoint_or_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
void usb_release_interface_cache(struct kref *ref)
{
struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
int j;
for (j = 0; j < intfc->num_altsetting; j++) {
struct usb_host_interface *alt = &intfc->altsetting[j];
kfree(alt->endpoint);
kfree(alt->string);
}
kfree(intfc);
}
static int usb_parse_interface(struct device *ddev, int cfgno,
struct usb_host_config *config, unsigned char *buffer, int size,
u8 inums[], u8 nalts[])
{
unsigned char *buffer0 = buffer;
struct usb_interface_descriptor *d;
int inum, asnum;
struct usb_interface_cache *intfc;
struct usb_host_interface *alt;
int i, n;
int len, retval;
int num_ep, num_ep_orig;
d = (struct usb_interface_descriptor *) buffer;
buffer += d->bLength;
size -= d->bLength;
if (d->bLength < USB_DT_INTERFACE_SIZE)
goto skip_to_next_interface_descriptor;
/* Which interface entry is this? */
intfc = NULL;
inum = d->bInterfaceNumber;
for (i = 0; i < config->desc.bNumInterfaces; ++i) {
if (inums[i] == inum) {
intfc = config->intf_cache[i];
break;
}
}
if (!intfc || intfc->num_altsetting >= nalts[i])
goto skip_to_next_interface_descriptor;
/* Check for duplicate altsetting entries */
asnum = d->bAlternateSetting;
for ((i = 0, alt = &intfc->altsetting[0]);
i < intfc->num_altsetting;
(++i, ++alt)) {
if (alt->desc.bAlternateSetting == asnum) {
dev_warn(ddev, "Duplicate descriptor for config %d "
"interface %d altsetting %d, skipping\n",
cfgno, inum, asnum);
goto skip_to_next_interface_descriptor;
}
}
++intfc->num_altsetting;
memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first endpoint or interface descriptor */
alt->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
USB_DT_INTERFACE, &n);
alt->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "interface");
buffer += i;
size -= i;
/* Allocate space for the right(?) number of endpoints */
num_ep = num_ep_orig = alt->desc.bNumEndpoints;
alt->desc.bNumEndpoints = 0; /* Use as a counter */
if (num_ep > USB_MAXENDPOINTS) {
dev_warn(ddev, "too many endpoints for config %d interface %d "
"altsetting %d: %d, using maximum allowed: %d\n",
cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
num_ep = USB_MAXENDPOINTS;
}
if (num_ep > 0) {
/* Can't allocate 0 bytes */
len = sizeof(struct usb_host_endpoint) * num_ep;
alt->endpoint = kzalloc(len, GFP_KERNEL);
if (!alt->endpoint)
return -ENOMEM;
}
/* Parse all the endpoint descriptors */
n = 0;
while (size > 0) {
if (((struct usb_descriptor_header *) buffer)->bDescriptorType
== USB_DT_INTERFACE)
break;
retval = usb_parse_endpoint(ddev, cfgno, inum, asnum, alt,
num_ep, buffer, size);
if (retval < 0)
return retval;
++n;
buffer += retval;
size -= retval;
}
if (n != num_ep_orig)
dev_warn(ddev, "config %d interface %d altsetting %d has %d "
"endpoint descriptor%s, different from the interface "
"descriptor's value: %d\n",
cfgno, inum, asnum, n, plural(n), num_ep_orig);
return buffer - buffer0;
skip_to_next_interface_descriptor:
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, NULL);
return buffer - buffer0 + i;
}
static int usb_parse_configuration(struct usb_device *dev, int cfgidx,
struct usb_host_config *config, unsigned char *buffer, int size)
{
struct device *ddev = &dev->dev;
unsigned char *buffer0 = buffer;
int cfgno;
int nintf, nintf_orig;
int i, j, n;
struct usb_interface_cache *intfc;
unsigned char *buffer2;
int size2;
struct usb_descriptor_header *header;
int len, retval;
u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
unsigned iad_num = 0;
memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
if (config->desc.bDescriptorType != USB_DT_CONFIG ||
config->desc.bLength < USB_DT_CONFIG_SIZE ||
config->desc.bLength > size) {
dev_err(ddev, "invalid descriptor for config index %d: "
"type = 0x%X, length = %d\n", cfgidx,
config->desc.bDescriptorType, config->desc.bLength);
return -EINVAL;
}
cfgno = config->desc.bConfigurationValue;
buffer += config->desc.bLength;
size -= config->desc.bLength;
nintf = nintf_orig = config->desc.bNumInterfaces;
if (nintf > USB_MAXINTERFACES) {
dev_warn(ddev, "config %d has too many interfaces: %d, "
"using maximum allowed: %d\n",
cfgno, nintf, USB_MAXINTERFACES);
nintf = USB_MAXINTERFACES;
}
/* Go through the descriptors, checking their length and counting the
* number of altsettings for each interface */
n = 0;
for ((buffer2 = buffer, size2 = size);
size2 > 0;
(buffer2 += header->bLength, size2 -= header->bLength)) {
if (size2 < sizeof(struct usb_descriptor_header)) {
dev_warn(ddev, "config %d descriptor has %d excess "
"byte%s, ignoring\n",
cfgno, size2, plural(size2));
break;
}
header = (struct usb_descriptor_header *) buffer2;
if ((header->bLength > size2) || (header->bLength < 2)) {
dev_warn(ddev, "config %d has an invalid descriptor "
"of length %d, skipping remainder of the config\n",
cfgno, header->bLength);
break;
}
if (header->bDescriptorType == USB_DT_INTERFACE) {
struct usb_interface_descriptor *d;
int inum;
d = (struct usb_interface_descriptor *) header;
if (d->bLength < USB_DT_INTERFACE_SIZE) {
dev_warn(ddev, "config %d has an invalid "
"interface descriptor of length %d, "
"skipping\n", cfgno, d->bLength);
continue;
}
inum = d->bInterfaceNumber;
if ((dev->quirks & USB_QUIRK_HONOR_BNUMINTERFACES) &&
n >= nintf_orig) {
dev_warn(ddev, "config %d has more interface "
"descriptors, than it declares in "
"bNumInterfaces, ignoring interface "
"number: %d\n", cfgno, inum);
continue;
}
if (inum >= nintf_orig)
dev_warn(ddev, "config %d has an invalid "
"interface number: %d but max is %d\n",
cfgno, inum, nintf_orig - 1);
/* Have we already encountered this interface?
* Count its altsettings */
for (i = 0; i < n; ++i) {
if (inums[i] == inum)
break;
}
if (i < n) {
if (nalts[i] < 255)
++nalts[i];
} else if (n < USB_MAXINTERFACES) {
inums[n] = inum;
nalts[n] = 1;
++n;
}
} else if (header->bDescriptorType ==
USB_DT_INTERFACE_ASSOCIATION) {
if (iad_num == USB_MAXIADS) {
dev_warn(ddev, "found more Interface "
"Association Descriptors "
"than allocated for in "
"configuration %d\n", cfgno);
} else {
config->intf_assoc[iad_num] =
(struct usb_interface_assoc_descriptor
*)header;
iad_num++;
}
} else if (header->bDescriptorType == USB_DT_DEVICE ||
header->bDescriptorType == USB_DT_CONFIG)
dev_warn(ddev, "config %d contains an unexpected "
"descriptor of type 0x%X, skipping\n",
cfgno, header->bDescriptorType);
} /* for ((buffer2 = buffer, size2 = size); ...) */
size = buffer2 - buffer;
config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
if (n != nintf)
dev_warn(ddev, "config %d has %d interface%s, different from "
"the descriptor's value: %d\n",
cfgno, n, plural(n), nintf_orig);
else if (n == 0)
dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
config->desc.bNumInterfaces = nintf = n;
/* Check for missing interface numbers */
for (i = 0; i < nintf; ++i) {
for (j = 0; j < nintf; ++j) {
if (inums[j] == i)
break;
}
if (j >= nintf)
dev_warn(ddev, "config %d has no interface number "
"%d\n", cfgno, i);
}
/* Allocate the usb_interface_caches and altsetting arrays */
for (i = 0; i < nintf; ++i) {
j = nalts[i];
if (j > USB_MAXALTSETTING) {
dev_warn(ddev, "too many alternate settings for "
"config %d interface %d: %d, "
"using maximum allowed: %d\n",
cfgno, inums[i], j, USB_MAXALTSETTING);
nalts[i] = j = USB_MAXALTSETTING;
}
len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;
config->intf_cache[i] = intfc = kzalloc(len, GFP_KERNEL);
if (!intfc)
return -ENOMEM;
kref_init(&intfc->ref);
}
/* FIXME: parse the BOS descriptor */
/* Skip over any Class Specific or Vendor Specific descriptors;
* find the first interface descriptor */
config->extra = buffer;
i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
USB_DT_INTERFACE, &n);
config->extralen = i;
if (n > 0)
dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
n, plural(n), "configuration");
buffer += i;
size -= i;
/* Parse all the interface/altsetting descriptors */
while (size > 0) {
retval = usb_parse_interface(ddev, cfgno, config,
buffer, size, inums, nalts);
if (retval < 0)
return retval;
buffer += retval;
size -= retval;
}
/* Check for missing altsettings */
for (i = 0; i < nintf; ++i) {
intfc = config->intf_cache[i];
for (j = 0; j < intfc->num_altsetting; ++j) {
for (n = 0; n < intfc->num_altsetting; ++n) {
if (intfc->altsetting[n].desc.
bAlternateSetting == j)
break;
}
if (n >= intfc->num_altsetting)
dev_warn(ddev, "config %d interface %d has no "
"altsetting %d\n", cfgno, inums[i], j);
}
}
return 0;
}
/* hub-only!! ... and only exported for reset/reinit path.
* otherwise used internally on disconnect/destroy path
*/
void usb_destroy_configuration(struct usb_device *dev)
{
int c, i;
if (!dev->config)
return;
if (dev->rawdescriptors) {
for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
kfree(dev->rawdescriptors[i]);
kfree(dev->rawdescriptors);
dev->rawdescriptors = NULL;
}
for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
struct usb_host_config *cf = &dev->config[c];
kfree(cf->string);
for (i = 0; i < cf->desc.bNumInterfaces; i++) {
if (cf->intf_cache[i])
kref_put(&cf->intf_cache[i]->ref,
usb_release_interface_cache);
}
}
kfree(dev->config);
dev->config = NULL;
}
/*
* Get the USB config descriptors, cache and parse'em
*
* hub-only!! ... and only in reset path, or usb_new_device()
* (used by real hubs and virtual root hubs)
*/
int usb_get_configuration(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
int ncfg = dev->descriptor.bNumConfigurations;
int result = 0;
unsigned int cfgno, length;
unsigned char *bigbuffer;
struct usb_config_descriptor *desc;
cfgno = 0;
result = -ENOMEM;
if (ncfg > USB_MAXCONFIG) {
dev_warn(ddev, "too many configurations: %d, "
"using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
}
if (ncfg < 1) {
dev_err(ddev, "no configurations\n");
return -EINVAL;
}
length = ncfg * sizeof(struct usb_host_config);
dev->config = kzalloc(length, GFP_KERNEL);
if (!dev->config)
goto err2;
length = ncfg * sizeof(char *);
dev->rawdescriptors = kzalloc(length, GFP_KERNEL);
if (!dev->rawdescriptors)
goto err2;
desc = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
if (!desc)
goto err2;
result = 0;
for (; cfgno < ncfg; cfgno++) {
/* We grab just the first descriptor so we know how long
* the whole configuration is */
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
desc, USB_DT_CONFIG_SIZE);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s: %d\n", cfgno, "start", result);
if (result != -EPIPE)
goto err;
dev_err(ddev, "chopping to %d config(s)\n", cfgno);
dev->descriptor.bNumConfigurations = cfgno;
break;
} else if (result < 4) {
dev_err(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno,
USB_DT_CONFIG_SIZE, result);
result = -EINVAL;
goto err;
}
length = max((int) le16_to_cpu(desc->wTotalLength),
USB_DT_CONFIG_SIZE);
/* Now that we know the length, get the whole thing */
bigbuffer = kmalloc(length, GFP_KERNEL);
if (!bigbuffer) {
result = -ENOMEM;
goto err;
}
if (dev->quirks & USB_QUIRK_DELAY_INIT)
msleep(200);
result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
bigbuffer, length);
if (result < 0) {
dev_err(ddev, "unable to read config index %d "
"descriptor/%s\n", cfgno, "all");
kfree(bigbuffer);
goto err;
}
if (result < length) {
dev_warn(ddev, "config index %d descriptor too short "
"(expected %i, got %i)\n", cfgno, length, result);
length = result;
}
dev->rawdescriptors[cfgno] = bigbuffer;
result = usb_parse_configuration(dev, cfgno,
&dev->config[cfgno], bigbuffer, length);
if (result < 0) {
++cfgno;
goto err;
}
}
result = 0;
err:
kfree(desc);
dev->descriptor.bNumConfigurations = cfgno;
err2:
if (result == -ENOMEM)
dev_err(ddev, "out of memory\n");
return result;
}
void usb_release_bos_descriptor(struct usb_device *dev)
{
if (dev->bos) {
kfree(dev->bos->desc);
kfree(dev->bos);
dev->bos = NULL;
}
}
/* Get BOS descriptor set */
int usb_get_bos_descriptor(struct usb_device *dev)
{
struct device *ddev = &dev->dev;
struct usb_bos_descriptor *bos;
struct usb_dev_cap_header *cap;
unsigned char *buffer;
int length, total_len, num, i;
int ret;
bos = kzalloc(sizeof(struct usb_bos_descriptor), GFP_KERNEL);
if (!bos)
return -ENOMEM;
/* Get BOS descriptor */
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, bos, USB_DT_BOS_SIZE);
if (ret < USB_DT_BOS_SIZE) {
dev_err(ddev, "unable to get BOS descriptor\n");
if (ret >= 0)
ret = -ENOMSG;
kfree(bos);
return ret;
}
length = bos->bLength;
total_len = le16_to_cpu(bos->wTotalLength);
num = bos->bNumDeviceCaps;
kfree(bos);
if (total_len < length)
return -EINVAL;
dev->bos = kzalloc(sizeof(struct usb_host_bos), GFP_KERNEL);
if (!dev->bos)
return -ENOMEM;
/* Now let's get the whole BOS descriptor set */
buffer = kzalloc(total_len, GFP_KERNEL);
if (!buffer) {
ret = -ENOMEM;
goto err;
}
dev->bos->desc = (struct usb_bos_descriptor *)buffer;
ret = usb_get_descriptor(dev, USB_DT_BOS, 0, buffer, total_len);
if (ret < total_len) {
dev_err(ddev, "unable to get BOS descriptor set\n");
if (ret >= 0)
ret = -ENOMSG;
goto err;
}
total_len -= length;
for (i = 0; i < num; i++) {
buffer += length;
cap = (struct usb_dev_cap_header *)buffer;
length = cap->bLength;
if (total_len < length)
break;
total_len -= length;
if (cap->bDescriptorType != USB_DT_DEVICE_CAPABILITY) {
dev_warn(ddev, "descriptor type invalid, skip\n");
continue;
}
switch (cap->bDevCapabilityType) {
case USB_CAP_TYPE_WIRELESS_USB:
/* Wireless USB cap descriptor is handled by wusb */
break;
case USB_CAP_TYPE_EXT:
dev->bos->ext_cap =
(struct usb_ext_cap_descriptor *)buffer;
break;
case USB_SS_CAP_TYPE:
dev->bos->ss_cap =
(struct usb_ss_cap_descriptor *)buffer;
break;
case USB_SSP_CAP_TYPE:
dev->bos->ssp_cap =
(struct usb_ssp_cap_descriptor *)buffer;
break;
case CONTAINER_ID_TYPE:
dev->bos->ss_id =
(struct usb_ss_container_id_descriptor *)buffer;
break;
case USB_PTM_CAP_TYPE:
dev->bos->ptm_cap =
(struct usb_ptm_cap_descriptor *)buffer;
default:
break;
}
}
return 0;
err:
usb_release_bos_descriptor(dev);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-119/c/bad_2912_0 |
crossvul-cpp_data_bad_2732_3 | /*
* Rufus: The Reliable USB Formatting Utility
* Standard Dialog Routines (Browse for folder, About, etc)
* Copyright © 2011-2017 Pete Batard <pete@akeo.ie>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <shlobj.h>
#include <commdlg.h>
#include <richedit.h>
#include "rufus.h"
#include "missing.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#include "registry.h"
#include "settings.h"
#include "license.h"
PF_TYPE_DECL(WINAPI, HRESULT, SHCreateItemFromParsingName, (PCWSTR, IBindCtx*, REFIID, void **));
PF_TYPE_DECL(WINAPI, LPITEMIDLIST, SHSimpleIDListFromPath, (PCWSTR pszPath));
#define INIT_VISTA_SHELL32 PF_INIT(SHCreateItemFromParsingName, Shell32)
#define INIT_XP_SHELL32 PF_INIT(SHSimpleIDListFromPath, Shell32)
#define IS_VISTA_SHELL32_AVAILABLE (pfSHCreateItemFromParsingName != NULL)
/* Globals */
static HICON hMessageIcon = (HICON)INVALID_HANDLE_VALUE;
static char* szMessageText = NULL;
static char* szMessageTitle = NULL;
static char **szDialogItem;
static int nDialogItems;
static HWND hBrowseEdit;
extern HWND hUpdatesDlg;
static WNDPROC pOrgBrowseWndproc;
static const SETTEXTEX friggin_microsoft_unicode_amateurs = {ST_DEFAULT, CP_UTF8};
static BOOL notification_is_question;
static const notification_info* notification_more_info;
static BOOL settings_commcheck = FALSE;
static WNDPROC update_original_proc = NULL;
static HWINEVENTHOOK fp_weh = NULL;
static char *fp_title_str = "Microsoft Windows", *fp_button_str = "Format disk";
extern loc_cmd* selected_locale;
/*
* https://blogs.msdn.microsoft.com/oldnewthing/20040802-00/?p=38283/
*/
void SetDialogFocus(HWND hDlg, HWND hCtrl)
{
SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)hCtrl, TRUE);
}
/*
* We need a sub-callback to read the content of the edit box on exit and update
* our path, else if what the user typed does match the selection, it is discarded.
* Talk about a convoluted way of producing an intuitive folder selection dialog
*/
INT CALLBACK BrowseDlgCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message) {
case WM_DESTROY:
GetWindowTextU(hBrowseEdit, szFolderPath, sizeof(szFolderPath));
break;
}
return (INT)CallWindowProc(pOrgBrowseWndproc, hDlg, message, wParam, lParam);
}
/*
* Main BrowseInfo callback to set the initial directory and populate the edit control
*/
INT CALLBACK BrowseInfoCallback(HWND hDlg, UINT message, LPARAM lParam, LPARAM pData)
{
char dir[MAX_PATH];
wchar_t* wpath;
LPITEMIDLIST pidl;
switch(message) {
case BFFM_INITIALIZED:
pOrgBrowseWndproc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)BrowseDlgCallback);
// Windows hides the full path in the edit box by default, which is bull.
// Get a handle to the edit control to fix that
hBrowseEdit = FindWindowExA(hDlg, NULL, "Edit", NULL);
SetWindowTextU(hBrowseEdit, szFolderPath);
SetDialogFocus(hDlg, hBrowseEdit);
// On XP, BFFM_SETSELECTION can't be used with a Unicode Path in SendMessageW
// or a pidl (at least with MinGW) => must use SendMessageA
if (nWindowsVersion <= WINDOWS_XP) {
SendMessageLU(hDlg, BFFM_SETSELECTION, (WPARAM)TRUE, szFolderPath);
} else {
// On Windows 7, MinGW only properly selects the specified folder when using a pidl
wpath = utf8_to_wchar(szFolderPath);
pidl = (*pfSHSimpleIDListFromPath)(wpath);
safe_free(wpath);
// NB: see http://connect.microsoft.com/VisualStudio/feedback/details/518103/bffm-setselection-does-not-work-with-shbrowseforfolder-on-windows-7
// for details as to why we send BFFM_SETSELECTION twice.
SendMessageW(hDlg, BFFM_SETSELECTION, (WPARAM)FALSE, (LPARAM)pidl);
Sleep(100);
PostMessageW(hDlg, BFFM_SETSELECTION, (WPARAM)FALSE, (LPARAM)pidl);
}
break;
case BFFM_SELCHANGED:
// Update the status
if (SHGetPathFromIDListU((LPITEMIDLIST)lParam, dir)) {
SendMessageLU(hDlg, BFFM_SETSTATUSTEXT, 0, dir);
SetWindowTextU(hBrowseEdit, dir);
}
break;
}
return 0;
}
/*
* Browse for a folder and update the folder edit box
* Will use the newer IFileOpenDialog if *compiled* for Vista or later
*/
void BrowseForFolder(void) {
BROWSEINFOW bi;
LPITEMIDLIST pidl;
WCHAR *wpath;
size_t i;
HRESULT hr;
IShellItem *psi = NULL;
IShellItem *si_path = NULL; // Automatically freed
IFileOpenDialog *pfod = NULL;
WCHAR *fname;
char* tmp_path = NULL;
dialog_showing++;
if (nWindowsVersion >= WINDOWS_VISTA) {
INIT_VISTA_SHELL32;
if (IS_VISTA_SHELL32_AVAILABLE) {
hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC,
&IID_IFileOpenDialog, (LPVOID)&pfod);
if (FAILED(hr)) {
uprintf("CoCreateInstance for FileOpenDialog failed: error %X\n", hr);
pfod = NULL; // Just in case
goto fallback;
}
hr = pfod->lpVtbl->SetOptions(pfod, FOS_PICKFOLDERS);
if (FAILED(hr)) {
uprintf("Failed to set folder option for FileOpenDialog: error %X\n", hr);
goto fallback;
}
// Set the initial folder (if the path is invalid, will simply use last)
wpath = utf8_to_wchar(szFolderPath);
// The new IFileOpenDialog makes us split the path
fname = NULL;
if ((wpath != NULL) && (wcslen(wpath) >= 1)) {
for (i = wcslen(wpath) - 1; i != 0; i--) {
if (wpath[i] == L'\\') {
wpath[i] = 0;
fname = &wpath[i + 1];
break;
}
}
}
hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path);
if (SUCCEEDED(hr)) {
if (wpath != NULL) {
pfod->lpVtbl->SetFolder(pfod, si_path);
}
if (fname != NULL) {
pfod->lpVtbl->SetFileName(pfod, fname);
}
}
safe_free(wpath);
hr = pfod->lpVtbl->Show(pfod, hMainDialog);
if (SUCCEEDED(hr)) {
hr = pfod->lpVtbl->GetResult(pfod, &psi);
if (SUCCEEDED(hr)) {
psi->lpVtbl->GetDisplayName(psi, SIGDN_FILESYSPATH, &wpath);
tmp_path = wchar_to_utf8(wpath);
CoTaskMemFree(wpath);
if (tmp_path == NULL) {
uprintf("Could not convert path\n");
} else {
static_strcpy(szFolderPath, tmp_path);
safe_free(tmp_path);
}
} else {
uprintf("Failed to set folder option for FileOpenDialog: error %X\n", hr);
}
} else if ((hr & 0xFFFF) != ERROR_CANCELLED) {
// If it's not a user cancel, assume the dialog didn't show and fallback
uprintf("Could not show FileOpenDialog: error %X\n", hr);
goto fallback;
}
pfod->lpVtbl->Release(pfod);
dialog_showing--;
return;
}
fallback:
if (pfod != NULL) {
pfod->lpVtbl->Release(pfod);
}
}
INIT_XP_SHELL32;
memset(&bi, 0, sizeof(BROWSEINFOW));
bi.hwndOwner = hMainDialog;
bi.lpszTitle = utf8_to_wchar(lmprintf(MSG_106));
bi.lpfn = BrowseInfoCallback;
// BIF_NONEWFOLDERBUTTON = 0x00000200 is unknown on MinGW
bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS |
BIF_DONTGOBELOWDOMAIN | BIF_EDITBOX | 0x00000200;
pidl = SHBrowseForFolderW(&bi);
if (pidl != NULL) {
CoTaskMemFree(pidl);
}
safe_free(bi.lpszTitle);
dialog_showing--;
}
/*
* Return the UTF8 path of a file selected through a load or save dialog
* Will use the newer IFileOpenDialog if *compiled* for Vista or later
* All string parameters are UTF-8
* IMPORTANT NOTE: On Vista and later, remember that you need to call
* CoInitializeEx() for *EACH* thread you invoke FileDialog from, as
* GetDisplayName() will return error 0x8001010E otherwise.
*/
char* FileDialog(BOOL save, char* path, const ext_t* ext, DWORD options)
{
DWORD tmp;
OPENFILENAMEA ofn;
char selected_name[MAX_PATH];
char *ext_string = NULL, *all_files = NULL;
size_t i, j, ext_strlen;
BOOL r;
char* filepath = NULL;
HRESULT hr = FALSE;
IFileDialog *pfd = NULL;
IShellItem *psiResult;
COMDLG_FILTERSPEC* filter_spec = NULL;
wchar_t *wpath = NULL, *wfilename = NULL;
IShellItem *si_path = NULL; // Automatically freed
if ((ext == NULL) || (ext->count == 0) || (ext->extension == NULL) || (ext->description == NULL))
return NULL;
dialog_showing++;
if (nWindowsVersion >= WINDOWS_VISTA) {
INIT_VISTA_SHELL32;
filter_spec = (COMDLG_FILTERSPEC*)calloc(ext->count + 1, sizeof(COMDLG_FILTERSPEC));
if ((IS_VISTA_SHELL32_AVAILABLE) && (filter_spec != NULL)) {
// Setup the file extension filter table
for (i = 0; i < ext->count; i++) {
filter_spec[i].pszSpec = utf8_to_wchar(ext->extension[i]);
filter_spec[i].pszName = utf8_to_wchar(ext->description[i]);
}
filter_spec[i].pszSpec = L"*.*";
filter_spec[i].pszName = utf8_to_wchar(lmprintf(MSG_107));
hr = CoCreateInstance(save ? &CLSID_FileSaveDialog : &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC,
&IID_IFileDialog, (LPVOID)&pfd);
if (FAILED(hr)) {
SetLastError(hr);
uprintf("CoCreateInstance for FileOpenDialog failed: %s\n", WindowsErrorString());
pfd = NULL; // Just in case
goto fallback;
}
// Set the file extension filters
pfd->lpVtbl->SetFileTypes(pfd, (UINT)ext->count + 1, filter_spec);
// Set the default directory
wpath = utf8_to_wchar(path);
hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path);
if (SUCCEEDED(hr)) {
pfd->lpVtbl->SetFolder(pfd, si_path);
}
safe_free(wpath);
// Set the default filename
wfilename = utf8_to_wchar((ext->filename == NULL) ? "" : ext->filename);
if (wfilename != NULL) {
pfd->lpVtbl->SetFileName(pfd, wfilename);
}
// Display the dialog
hr = pfd->lpVtbl->Show(pfd, hMainDialog);
// Cleanup
safe_free(wfilename);
for (i = 0; i < ext->count; i++) {
safe_free(filter_spec[i].pszSpec);
safe_free(filter_spec[i].pszName);
}
safe_free(filter_spec[i].pszName);
safe_free(filter_spec);
if (SUCCEEDED(hr)) {
// Obtain the result of the user's interaction with the dialog.
hr = pfd->lpVtbl->GetResult(pfd, &psiResult);
if (SUCCEEDED(hr)) {
hr = psiResult->lpVtbl->GetDisplayName(psiResult, SIGDN_FILESYSPATH, &wpath);
if (SUCCEEDED(hr)) {
filepath = wchar_to_utf8(wpath);
CoTaskMemFree(wpath);
} else {
SetLastError(hr);
uprintf("Unable to access file path: %s\n", WindowsErrorString());
}
psiResult->lpVtbl->Release(psiResult);
}
} else if ((hr & 0xFFFF) != ERROR_CANCELLED) {
// If it's not a user cancel, assume the dialog didn't show and fallback
SetLastError(hr);
uprintf("Could not show FileOpenDialog: %s\n", WindowsErrorString());
goto fallback;
}
pfd->lpVtbl->Release(pfd);
dialog_showing--;
return filepath;
}
fallback:
safe_free(filter_spec);
if (pfd != NULL) {
pfd->lpVtbl->Release(pfd);
}
}
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hMainDialog;
// Selected File name
static_sprintf(selected_name, "%s", (ext->filename == NULL)?"":ext->filename);
ofn.lpstrFile = selected_name;
ofn.nMaxFile = MAX_PATH;
// Set the file extension filters
all_files = lmprintf(MSG_107);
ext_strlen = 0;
for (i=0; i<ext->count; i++) {
ext_strlen += safe_strlen(ext->description[i]) + 2*safe_strlen(ext->extension[i]) + sizeof(" ()\r\r");
}
ext_strlen += safe_strlen(all_files) + sizeof(" (*.*)\r*.*\r");
ext_string = (char*)malloc(ext_strlen+1);
if (ext_string == NULL)
return NULL;
ext_string[0] = 0;
for (i=0, j=0; i<ext->count; i++) {
j += _snprintf(&ext_string[j], ext_strlen-j, "%s (%s)\r%s\r", ext->description[i], ext->extension[i], ext->extension[i]);
}
j = _snprintf(&ext_string[j], ext_strlen-j, "%s (*.*)\r*.*\r", all_files);
// Microsoft could really have picked a better delimiter!
for (i=0; i<ext_strlen; i++) {
// Since the VS Code Analysis tool is dumb...
#if defined(_MSC_VER)
#pragma warning(suppress: 6385)
#endif
if (ext_string[i] == '\r') {
#if defined(_MSC_VER)
#pragma warning(suppress: 6386)
#endif
ext_string[i] = 0;
}
}
ofn.lpstrFilter = ext_string;
ofn.nFilterIndex = 1;
ofn.lpstrInitialDir = path;
ofn.Flags = OFN_OVERWRITEPROMPT | options;
// Show Dialog
if (save) {
r = GetSaveFileNameU(&ofn);
} else {
r = GetOpenFileNameU(&ofn);
}
if (r) {
filepath = safe_strdup(selected_name);
} else {
tmp = CommDlgExtendedError();
if (tmp != 0) {
uprintf("Could not select file for %s. Error %X\n", save?"save":"open", tmp);
}
}
safe_free(ext_string);
dialog_showing--;
return filepath;
}
/*
* Create the application status bar
*/
void CreateStatusBar(void)
{
SIZE sz = {0, 0};
RECT rect;
LONG x, y, width, height;
int edge[3];
TBBUTTON tbbStatusToolbarButtons[1];
TBBUTTONINFO tbi;
HFONT hFont;
HDC hDC;
// Create the status bar (WS_CLIPSIBLINGS since we have an overlapping button)
hStatus = CreateWindowExW(0, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | SBARS_TOOLTIPS | WS_CLIPSIBLINGS,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hMainDialog,
(HMENU)IDC_STATUS, hMainInstance, NULL);
// Keep track of the status bar height
GetClientRect(hStatus, &rect);
height = rect.bottom;
// Set the font we'll use to display the '#' sign in the toolbar button
hFont = CreateFontA(-MulDiv(10, GetDeviceCaps(GetDC(hMainDialog), LOGPIXELSY), 72),
0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
0, 0, PROOF_QUALITY, 0, (nWindowsVersion >= WINDOWS_VISTA)?"Segoe UI":"Arial Unicode MS");
// Find the width of our hash sign
hDC = GetDC(hMainDialog);
SelectObject(hDC, hFont);
GetTextExtentPoint32W(hDC, L"#", 1, &sz);
if (hDC != NULL)
ReleaseDC(hMainDialog, hDC);
// Create 3 status areas
GetClientRect(hMainDialog, &rect);
edge[1] = rect.right - (int)(SB_TIMER_SECTION_SIZE * fScale);
edge[0] = edge[1] - (8 + sz.cx + 8 + 1); // There's 8 absolute pixels on right and left of the text
edge[2] = rect.right;
SendMessage(hStatus, SB_SETPARTS, (WPARAM)ARRAYSIZE(edge), (LPARAM)&edge);
// NB: To add an icon on the status bar, you can use something like this:
// SendMessage(hStatus, SB_SETICON, (WPARAM) 1, (LPARAM)LoadImage(GetLibraryHandle("rasdlg"),
// MAKEINTRESOURCE(50), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR | LR_SHARED));
// This is supposed to create a toolips for a statusbar section (when SBARS_TOOLTIPS is in use)... but doesn't :(
// SendMessageLU(hStatus, SB_SETTIPTEXT, (WPARAM)2, (LPARAM)"HELLO");
// Compute the dimensions for the hash button
x = edge[0];
if (nWindowsVersion <= WINDOWS_XP) {
x -= 1;
height -= 2;
}
y = rect.bottom - height + 1;
width = edge[1] - edge[0] - 1;
// How I wish there was a way to figure out how to make Windows controls look good
// at all scales, without adding all these crappy empirical adjustments...
if ((fScale > 1.20f) && (fScale <2.40f))
height -= 1;
if (nWindowsVersion <= WINDOWS_7)
height += 1;
// Create the status toolbar
hStatusToolbar = CreateWindowExW(WS_EX_TRANSPARENT, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_TABSTOP | WS_DISABLED |
TBSTYLE_LIST | CCS_NOPARENTALIGN | CCS_NODIVIDER | CCS_NORESIZE,
x, y, width, height, hMainDialog, (HMENU)IDC_STATUS_TOOLBAR, hMainInstance, NULL);
// Set the button properties
SendMessage(hStatusToolbar, WM_SETFONT, (WPARAM)hFont, TRUE);
SendMessage(hStatusToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
SendMessage(hStatusToolbar, TB_SETIMAGELIST, 0, (LPARAM)NULL);
SendMessage(hStatusToolbar, TB_SETDISABLEDIMAGELIST, 0, (LPARAM)NULL);
SendMessage(hStatusToolbar, TB_SETBITMAPSIZE, 0, MAKELONG(0,0));
// Set our text
memset(tbbStatusToolbarButtons, 0, sizeof(TBBUTTON));
tbbStatusToolbarButtons[0].idCommand = IDC_HASH;
tbbStatusToolbarButtons[0].fsStyle = BTNS_SHOWTEXT;
tbbStatusToolbarButtons[0].fsState = TBSTATE_ENABLED;
tbbStatusToolbarButtons[0].iString = (INT_PTR)L"#";
SendMessage(hStatusToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(hStatusToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM)&tbbStatusToolbarButtons);
SendMessage(hStatusToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(width, height - 1));
// Yeah, you'd think that TB_SETBUTTONSIZE would work for the width... but you'd be wrong.
// The only working method that actually enforces the requested width is TB_SETBUTTONINFO
tbi.cbSize = sizeof(tbi);
tbi.dwMask = TBIF_SIZE | TBIF_COMMAND;
tbi.cx = (WORD)width;
tbi.idCommand = IDC_HASH;
SendMessage(hStatusToolbar, TB_SETBUTTONINFO, (WPARAM)IDC_HASH, (LPARAM)&tbi);
// Need to resend the positioning for the toolbar to become active... One of Windows' mysteries
// Also use this opportunity to set our Z-order for tab stop
SetWindowPos(hStatusToolbar, GetDlgItem(hMainDialog, IDCANCEL), x, y, width, height, 0);
ShowWindow(hStatusToolbar, SW_SHOWNORMAL);
}
/*
* Center a dialog with regards to the main application Window or the desktop
* See http://msdn.microsoft.com/en-us/library/windows/desktop/ms644996.aspx#init_box
*/
void CenterDialog(HWND hDlg)
{
HWND hParent;
RECT rc, rcDlg, rcParent;
if ((hParent = GetParent(hDlg)) == NULL) {
hParent = GetDesktopWindow();
}
GetWindowRect(hParent, &rcParent);
GetWindowRect(hDlg, &rcDlg);
CopyRect(&rc, &rcParent);
// Offset the parent and dialog box rectangles so that right and bottom
// values represent the width and height, and then offset the parent again
// to discard space taken up by the dialog box.
OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
OffsetRect(&rc, -rc.left, -rc.top);
OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
SetWindowPos(hDlg, HWND_TOP, rcParent.left + (rc.right / 2), rcParent.top + (rc.bottom / 2) - 25, 0, 0, SWP_NOSIZE);
}
// http://stackoverflow.com/questions/431470/window-border-width-and-height-in-win32-how-do-i-get-it
SIZE GetBorderSize(HWND hDlg)
{
RECT rect = {0, 0, 0, 0};
SIZE size = {0, 0};
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hDlg, &wi);
AdjustWindowRectEx(&rect, wi.dwStyle, FALSE, wi.dwExStyle);
size.cx = rect.right - rect.left;
size.cy = rect.bottom - rect.top;
return size;
}
void ResizeMoveCtrl(HWND hDlg, HWND hCtrl, int dx, int dy, int dw, int dh, float scale)
{
RECT rect;
POINT point;
SIZE border;
GetWindowRect(hCtrl, &rect);
point.x = (right_to_left_mode && (hDlg != hCtrl))?rect.right:rect.left;
point.y = rect.top;
if (hDlg != hCtrl)
ScreenToClient(hDlg, &point);
GetClientRect(hCtrl, &rect);
// If the control has any borders (dialog, edit box), take them into account
border = GetBorderSize(hCtrl);
MoveWindow(hCtrl, point.x + (int)(scale*(float)dx), point.y + (int)(scale*(float)dy),
(rect.right - rect.left) + (int)(scale*(float)dw + border.cx),
(rect.bottom - rect.top) + (int)(scale*(float)dh + border.cy), TRUE);
InvalidateRect(hCtrl, NULL, TRUE);
}
/*
* License callback
*/
INT_PTR CALLBACK LicenseCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
long style;
HWND hLicense;
switch (message) {
case WM_INITDIALOG:
hLicense = GetDlgItem(hDlg, IDC_LICENSE_TEXT);
apply_localization(IDD_LICENSE, hDlg);
CenterDialog(hDlg);
// Suppress any inherited RTL flags
style = GetWindowLong(hLicense, GWL_EXSTYLE);
style &= ~(WS_EX_RTLREADING | WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR);
SetWindowLong(hLicense, GWL_EXSTYLE, style);
style = GetWindowLong(hLicense, GWL_STYLE);
style &= ~(ES_RIGHT);
SetWindowLong(hLicense, GWL_STYLE, style);
SetDlgItemTextA(hDlg, IDC_LICENSE_TEXT, gplv3);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
reset_localization(IDD_LICENSE);
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
}
/*
* About dialog callback
*/
INT_PTR CALLBACK AboutCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int i, dy;
const int edit_id[2] = {IDC_ABOUT_BLURB, IDC_ABOUT_COPYRIGHTS};
char about_blurb[2048];
const char* edit_text[2] = {about_blurb, additional_copyrights};
HWND hEdit[2];
TEXTRANGEW tr;
ENLINK* enl;
RECT rect;
REQRESIZE* rsz;
wchar_t wUrl[256];
static BOOL resized_already = TRUE;
switch (message) {
case WM_INITDIALOG:
resized_already = FALSE;
// Execute dialog localization
apply_localization(IDD_ABOUTBOX, hDlg);
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
if (settings_commcheck)
ShowWindow(GetDlgItem(hDlg, IDC_ABOUT_UPDATES), SW_SHOW);
static_sprintf(about_blurb, about_blurb_format, lmprintf(MSG_174|MSG_RTF),
lmprintf(MSG_175|MSG_RTF, rufus_version[0], rufus_version[1], rufus_version[2]),
right_to_left_mode?"Akeo \\\\ Pete Batard 2011-2017 © Copyright":"Copyright © 2011-2017 Pete Batard / Akeo",
lmprintf(MSG_176|MSG_RTF), lmprintf(MSG_177|MSG_RTF), lmprintf(MSG_178|MSG_RTF));
for (i=0; i<ARRAYSIZE(hEdit); i++) {
hEdit[i] = GetDlgItem(hDlg, edit_id[i]);
SendMessage(hEdit[i], EM_AUTOURLDETECT, 1, 0);
/* Can't use SetDlgItemText, because it only works with RichEdit20A... and VS insists
* on reverting to RichEdit20W as soon as you edit the dialog. You can try all the W
* methods you want, it JUST WON'T WORK unless you use EM_SETTEXTEX. Also see:
* http://blog.kowalczyk.info/article/eny/Setting-unicode-rtf-text-in-rich-edit-control.html */
SendMessageA(hEdit[i], EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)edit_text[i]);
SendMessage(hEdit[i], EM_SETSEL, -1, -1);
SendMessage(hEdit[i], EM_SETEVENTMASK, 0, ENM_LINK|((i==0)?ENM_REQUESTRESIZE:0));
SendMessage(hEdit[i], EM_SETBKGNDCOLOR, 0, (LPARAM)GetSysColor(COLOR_BTNFACE));
}
// Need to send an explicit SetSel to avoid being positioned at the end of richedit control when tabstop is used
SendMessage(hEdit[1], EM_SETSEL, 0, 0);
SendMessage(hEdit[0], EM_REQUESTRESIZE, 0, 0);
break;
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code) {
case EN_REQUESTRESIZE:
if (!resized_already) {
resized_already = TRUE;
GetWindowRect(GetDlgItem(hDlg, edit_id[0]), &rect);
dy = rect.bottom - rect.top;
rsz = (REQRESIZE *)lParam;
dy -= rsz->rc.bottom - rsz->rc.top;
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, edit_id[0]), 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, edit_id[1]), 0, -dy, 0, dy, 1.0f);
}
break;
case EN_LINK:
enl = (ENLINK*) lParam;
if (enl->msg == WM_LBUTTONUP) {
tr.lpstrText = wUrl;
tr.chrg.cpMin = enl->chrg.cpMin;
tr.chrg.cpMax = enl->chrg.cpMax;
SendMessageW(enl->nmhdr.hwndFrom, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
wUrl[ARRAYSIZE(wUrl)-1] = 0;
ShellExecuteW(hDlg, L"open", wUrl, NULL, NULL, SW_SHOWNORMAL);
}
break;
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
reset_localization(IDD_ABOUTBOX);
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
case IDC_ABOUT_LICENSE:
MyDialogBox(hMainInstance, IDD_LICENSE, hDlg, LicenseCallback);
break;
case IDC_ABOUT_UPDATES:
MyDialogBox(hMainInstance, IDD_UPDATE_POLICY, hDlg, UpdateCallback);
break;
}
break;
}
return (INT_PTR)FALSE;
}
INT_PTR CreateAboutBox(void)
{
INT_PTR r;
dialog_showing++;
r = MyDialogBox(hMainInstance, IDD_ABOUTBOX, hMainDialog, AboutCallback);
dialog_showing--;
return r;
}
/*
* We use our own MessageBox for notifications to have greater control (center, no close button, etc)
*/
INT_PTR CALLBACK NotificationCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
HFONT hDlgFont;
switch (message) {
case WM_INITDIALOG:
if (nWindowsVersion >= WINDOWS_VISTA) { // of course, this stuff doesn't work on XP!
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_NOTIFICATION_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_MORE_INFO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
}
apply_localization(IDD_NOTIFICATION, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon
if (Static_SetIcon(GetDlgItem(hDlg, IDC_NOTIFICATION_ICON), hMessageIcon) == 0) {
uprintf("Could not set dialog icon\n");
}
// Set the dialog title
if (szMessageTitle != NULL) {
SetWindowTextU(hDlg, szMessageTitle);
}
// Enable/disable the buttons and set text
if (!notification_is_question) {
SetWindowTextU(GetDlgItem(hDlg, IDNO), lmprintf(MSG_006));
} else {
ShowWindow(GetDlgItem(hDlg, IDYES), SW_SHOW);
}
if ((notification_more_info != NULL) && (notification_more_info->callback != NULL)) {
ShowWindow(GetDlgItem(hDlg, IDC_MORE_INFO), SW_SHOW);
}
// Set the control text
if (szMessageText != NULL) {
SetWindowTextU(GetDlgItem(hDlg, IDC_NOTIFICATION_TEXT), szMessageText);
}
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for(i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
case IDYES:
case IDNO:
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
case IDC_MORE_INFO:
if (notification_more_info != NULL)
MyDialogBox(hMainInstance, notification_more_info->id, hDlg, notification_more_info->callback);
break;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display a custom notification
*/
BOOL Notification(int type, const notification_info* more_info, char* title, char* format, ...)
{
BOOL ret;
va_list args;
dialog_showing++;
szMessageText = (char*)malloc(MAX_PATH);
if (szMessageText == NULL) return FALSE;
szMessageTitle = safe_strdup(title);
if (szMessageTitle == NULL) return FALSE;
va_start(args, format);
safe_vsnprintf(szMessageText, MAX_PATH-1, format, args);
va_end(args);
szMessageText[MAX_PATH-1] = 0;
notification_more_info = more_info;
notification_is_question = FALSE;
switch(type) {
case MSG_WARNING_QUESTION:
notification_is_question = TRUE;
// Fall through
case MSG_WARNING:
hMessageIcon = LoadIcon(NULL, IDI_WARNING);
break;
case MSG_ERROR:
hMessageIcon = LoadIcon(NULL, IDI_ERROR);
break;
case MSG_QUESTION:
hMessageIcon = LoadIcon(NULL, IDI_QUESTION);
notification_is_question = TRUE;
break;
case MSG_INFO:
default:
hMessageIcon = LoadIcon(NULL, IDI_INFORMATION);
break;
}
ret = (MyDialogBox(hMainInstance, IDD_NOTIFICATION, hMainDialog, NotificationCallback) == IDYES);
safe_free(szMessageText);
safe_free(szMessageTitle);
dialog_showing--;
return ret;
}
/*
* Custom dialog for radio button selection dialog
*/
INT_PTR CALLBACK SelectionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i, dh, r = -1;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
RECT rect, rect2;
HFONT hDlgFont;
HWND hCtrl;
HDC hDC;
switch (message) {
case WM_INITDIALOG:
// Don't overflow our max radio button
if (nDialogItems > (IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1 + 1)) {
uprintf("Warning: Too many options requested for Selection (%d vs %d)",
nDialogItems, IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1);
nDialogItems = IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1;
}
// TODO: This shouldn't be needed when using DS_SHELLFONT
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if (nWindowsVersion >= WINDOWS_VISTA) {
// In versions of Windows prior to Vista, the iPaddedBorderWidth member
// is not present, so we need to subtract its size from cbSize.
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
}
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_SELECTION_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
for (i = 0; i < nDialogItems; i++)
SendMessage(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
apply_localization(IDD_SELECTION, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon and set the text
Static_SetIcon(GetDlgItem(hDlg, IDC_SELECTION_ICON), LoadIcon(NULL, IDI_QUESTION));
SetWindowTextU(hDlg, szMessageTitle);
SetWindowTextU(GetDlgItem(hDlg, IDCANCEL), lmprintf(MSG_007));
SetWindowTextU(GetDlgItem(hDlg, IDC_SELECTION_TEXT), szMessageText);
for (i = 0; i < nDialogItems; i++) {
SetWindowTextU(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), szDialogItem[i]);
ShowWindow(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), SW_SHOW);
}
// Move/Resize the controls as needed to fit our text
hCtrl = GetDlgItem(hDlg, IDC_SELECTION_TEXT);
hDC = GetDC(hCtrl);
SelectFont(hDC, hDlgFont); // Yes, you *MUST* reapply the font to the DC, even after SetWindowText!
GetWindowRect(hCtrl, &rect);
dh = rect.bottom - rect.top;
DrawTextU(hDC, szMessageText, -1, &rect, DT_CALCRECT | DT_WORDBREAK);
dh = rect.bottom - rect.top - dh;
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
ResizeMoveCtrl(hDlg, hCtrl, 0, 0, 0, dh, 1.0f);
for (i = 0; i < nDialogItems; i++)
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), 0, dh, 0, 0, 1.0f);
if (nDialogItems > 2) {
GetWindowRect(GetDlgItem(hDlg, IDC_SELECTION_CHOICE2), &rect);
GetWindowRect(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + nDialogItems - 1), &rect2);
dh += rect2.top - rect.top;
}
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, dh, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, -1), 0, 0, 0, dh, 1.0f); // IDC_STATIC = -1
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_SELECTION_LINE), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDOK), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, dh, 0, 0, 1.0f);
// Set the radio selection
Button_SetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1), BST_CHECKED);
Button_SetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE2), BST_UNCHECKED);
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for (i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
for (i = 0; (i < nDialogItems) &&
(Button_GetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i)) != BST_CHECKED); i++);
if (i < nDialogItems)
r = i + 1;
// Fall through
case IDNO:
case IDCANCEL:
EndDialog(hDlg, r);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display an item selection dialog
*/
int SelectionDialog(char* title, char* message, char** choices, int size)
{
int ret;
dialog_showing++;
szMessageTitle = title;
szMessageText = message;
szDialogItem = choices;
nDialogItems = size;
ret = (int)MyDialogBox(hMainInstance, IDD_SELECTION, hMainDialog, SelectionCallback);
dialog_showing--;
return ret;
}
/*
* Custom dialog for list dialog
*/
INT_PTR CALLBACK ListCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i, dh, r = -1;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
RECT rect, rect2;
HFONT hDlgFont;
HWND hCtrl;
HDC hDC;
switch (message) {
case WM_INITDIALOG:
// Don't overflow our max radio button
if (nDialogItems > (IDC_LIST_ITEMMAX - IDC_LIST_ITEM1 + 1)) {
uprintf("Warning: Too many items requested for List (%d vs %d)",
nDialogItems, IDC_LIST_ITEMMAX - IDC_LIST_ITEM1);
nDialogItems = IDC_LIST_ITEMMAX - IDC_LIST_ITEM1;
}
// TODO: This shouldn't be needed when using DS_SHELLFONT
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if (nWindowsVersion >= WINDOWS_VISTA) {
// In versions of Windows prior to Vista, the iPaddedBorderWidth member
// is not present, so we need to subtract its size from cbSize.
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
}
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_LIST_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
for (i = 0; i < nDialogItems; i++)
SendMessage(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
apply_localization(IDD_LIST, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon and set the text
Static_SetIcon(GetDlgItem(hDlg, IDC_LIST_ICON), LoadIcon(NULL, IDI_EXCLAMATION));
SetWindowTextU(hDlg, szMessageTitle);
SetWindowTextU(GetDlgItem(hDlg, IDCANCEL), lmprintf(MSG_007));
SetWindowTextU(GetDlgItem(hDlg, IDC_LIST_TEXT), szMessageText);
for (i = 0; i < nDialogItems; i++) {
SetWindowTextU(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), szDialogItem[i]);
ShowWindow(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), SW_SHOW);
}
// Move/Resize the controls as needed to fit our text
hCtrl = GetDlgItem(hDlg, IDC_LIST_TEXT);
hDC = GetDC(hCtrl);
SelectFont(hDC, hDlgFont); // Yes, you *MUST* reapply the font to the DC, even after SetWindowText!
GetWindowRect(hCtrl, &rect);
dh = rect.bottom - rect.top;
DrawTextU(hDC, szMessageText, -1, &rect, DT_CALCRECT | DT_WORDBREAK);
dh = rect.bottom - rect.top - dh;
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
ResizeMoveCtrl(hDlg, hCtrl, 0, 0, 0, dh, 1.0f);
for (i = 0; i < nDialogItems; i++)
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), 0, dh, 0, 0, 1.0f);
if (nDialogItems > 1) {
GetWindowRect(GetDlgItem(hDlg, IDC_LIST_ITEM1), &rect);
GetWindowRect(GetDlgItem(hDlg, IDC_LIST_ITEM1 + nDialogItems - 1), &rect2);
dh += rect2.top - rect.top;
}
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, dh, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, -1), 0, 0, 0, dh, 1.0f); // IDC_STATIC = -1
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_LIST_LINE), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDOK), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, dh, 0, 0, 1.0f);
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for (i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDNO:
case IDCANCEL:
EndDialog(hDlg, r);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display a dialog with a list of items
*/
void ListDialog(char* title, char* message, char** items, int size)
{
dialog_showing++;
szMessageTitle = title;
szMessageText = message;
szDialogItem = items;
nDialogItems = size;
MyDialogBox(hMainInstance, IDD_LIST, hMainDialog, ListCallback);
dialog_showing--;
}
static struct {
HWND hTip; // Tooltip handle
HWND hCtrl; // Handle of the control the tooltip belongs to
WNDPROC original_proc;
LPWSTR wstring;
} ttlist[MAX_TOOLTIPS] = { {0} };
INT_PTR CALLBACK TooltipCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LPNMTTDISPINFOW lpnmtdi;
int i = MAX_TOOLTIPS;
// Make sure we have an original proc
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == hDlg) break;
}
if (i == MAX_TOOLTIPS)
return (INT_PTR)FALSE;
switch (message) {
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code) {
case TTN_GETDISPINFOW:
lpnmtdi = (LPNMTTDISPINFOW)lParam;
lpnmtdi->lpszText = ttlist[i].wstring;
SendMessage(hDlg, TTM_SETMAXTIPWIDTH, 0, 300);
return (INT_PTR)TRUE;
}
break;
}
#ifdef _DEBUG
// comctl32 causes issues if the tooltips are not being manipulated from the same thread as their parent controls
if (GetCurrentThreadId() != MainThreadId)
uprintf("Warning: Tooltip callback is being called from wrong thread");
#endif
return CallWindowProc(ttlist[i].original_proc, hDlg, message, wParam, lParam);
}
/*
* Create a tooltip for the control passed as first parameter
* duration sets the duration in ms. Use -1 for default
* message is an UTF-8 string
*/
BOOL CreateTooltip(HWND hControl, const char* message, int duration)
{
TOOLINFOW toolInfo = {0};
int i;
if ( (hControl == NULL) || (message == NULL) ) {
return FALSE;
}
// Destroy existing tooltip if any
DestroyTooltip(hControl);
// Find an empty slot
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == NULL) break;
}
if (i >= MAX_TOOLTIPS) {
uprintf("Maximum number of tooltips reached (%d)\n", MAX_TOOLTIPS);
return FALSE;
}
// Create the tooltip window
ttlist[i].hTip = CreateWindowExW(0, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hMainDialog, NULL,
hMainInstance, NULL);
if (ttlist[i].hTip == NULL) {
return FALSE;
}
ttlist[i].hCtrl = hControl;
// Subclass the tooltip to handle multiline
ttlist[i].original_proc = (WNDPROC)SetWindowLongPtr(ttlist[i].hTip, GWLP_WNDPROC, (LONG_PTR)TooltipCallback);
// Set the string to display (can be multiline)
ttlist[i].wstring = utf8_to_wchar(message);
// Set tooltip duration (ms)
PostMessage(ttlist[i].hTip, TTM_SETDELAYTIME, (WPARAM)TTDT_AUTOPOP, (LPARAM)duration);
// Associate the tooltip to the control
toolInfo.cbSize = sizeof(toolInfo);
toolInfo.hwnd = ttlist[i].hTip; // Set to the tooltip itself to ease up subclassing
toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS | ((right_to_left_mode)?TTF_RTLREADING:0);
// set TTF_NOTBUTTON and TTF_CENTERTIP if it isn't a button
if (!(SendMessage(hControl, WM_GETDLGCODE, 0, 0) & DLGC_BUTTON))
toolInfo.uFlags |= 0x80000000L | TTF_CENTERTIP;
toolInfo.uId = (UINT_PTR)hControl;
toolInfo.lpszText = LPSTR_TEXTCALLBACKW;
SendMessageW(ttlist[i].hTip, TTM_ADDTOOLW, 0, (LPARAM)&toolInfo);
return TRUE;
}
/* Destroy a tooltip. hCtrl = handle of the control the tooltip is associated with */
void DestroyTooltip(HWND hControl)
{
int i;
if (hControl == NULL) return;
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hCtrl == hControl) break;
}
if (i >= MAX_TOOLTIPS) return;
DestroyWindow(ttlist[i].hTip);
safe_free(ttlist[i].wstring);
ttlist[i].original_proc = NULL;
ttlist[i].hTip = NULL;
ttlist[i].hCtrl = NULL;
}
void DestroyAllTooltips(void)
{
int i, j;
for (i=0, j=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == NULL) continue;
j++;
DestroyWindow(ttlist[i].hTip);
safe_free(ttlist[i].wstring);
ttlist[i].original_proc = NULL;
ttlist[i].hTip = NULL;
ttlist[i].hCtrl = NULL;
}
}
/* Determine if a Windows is being displayed or not */
BOOL IsShown(HWND hDlg)
{
WINDOWPLACEMENT placement = {0};
placement.length = sizeof(WINDOWPLACEMENT);
if (!GetWindowPlacement(hDlg, &placement))
return FALSE;
switch (placement.showCmd) {
case SW_SHOWNORMAL:
case SW_SHOWMAXIMIZED:
case SW_SHOW:
case SW_SHOWDEFAULT:
return TRUE;
default:
return FALSE;
}
}
/* Compute the width of a dropdown list entry */
LONG GetEntryWidth(HWND hDropDown, const char *entry)
{
HDC hDC;
HFONT hFont, hDefFont = NULL;
SIZE size;
hDC = GetDC(hDropDown);
hFont = (HFONT)SendMessage(hDropDown, WM_GETFONT, 0, 0);
if (hFont != NULL)
hDefFont = (HFONT)SelectObject(hDC, hFont);
if (!GetTextExtentPointU(hDC, entry, &size))
size.cx = 0;
if (hFont != NULL)
SelectObject(hDC, hDefFont);
if (hDC != NULL)
ReleaseDC(hDropDown, hDC);
return size.cx;
}
/*
* Windows 7 taskbar icon handling (progress bar overlay, etc)
* Some platforms don't have these, so we redefine
*/
typedef enum MY_STPFLAG
{
MY_STPF_NONE = 0,
MY_STPF_USEAPPTHUMBNAILALWAYS = 0x1,
MY_STPF_USEAPPTHUMBNAILWHENACTIVE = 0x2,
MY_STPF_USEAPPPEEKALWAYS = 0x4,
MY_STPF_USEAPPPEEKWHENACTIVE = 0x8
} MY_STPFLAG;
typedef enum MY_THUMBBUTTONMASK
{
MY_THB_BITMAP = 0x1,
MY_THB_ICON = 0x2,
MY_THB_TOOLTIP = 0x4,
MY_THB_FLAGS = 0x8
} MY_THUMBBUTTONMASK;
typedef enum MY_THUMBBUTTONFLAGS
{
MY_THBF_ENABLED = 0,
MY_THBF_DISABLED = 0x1,
MY_THBF_DISMISSONCLICK = 0x2,
MY_THBF_NOBACKGROUND = 0x4,
MY_THBF_HIDDEN = 0x8,
MY_THBF_NONINTERACTIVE = 0x10
} MY_THUMBBUTTONFLAGS;
typedef struct MY_THUMBBUTTON
{
MY_THUMBBUTTONMASK dwMask;
UINT iId;
UINT iBitmap;
HICON hIcon;
WCHAR szTip[260];
MY_THUMBBUTTONFLAGS dwFlags;
} MY_THUMBBUTTON;
/*
typedef enum MY_TBPFLAG
{
TASKBAR_NOPROGRESS = 0,
TASKBAR_INDETERMINATE = 0x1,
TASKBAR_NORMAL = 0x2,
TASKBAR_ERROR = 0x4,
TASKBAR_PAUSED = 0x8
} MY_TBPFLAG;
*/
#pragma push_macro("INTERFACE")
#undef INTERFACE
#define INTERFACE my_ITaskbarList3
DECLARE_INTERFACE_(my_ITaskbarList3, IUnknown) {
STDMETHOD (QueryInterface) (THIS_ REFIID riid, LPVOID *ppvObj) PURE;
STDMETHOD_(ULONG, AddRef) (THIS) PURE;
STDMETHOD_(ULONG, Release) (THIS) PURE;
STDMETHOD (HrInit) (THIS) PURE;
STDMETHOD (AddTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (DeleteTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (ActivateTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (SetActiveAlt) (THIS_ HWND hwnd) PURE;
STDMETHOD (MarkFullscreenWindow) (THIS_ HWND hwnd, int fFullscreen) PURE;
STDMETHOD (SetProgressValue) (THIS_ HWND hwnd, ULONGLONG ullCompleted, ULONGLONG ullTotal) PURE;
STDMETHOD (SetProgressState) (THIS_ HWND hwnd, TASKBAR_PROGRESS_FLAGS tbpFlags) PURE;
STDMETHOD (RegisterTab) (THIS_ HWND hwndTab,HWND hwndMDI) PURE;
STDMETHOD (UnregisterTab) (THIS_ HWND hwndTab) PURE;
STDMETHOD (SetTabOrder) (THIS_ HWND hwndTab, HWND hwndInsertBefore) PURE;
STDMETHOD (SetTabActive) (THIS_ HWND hwndTab, HWND hwndMDI, DWORD dwReserved) PURE;
STDMETHOD (ThumbBarAddButtons) (THIS_ HWND hwnd, UINT cButtons, MY_THUMBBUTTON* pButton) PURE;
STDMETHOD (ThumbBarUpdateButtons) (THIS_ HWND hwnd, UINT cButtons, MY_THUMBBUTTON* pButton) PURE;
STDMETHOD (ThumbBarSetImageList) (THIS_ HWND hwnd, HIMAGELIST himl) PURE;
STDMETHOD (SetOverlayIcon) (THIS_ HWND hwnd, HICON hIcon, LPCWSTR pszDescription) PURE;
STDMETHOD (SetThumbnailTooltip) (THIS_ HWND hwnd, LPCWSTR pszTip) PURE;
STDMETHOD (SetThumbnailClip) (THIS_ HWND hwnd, RECT *prcClip) PURE;
};
const IID my_IID_ITaskbarList3 =
{ 0xea1afb91, 0x9e28, 0x4b86, { 0x90, 0xe9, 0x9e, 0x9f, 0x8a, 0x5e, 0xef, 0xaf } };
const IID my_CLSID_TaskbarList =
{ 0x56fdf344, 0xfd6d, 0x11d0, { 0x95, 0x8a ,0x0, 0x60, 0x97, 0xc9, 0xa0 ,0x90 } };
static my_ITaskbarList3* ptbl = NULL;
// Create a taskbar icon progressbar
BOOL CreateTaskbarList(void)
{
HRESULT hr;
if (nWindowsVersion < WINDOWS_7)
// Only valid for Windows 7 or later
return FALSE;
hr = CoCreateInstance(&my_CLSID_TaskbarList, NULL, CLSCTX_ALL, &my_IID_ITaskbarList3, (LPVOID)&ptbl);
if (FAILED(hr)) {
uprintf("CoCreateInstance for TaskbarList failed: error %X\n", hr);
ptbl = NULL;
return FALSE;
}
return TRUE;
}
BOOL SetTaskbarProgressState(TASKBAR_PROGRESS_FLAGS tbpFlags)
{
if (ptbl == NULL)
return FALSE;
return !FAILED(ptbl->lpVtbl->SetProgressState(ptbl, hMainDialog, tbpFlags));
}
BOOL SetTaskbarProgressValue(ULONGLONG ullCompleted, ULONGLONG ullTotal)
{
if (ptbl == NULL)
return FALSE;
return !FAILED(ptbl->lpVtbl->SetProgressValue(ptbl, hMainDialog, ullCompleted, ullTotal));
}
#pragma pop_macro("INTERFACE")
/*
* Update policy and settings dialog callback
*/
INT_PTR CALLBACK UpdateCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int dy;
RECT rect;
REQRESIZE* rsz;
HWND hPolicy;
static HWND hFrequency, hBeta;
int32_t freq;
char update_policy_text[4096];
static BOOL resized_already = TRUE;
switch (message) {
case WM_INITDIALOG:
resized_already = FALSE;
hUpdatesDlg = hDlg;
apply_localization(IDD_UPDATE_POLICY, hDlg);
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
hFrequency = GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY);
hBeta = GetDlgItem(hDlg, IDC_INCLUDE_BETAS);
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_013)), -1));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_030, lmprintf(MSG_014))), 86400));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_015)), 604800));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_016)), 2629800));
freq = ReadSetting32(SETTING_UPDATE_INTERVAL);
EnableWindow(GetDlgItem(hDlg, IDC_CHECK_NOW), (freq != 0));
EnableWindow(hBeta, (freq >= 0));
switch(freq) {
case -1:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 0));
break;
case 0:
case 86400:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 1));
break;
case 604800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 2));
break;
case 2629800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 3));
break;
default:
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_017)), freq));
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 4));
break;
}
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_008)));
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_009)));
IGNORE_RETVAL(ComboBox_SetCurSel(hBeta, ReadSettingBool(SETTING_INCLUDE_BETAS)?0:1));
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
SendMessage(hPolicy, EM_AUTOURLDETECT, 1, 0);
static_sprintf(update_policy_text, update_policy, lmprintf(MSG_179|MSG_RTF),
lmprintf(MSG_180|MSG_RTF), lmprintf(MSG_181|MSG_RTF), lmprintf(MSG_182|MSG_RTF), lmprintf(MSG_183|MSG_RTF),
lmprintf(MSG_184|MSG_RTF), lmprintf(MSG_185|MSG_RTF), lmprintf(MSG_186|MSG_RTF));
SendMessageA(hPolicy, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update_policy_text);
SendMessage(hPolicy, EM_SETSEL, -1, -1);
SendMessage(hPolicy, EM_SETEVENTMASK, 0, ENM_LINK|ENM_REQUESTRESIZE);
SendMessageA(hPolicy, EM_SETBKGNDCOLOR, 0, (LPARAM)GetSysColor(COLOR_BTNFACE));
SendMessage(hPolicy, EM_REQUESTRESIZE, 0, 0);
break;
case WM_NOTIFY:
if ((((LPNMHDR)lParam)->code == EN_REQUESTRESIZE) && (!resized_already)) {
resized_already = TRUE;
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
GetWindowRect(hPolicy, &rect);
dy = rect.bottom - rect.top;
rsz = (REQRESIZE *)lParam;
dy -= rsz->rc.bottom - rsz->rc.top + 6; // add the border
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, hPolicy, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_SETTINGS_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_FREQUENCY_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_INCLUDE_BETAS_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_INCLUDE_BETAS), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_CHECK_NOW_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_CHECK_NOW), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, -dy, 0, 0, 1.0f);
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
reset_localization(IDD_UPDATE_POLICY);
EndDialog(hDlg, LOWORD(wParam));
hUpdatesDlg = NULL;
return (INT_PTR)TRUE;
case IDC_CHECK_NOW:
CheckForUpdates(TRUE);
return (INT_PTR)TRUE;
case IDC_UPDATE_FREQUENCY:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
freq = (int32_t)ComboBox_GetItemData(hFrequency, ComboBox_GetCurSel(hFrequency));
WriteSetting32(SETTING_UPDATE_INTERVAL, (DWORD)freq);
EnableWindow(hBeta, (freq >= 0));
return (INT_PTR)TRUE;
case IDC_INCLUDE_BETAS:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
WriteSettingBool(SETTING_INCLUDE_BETAS, ComboBox_GetCurSel(hBeta) == 0);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Initial update check setup
*/
BOOL SetUpdateCheck(void)
{
BOOL enable_updates;
uint64_t commcheck = _GetTickCount64();
notification_info more_info = { IDD_UPDATE_POLICY, UpdateCallback };
char filename[MAX_PATH] = "", exename[] = APPLICATION_NAME ".exe";
size_t fn_len, exe_len;
// Test if we can read and write settings. If not, forget it.
WriteSetting64(SETTING_COMM_CHECK, commcheck);
if (ReadSetting64(SETTING_COMM_CHECK) != commcheck)
return FALSE;
settings_commcheck = TRUE;
// If the update interval is not set, this is the first time we run so prompt the user
if (ReadSetting32(SETTING_UPDATE_INTERVAL) == 0) {
// Add a hack for people who'd prefer the app not to prompt about update settings on first run.
// If the executable is called "rufus.exe", without version, we disable the prompt
GetModuleFileNameU(NULL, filename, sizeof(filename));
fn_len = safe_strlen(filename);
exe_len = safe_strlen(exename);
#if !defined(_DEBUG) // Don't allow disabling update prompt, unless it's a release
if ((fn_len > exe_len) && (safe_stricmp(&filename[fn_len-exe_len], exename) == 0)) {
uprintf("Short name used - Disabling initial update policy prompt\n");
enable_updates = TRUE;
} else {
#endif
enable_updates = Notification(MSG_QUESTION, &more_info, lmprintf(MSG_004), lmprintf(MSG_005));
#if !defined(_DEBUG)
}
#endif
if (!enable_updates) {
WriteSetting32(SETTING_UPDATE_INTERVAL, -1);
return FALSE;
}
// If the user hasn't set the interval in the dialog, set to default
if ( (ReadSetting32(SETTING_UPDATE_INTERVAL) == 0) ||
((ReadSetting32(SETTING_UPDATE_INTERVAL) == -1) && enable_updates) )
WriteSetting32(SETTING_UPDATE_INTERVAL, 86400);
}
return TRUE;
}
static void CreateStaticFont(HDC dc, HFONT* hyperlink_font) {
TEXTMETRIC tm;
LOGFONT lf;
if (*hyperlink_font != NULL)
return;
GetTextMetrics(dc, &tm);
lf.lfHeight = tm.tmHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = tm.tmWeight;
lf.lfItalic = tm.tmItalic;
lf.lfUnderline = TRUE;
lf.lfStrikeOut = tm.tmStruckOut;
lf.lfCharSet = tm.tmCharSet;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = tm.tmPitchAndFamily;
GetTextFace(dc, LF_FACESIZE, lf.lfFaceName);
*hyperlink_font = CreateFontIndirect(&lf);
}
/*
* Work around the limitations of edit control, to display a hand cursor for hyperlinks
* NB: The LTEXT control must have SS_NOTIFY attribute for this to work
*/
INT_PTR CALLBACK update_subclass_callback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_SETCURSOR:
if ((HWND)wParam == GetDlgItem(hDlg, IDC_WEBSITE)) {
SetCursor(LoadCursor(NULL, IDC_HAND));
return (INT_PTR)TRUE;
}
break;
}
return CallWindowProc(update_original_proc, hDlg, message, wParam, lParam);
}
/*
* New version notification dialog
*/
INT_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
char cmdline[] = APPLICATION_NAME " -w 150";
static char* filepath = NULL;
static int download_status = 0;
LONG i;
HWND hNotes;
STARTUPINFOA si;
PROCESS_INFORMATION pi;
HFONT hyperlink_font = NULL;
EXT_DECL(dl_ext, NULL, __VA_GROUP__("*.exe"), __VA_GROUP__(lmprintf(MSG_037)));
switch (message) {
case WM_INITDIALOG:
apply_localization(IDD_NEW_VERSION, hDlg);
download_status = 0;
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Subclass the callback so that we can change the cursor
update_original_proc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)update_subclass_callback);
hNotes = GetDlgItem(hDlg, IDC_RELEASE_NOTES);
SendMessage(hNotes, EM_AUTOURLDETECT, 1, 0);
SendMessageA(hNotes, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update.release_notes);
SendMessage(hNotes, EM_SETSEL, -1, -1);
SendMessage(hNotes, EM_SETEVENTMASK, 0, ENM_LINK);
SetWindowTextU(GetDlgItem(hDlg, IDC_YOUR_VERSION), lmprintf(MSG_018,
rufus_version[0], rufus_version[1], rufus_version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_LATEST_VERSION), lmprintf(MSG_019,
update.version[0], update.version[1], update.version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD_URL), update.download_url);
SendMessage(GetDlgItem(hDlg, IDC_PROGRESS), PBM_SETRANGE, 0, (MAX_PROGRESS<<16) & 0xFFFF0000);
if (update.download_url == NULL)
EnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);
break;
case WM_CTLCOLORSTATIC:
if ((HWND)lParam != GetDlgItem(hDlg, IDC_WEBSITE))
return FALSE;
// Change the font for the hyperlink
SetBkMode((HDC)wParam, TRANSPARENT);
CreateStaticFont((HDC)wParam, &hyperlink_font);
SelectObject((HDC)wParam, hyperlink_font);
SetTextColor((HDC)wParam, RGB(0,0,125)); // DARK_BLUE
return (INT_PTR)CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
if (download_status != 1) {
reset_localization(IDD_NEW_VERSION);
safe_free(filepath);
EndDialog(hDlg, LOWORD(wParam));
}
return (INT_PTR)TRUE;
case IDC_WEBSITE:
ShellExecuteA(hDlg, "open", RUFUS_URL, NULL, NULL, SW_SHOWNORMAL);
break;
case IDC_DOWNLOAD: // Also doubles as abort and launch function
switch(download_status) {
case 1: // Abort
FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_CANCELLED;
download_status = 0;
break;
case 2: // Launch newer version and close this one
Sleep(1000); // Add a delay on account of antivirus scanners
if (ValidateSignature(hDlg, filepath) != NO_ERROR)
break;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (!CreateProcessU(filepath, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
PrintInfo(0, MSG_214);
uprintf("Failed to launch new application: %s\n", WindowsErrorString());
} else {
PrintInfo(0, MSG_213);
PostMessage(hDlg, WM_COMMAND, (WPARAM)IDCLOSE, 0);
PostMessage(hMainDialog, WM_CLOSE, 0, 0);
}
break;
default: // Download
if (update.download_url == NULL) {
uprintf("Could not get download URL\n");
break;
}
for (i=(int)strlen(update.download_url); (i>0)&&(update.download_url[i]!='/'); i--);
dl_ext.filename = &update.download_url[i+1];
filepath = FileDialog(TRUE, app_dir, &dl_ext, OFN_NOCHANGEDIR);
if (filepath == NULL) {
uprintf("Could not get save path\n");
break;
}
// Opening the File Dialog will make us lose tabbing focus - set it back
SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hDlg, IDC_DOWNLOAD), TRUE);
DownloadFileThreaded(update.download_url, filepath, hDlg);
break;
}
return (INT_PTR)TRUE;
}
break;
case UM_PROGRESS_INIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_038));
FormatStatus = 0;
download_status = 1;
return (INT_PTR)TRUE;
case UM_PROGRESS_EXIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE);
if (wParam) {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_039));
download_status = 2;
} else {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_040));
download_status = 0;
}
return (INT_PTR)TRUE;
}
return (INT_PTR)FALSE;
}
void DownloadNewVersion(void)
{
MyDialogBox(hMainInstance, IDD_NEW_VERSION, hMainDialog, NewVersionCallback);
}
void SetTitleBarIcon(HWND hDlg)
{
int i16, s16, s32;
HICON hSmallIcon, hBigIcon;
// High DPI scaling
i16 = GetSystemMetrics(SM_CXSMICON);
// Adjust icon size lookup
s16 = i16;
s32 = (int)(32.0f*fScale);
if (s16 >= 54)
s16 = 64;
else if (s16 >= 40)
s16 = 48;
else if (s16 >= 28)
s16 = 32;
else if (s16 >= 20)
s16 = 24;
if (s32 >= 54)
s32 = 64;
else if (s32 >= 40)
s32 = 48;
else if (s32 >= 28)
s32 = 32;
else if (s32 >= 20)
s32 = 24;
// Create the title bar icon
hSmallIcon = (HICON)LoadImage(hMainInstance, MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, s16, s16, 0);
SendMessage (hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hSmallIcon);
hBigIcon = (HICON)LoadImage(hMainInstance, MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, s32, s32, 0);
SendMessage (hDlg, WM_SETICON, ICON_BIG, (LPARAM)hBigIcon);
}
// Return the onscreen size of the text displayed by a control
SIZE GetTextSize(HWND hCtrl)
{
SIZE sz = {0, 0};
HDC hDC;
wchar_t *wstr = NULL;
int len;
HFONT hFont;
// Compute the size of the text
hDC = GetDC(hCtrl);
if (hDC == NULL)
goto out;
hFont = (HFONT)SendMessageA(hCtrl, WM_GETFONT, 0, 0);
if (hFont == NULL)
goto out;
SelectObject(hDC, hFont);
len = GetWindowTextLengthW(hCtrl);
if (len <= 0)
goto out;
wstr = calloc(len + 1, sizeof(wchar_t));
if (wstr == NULL)
goto out;
if (GetWindowTextW(hCtrl, wstr, len + 1) > 0)
GetTextExtentPoint32W(hDC, wstr, len, &sz);
out:
safe_free(wstr);
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
return sz;
}
/*
* The following is used to work around dialog template limitations when switching from LTR to RTL
* or switching the font. This avoids having to multiply similar templates in the RC.
* TODO: Can we use http://stackoverflow.com/questions/6057239/which-font-is-the-default-for-mfc-dialog-controls?
* TODO: We are supposed to use Segoe with font size 9 in Vista or later
*/
// Produce a dialog template from our RC, and update its RTL and Font settings dynamically
// See http://blogs.msdn.com/b/oldnewthing/archive/2004/06/21/163596.aspx as well as
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms645389.aspx for a description
// of the Dialog structure
LPCDLGTEMPLATE GetDialogTemplate(int Dialog_ID)
{
int i;
const char thai_id[] = "th-TH";
size_t len;
DWORD size;
DWORD* dwBuf;
WCHAR* wBuf;
LPCDLGTEMPLATE rcTemplate = (LPCDLGTEMPLATE) GetResource(hMainInstance, MAKEINTRESOURCEA(Dialog_ID),
_RT_DIALOG, get_name_from_id(Dialog_ID), &size, TRUE);
if ((size == 0) || (rcTemplate == NULL)) {
safe_free(rcTemplate);
return NULL;
}
if (right_to_left_mode) {
// Add the RTL styles into our RC copy, so that we don't have to multiply dialog definitions in the RC
dwBuf = (DWORD*)rcTemplate;
dwBuf[2] = WS_EX_RTLREADING | WS_EX_APPWINDOW | WS_EX_LAYOUTRTL;
}
// All our dialogs are set to use 'Segoe UI Symbol' by default:
// 1. So that we can replace the font name with 'MS Shell Dlg' (XP) or 'Segoe UI'
// 2. So that Thai displays properly on RTF controls as it won't work with regular
// 'Segoe UI'... but Cyrillic won't work with 'Segoe UI Symbol'
// If 'Segoe UI Symbol' is available, and we are using Thai, we're done here
if (IsFontAvailable("Segoe UI Symbol") && (selected_locale != NULL)
&& (safe_strcmp(selected_locale->txt[0], thai_id) == 0))
return rcTemplate;
// 'Segoe UI Symbol' cannot be used => Fall back to the best we have
wBuf = (WCHAR*)rcTemplate;
wBuf = &wBuf[14]; // Move to class name
// Skip class name and title
for (i = 0; i<2; i++) {
if (*wBuf == 0xFFFF)
wBuf = &wBuf[2]; // Ordinal
else
wBuf = &wBuf[wcslen(wBuf) + 1]; // String
}
// NB: to change the font size to 9, you can use
// wBuf[0] = 0x0009;
wBuf = &wBuf[3];
// Make sure we are where we want to be and adjust the font
if (wcscmp(L"Segoe UI Symbol", wBuf) == 0) {
uintptr_t src, dst, start = (uintptr_t)rcTemplate;
// We can't simply zero the characters we don't want, as the size of the font
// string determines the next item lookup. So we must memmove the remaining of
// our buffer. Oh, and those items are DWORD aligned.
if ((nWindowsVersion > WINDOWS_XP) && IsFontAvailable("Segoe UI")) {
// 'Segoe UI Symbol' -> 'Segoe UI'
wBuf[8] = 0;
} else {
wcscpy(wBuf, L"MS Shell Dlg");
}
len = wcslen(wBuf);
wBuf[len + 1] = 0;
dst = (uintptr_t)&wBuf[len + 2];
dst &= ~3;
src = (uintptr_t)&wBuf[17];
src &= ~3;
memmove((void*)dst, (void*)src, size - (src - start));
} else {
uprintf("Could not locate font for %s!", get_name_from_id(Dialog_ID));
}
return rcTemplate;
}
HWND MyCreateDialog(HINSTANCE hInstance, int Dialog_ID, HWND hWndParent, DLGPROC lpDialogFunc)
{
LPCDLGTEMPLATE rcTemplate = GetDialogTemplate(Dialog_ID);
HWND hDlg = CreateDialogIndirect(hInstance, rcTemplate, hWndParent, lpDialogFunc);
safe_free(rcTemplate);
return hDlg;
}
INT_PTR MyDialogBox(HINSTANCE hInstance, int Dialog_ID, HWND hWndParent, DLGPROC lpDialogFunc)
{
INT_PTR ret;
LPCDLGTEMPLATE rcTemplate = GetDialogTemplate(Dialog_ID);
// A DialogBox doesn't handle reduce/restore so it won't pass restore messages to the
// main dialog if the main dialog was minimized. This can result in situations where the
// user cannot restore the main window if a new dialog prompt was triggered while the
// main dialog was reduced => Ensure the main dialog is visible before we display anything.
ShowWindow(hMainDialog, SW_NORMAL);
ret = DialogBoxIndirect(hMainInstance, rcTemplate, hWndParent, lpDialogFunc);
safe_free(rcTemplate);
return ret;
}
/*
* The following function calls are used to automatically detect and close the native
* Windows format prompt "You must format the disk in drive X:". To do that, we use an
* event hook that gets triggered whenever a window is placed in the foreground.
* In that hook, we look for a dialog that has style WS_POPUPWINDOW and has the relevant
* title. However, because the title in itself is too generic (the expectation is that
* it will be "Microsoft Windows") we also enumerate all the child controls from that
* prompt, using another callback, until we find one that contains the text we expect
* for the "Format disk" button.
* Oh, and since all of these strings are localized, we must first pick them up from
* the relevant mui (something like "C:\Windows\System32\en-GB\shell32.dll.mui")
*/
static BOOL CALLBACK FormatPromptCallback(HWND hWnd, LPARAM lParam)
{
char str[128];
BOOL *found = (BOOL*)lParam;
if (GetWindowTextU(hWnd, str, sizeof(str)) == 0)
return TRUE;
if (safe_strcmp(str, fp_button_str) == 0)
*found = TRUE;
return TRUE;
}
static void CALLBACK FormatPromptHook(HWINEVENTHOOK hWinEventHook, DWORD Event, HWND hWnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
char str[128];
BOOL found;
if (Event == EVENT_SYSTEM_FOREGROUND) {
if (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUPWINDOW) {
str[0] = 0;
GetWindowTextU(hWnd, str, sizeof(str));
if (safe_strcmp(str, fp_title_str) == 0) {
found = FALSE;
EnumChildWindows(hWnd, FormatPromptCallback, (LPARAM)&found);
if (found) {
SendMessage(hWnd, WM_COMMAND, (WPARAM)IDCANCEL, (LPARAM)0);
uprintf("Closed Windows format prompt");
}
}
}
}
}
BOOL SetFormatPromptHook(void)
{
HMODULE mui_lib;
char mui_path[MAX_PATH];
static char title_str[128], button_str[128];
if (fp_weh != NULL)
return TRUE; // No need to set again if active
// Fetch the localized strings in the relevant
static_sprintf(mui_path, "%s\\%s\\shell32.dll.mui", system_dir, GetCurrentMUI());
mui_lib = LoadLibraryU(mui_path);
if (mui_lib != NULL) {
// 4097 = "You need to format the disk in drive %c: before you can use it." (dialog text)
// 4125 = "Microsoft Windows" (dialog title)
// 4126 = "Format disk" (button)
if (LoadStringU(mui_lib, 4125, title_str, sizeof(title_str)) > 0)
fp_title_str = title_str;
else
uprintf("Warning: Could not locate localized format prompt title string in '%s': %s", mui_path, WindowsErrorString());
if (LoadStringU(mui_lib, 4126, button_str, sizeof(button_str)) > 0)
fp_button_str = button_str;
else
uprintf("Warning: Could not locate localized format prompt button string in '%s': %s", mui_path, WindowsErrorString());
FreeLibrary(mui_lib);
}
fp_weh = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL,
FormatPromptHook, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
return (fp_weh != NULL);
}
void ClrFormatPromptHook(void) {
UnhookWinEvent(fp_weh);
fp_weh = NULL;
}
void FlashTaskbar(HANDLE handle)
{
FLASHWINFO pf;
if (handle == NULL)
return;
pf.cbSize = sizeof(FLASHWINFO);
pf.hwnd = handle;
// Could also use FLASHW_ALL to flash the main dialog)
pf.dwFlags = FLASHW_TIMER | FLASHW_TRAY;
pf.uCount = 5;
pf.dwTimeout = 75;
FlashWindowEx(&pf);
}
#ifdef RUFUS_TEST
static __inline LPWORD lpwAlign(LPWORD addr)
{
return (LPWORD)((((uintptr_t)addr) + 3) & (~3));
}
INT_PTR CALLBACK SelectionDynCallback(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int r = -1;
switch (message) {
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
r = 0;
case IDCANCEL:
EndDialog(hwndDlg, r);
return (INT_PTR)TRUE;
}
}
return FALSE;
}
int SelectionDyn(char* title, char* message, char** szChoice, int nChoices)
{
#define ID_RADIO 12345
LPCWSTR lpwszTypeFace = L"MS Shell Dlg";
LPDLGTEMPLATEA lpdt;
LPDLGITEMTEMPLATEA lpdit;
LPCWSTR lpwszCaption;
LPWORD lpw;
LPWSTR lpwsz;
int i, ret, nchar;
lpdt = (LPDLGTEMPLATE)calloc(512 + nChoices * 256, 1);
// Set up a dialog window
lpdt->style = WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION | DS_MODALFRAME | DS_CENTER | DS_SHELLFONT;
lpdt->cdit = 2 + nChoices;
lpdt->x = 10;
lpdt->y = 10;
lpdt->cx = 300;
lpdt->cy = 100;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms645394.aspx:
// In a standard template for a dialog box, the DLGTEMPLATE structure is always immediately followed by
// three variable-length arrays that specify the menu, class, and title for the dialog box.
// When the DS_SETFONT style is specified, these arrays are also followed by a 16-bit value specifying
// point size and another variable-length array specifying a typeface name. Each array consists of one
// or more 16-bit elements. The menu, class, title, and font arrays must be aligned on WORD boundaries.
lpw = (LPWORD)(&lpdt[1]);
*lpw++ = 0; // No menu
*lpw++ = 0; // Default dialog class
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, title, -1, lpwsz, 50);
lpw += nchar;
// Set point size and typeface name if required
if (lpdt->style & (DS_SETFONT | DS_SHELLFONT)) {
*lpw++ = 8;
for (lpwsz = (LPWSTR)lpw, lpwszCaption = lpwszTypeFace; (*lpwsz++ = *lpwszCaption++) != 0; );
lpw = (LPWORD)lpwsz;
}
// Add an OK button
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON;
lpdit->x = 10;
lpdit->y = 70;
lpdit->cx = 50;
lpdit->cy = 14;
lpdit->id = IDOK;
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080; // Button class
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, "OK", -1, lpwsz, 50);
lpw += nchar;
*lpw++ = 0; // No creation data
// Add a Cancel button
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->x = 90;
lpdit->y = 70;
lpdit->cx = 50;
lpdit->cy = 14;
lpdit->id = IDCANCEL;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON;
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080;
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, lmprintf(MSG_007), -1, lpwsz, 50);
lpw += nchar;
*lpw++ = 0;
// Add radio buttons
for (i = 0; i < nChoices; i++) {
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->x = 10;
lpdit->y = 10 + 15 * i;
lpdit->cx = 40;
lpdit->cy = 20;
lpdit->id = ID_RADIO;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON | (i == 0 ? WS_GROUP : 0);
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080;
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, szChoice[i], -1, lpwsz, 150);
lpw += nchar;
*lpw++ = 0;
}
ret = (int)DialogBoxIndirect(hMainInstance, (LPDLGTEMPLATE)lpdt, hMainDialog, (DLGPROC)SelectionDynCallback);
free(lpdt);
return ret;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-494/c/bad_2732_3 |
crossvul-cpp_data_good_2732_1 | /*
* Rufus: The Reliable USB Formatting Utility
* PKI functions (code signing, etc.)
* Copyright © 2015-2016 Pete Batard <pete@akeo.ie>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <wincrypt.h>
#include <wintrust.h>
#include "rufus.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
// Signatures names we accept (may be suffixed, but the signature should start with one of those)
const char* cert_name[3] = { "Akeo Consulting", "Akeo Systems", "Pete Batard" };
typedef struct {
LPWSTR lpszProgramName;
LPWSTR lpszPublisherLink;
LPWSTR lpszMoreInfoLink;
} SPROG_PUBLISHERINFO, *PSPROG_PUBLISHERINFO;
/*
* FormatMessage does not handle PKI errors
*/
const char* WinPKIErrorString(void)
{
static char error_string[64];
DWORD error_code = GetLastError();
if (((error_code >> 16) != 0x8009) && ((error_code >> 16) != 0x800B))
return WindowsErrorString();
switch (error_code) {
case NTE_BAD_UID:
return "Bad UID.";
case CRYPT_E_MSG_ERROR:
return "An error occurred while performing an operation on a cryptographic message.";
case CRYPT_E_UNKNOWN_ALGO:
return "Unknown cryptographic algorithm.";
case CRYPT_E_INVALID_MSG_TYPE:
return "Invalid cryptographic message type.";
case CRYPT_E_HASH_VALUE:
return "The hash value is not correct";
case CRYPT_E_ISSUER_SERIALNUMBER:
return "Invalid issuer and/or serial number.";
case CRYPT_E_BAD_LEN:
return "The length specified for the output data was insufficient.";
case CRYPT_E_BAD_ENCODE:
return "An error occurred during encode or decode operation.";
case CRYPT_E_FILE_ERROR:
return "An error occurred while reading or writing to a file.";
case CRYPT_E_NOT_FOUND:
return "Cannot find object or property.";
case CRYPT_E_EXISTS:
return "The object or property already exists.";
case CRYPT_E_NO_PROVIDER:
return "No provider was specified for the store or object.";
case CRYPT_E_DELETED_PREV:
return "The previous certificate or CRL context was deleted.";
case CRYPT_E_NO_MATCH:
return "Cannot find the requested object.";
case CRYPT_E_UNEXPECTED_MSG_TYPE:
case CRYPT_E_NO_KEY_PROPERTY:
case CRYPT_E_NO_DECRYPT_CERT:
return "Private key or certificate issue";
case CRYPT_E_BAD_MSG:
return "Not a cryptographic message.";
case CRYPT_E_NO_SIGNER:
return "The signed cryptographic message does not have a signer for the specified signer index.";
case CRYPT_E_REVOKED:
return "The certificate is revoked.";
case CRYPT_E_NO_REVOCATION_DLL:
case CRYPT_E_NO_REVOCATION_CHECK:
case CRYPT_E_REVOCATION_OFFLINE:
case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
return "Cannot check certificate revocation.";
case CRYPT_E_INVALID_NUMERIC_STRING:
case CRYPT_E_INVALID_PRINTABLE_STRING:
case CRYPT_E_INVALID_IA5_STRING:
case CRYPT_E_INVALID_X500_STRING:
case CRYPT_E_NOT_CHAR_STRING:
return "Invalid string.";
case CRYPT_E_SECURITY_SETTINGS:
return "The cryptographic operation failed due to a local security option setting.";
case CRYPT_E_NO_VERIFY_USAGE_CHECK:
case CRYPT_E_VERIFY_USAGE_OFFLINE:
return "Cannot complete usage check.";
case CRYPT_E_NO_TRUSTED_SIGNER:
return "None of the signers of the cryptographic message or certificate trust list is trusted.";
case CERT_E_UNTRUSTEDROOT:
return "The root certificate is not trusted.";
case TRUST_E_NOSIGNATURE:
return "Not digitally signed.";
case TRUST_E_EXPLICIT_DISTRUST:
return "One of the certificates used was marked as untrusted by the user.";
default:
static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code);
return error_string;
}
}
// Mostly from https://support.microsoft.com/en-us/kb/323809
char* GetSignatureName(const char* path)
{
static char szSubjectName[128];
char *p = NULL, *mpath = NULL;
BOOL r;
HMODULE hm;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
PCCERT_CONTEXT pCertContext = NULL;
DWORD dwSize, dwEncoding, dwContentType, dwFormatType, dwSubjectSize;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
PCMSG_SIGNER_INFO pCounterSignerInfo = NULL;
DWORD dwSignerInfo = 0;
CERT_INFO CertInfo = { 0 };
SPROG_PUBLISHERINFO ProgPubInfo = { 0 };
wchar_t *szFileName;
// If the path is NULL, get the signature of the current runtime
if (path == NULL) {
szFileName = calloc(MAX_PATH, sizeof(wchar_t));
if (szFileName == NULL)
return NULL;
hm = GetModuleHandle(NULL);
if (hm == NULL) {
uprintf("PKI: Could not get current executable handle: %s", WinPKIErrorString());
return NULL;
}
dwSize = GetModuleFileNameW(hm, szFileName, MAX_PATH);
if ((dwSize == 0) || ((dwSize == MAX_PATH) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))) {
uprintf("PKI: Could not get module filename: %s", WinPKIErrorString());
return NULL;
}
mpath = wchar_to_utf8(szFileName);
} else {
szFileName = utf8_to_wchar(path);
}
// Get message handle and store handle from the signed file.
r = CryptQueryObject(CERT_QUERY_OBJECT_FILE, szFileName,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY,
0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, NULL);
if (!r) {
uprintf("PKI: Failed to get signature for '%s': %s", (path==NULL)?mpath:path, WinPKIErrorString());
goto out;
}
// Get signer information size.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
if (!r) {
uprintf("PKI: Failed to get signer size: %s", WinPKIErrorString());
goto out;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSignerInfo, 1);
if (!pSignerInfo) {
uprintf("PKI: Could not allocate memory for signer information");
goto out;
}
// Get Signer Information.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfo);
if (!r) {
uprintf("PKI: Failed to get signer information: %s", WinPKIErrorString());
goto out;
}
// Search for the signer certificate in the temporary certificate store.
CertInfo.Issuer = pSignerInfo->Issuer;
CertInfo.SerialNumber = pSignerInfo->SerialNumber;
pCertContext = CertFindCertificateInStore(hStore, ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)&CertInfo, NULL);
if (!pCertContext) {
uprintf("PKI: Failed to locate signer certificate in temporary store: %s", WinPKIErrorString());
goto out;
}
// Isolate the signing certificate subject name
dwSubjectSize = CertGetNameStringA(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
szSubjectName, sizeof(szSubjectName));
if (dwSubjectSize <= 1) {
uprintf("PKI: Failed to get Subject Name");
goto out;
}
uprintf("Downloaded executable is signed by '%s'", szSubjectName);
p = szSubjectName;
out:
safe_free(mpath);
safe_free(szFileName);
safe_free(ProgPubInfo.lpszProgramName);
safe_free(ProgPubInfo.lpszPublisherLink);
safe_free(ProgPubInfo.lpszMoreInfoLink);
safe_free(pSignerInfo);
safe_free(pCounterSignerInfo);
if (pCertContext != NULL)
CertFreeCertificateContext(pCertContext);
if (hStore != NULL)
CertCloseStore(hStore, 0);
if (hMsg != NULL)
CryptMsgClose(hMsg);
return p;
}
// From https://msdn.microsoft.com/en-us/library/windows/desktop/aa382384.aspx
LONG ValidateSignature(HWND hDlg, const char* path)
{
LONG r;
WINTRUST_DATA trust_data = { 0 };
WINTRUST_FILE_INFO trust_file = { 0 };
GUID guid_generic_verify = // WINTRUST_ACTION_GENERIC_VERIFY_V2
{ 0xaac56b, 0xcd44, 0x11d0,{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } };
char *signature_name;
size_t i, len;
// Check the signature name. Make it specific enough (i.e. don't simply check for "Akeo")
// so that, besides hacking our server, it'll place an extra hurdle on any malicious entity
// into also fooling a C.A. to issue a certificate that passes our test.
signature_name = GetSignatureName(path);
if (signature_name == NULL) {
uprintf("PKI: Could not get signature name");
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
return TRUST_E_NOSIGNATURE;
}
for (i = 0; i < ARRAYSIZE(cert_name); i++) {
len = strlen(cert_name[i]);
if (strncmp(signature_name, cert_name[i], len) == 0) {
// Test for whitespace after the part we match, for added safety
if ((len >= strlen(signature_name)) || isspace(signature_name[len]))
break;
}
}
if (i >= ARRAYSIZE(cert_name)) {
uprintf("PKI: Signature '%s' is unexpected...", signature_name);
if (MessageBoxExU(hDlg, lmprintf(MSG_285, signature_name), lmprintf(MSG_283),
MB_YESNO | MB_ICONWARNING | MB_IS_RTL, selected_langid) != IDYES)
return TRUST_E_EXPLICIT_DISTRUST;
}
trust_file.cbStruct = sizeof(trust_file);
trust_file.pcwszFilePath = utf8_to_wchar(path);
if (trust_file.pcwszFilePath == NULL) {
uprintf("PKI: Unable to convert '%s' to UTF16", path);
return ERROR_SEVERITY_ERROR | FAC(FACILITY_CERT) | ERROR_NOT_ENOUGH_MEMORY;
}
trust_data.cbStruct = sizeof(trust_data);
// NB: WTD_UI_ALL can result in ERROR_SUCCESS even if the signature validation fails,
// because it still prompts the user to run untrusted software, even after explicitly
// notifying them that the signature invalid (and of course Microsoft had to make
// that UI prompt a bit too similar to the other benign prompt you get when running
// trusted software, which, as per cert.org's assessment, may confuse non-security
// conscious-users who decide to gloss over these kind of notifications).
trust_data.dwUIChoice = WTD_UI_NONE;
// We just downloaded from the Internet, so we should be able to check revocation
trust_data.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
// 0x400 = WTD_MOTW for Windows 8.1 or later
trust_data.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN | 0x400;
trust_data.dwUnionChoice = WTD_CHOICE_FILE;
trust_data.pFile = &trust_file;
r = WinVerifyTrust(NULL, &guid_generic_verify, &trust_data);
safe_free(trust_file.pcwszFilePath);
switch (r) {
case ERROR_SUCCESS:
break;
case TRUST_E_NOSIGNATURE:
// Should already have been reported, but since we have a custom message for it...
uprintf("PKI: File does not appear to be signed: %s", WinPKIErrorString());
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
break;
default:
uprintf("PKI: Failed to validate signature: %s", WinPKIErrorString());
MessageBoxExU(hDlg, lmprintf(MSG_240), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
break;
}
return r;
}
| ./CrossVul/dataset_final_sorted/CWE-494/c/good_2732_1 |
crossvul-cpp_data_bad_2732_1 | /*
* Rufus: The Reliable USB Formatting Utility
* PKI functions (code signing, etc.)
* Copyright © 2015-2016 Pete Batard <pete@akeo.ie>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <stdio.h>
#include <wincrypt.h>
#include <wintrust.h>
#include "rufus.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
// Signatures names we accept (may be suffixed, but the signature should start with one of those)
const char* cert_name[3] = { "Akeo Consulting", "Akeo Systems", "Pete Batard" };
typedef struct {
LPWSTR lpszProgramName;
LPWSTR lpszPublisherLink;
LPWSTR lpszMoreInfoLink;
} SPROG_PUBLISHERINFO, *PSPROG_PUBLISHERINFO;
/*
* FormatMessage does not handle PKI errors
*/
const char* WinPKIErrorString(void)
{
static char error_string[64];
DWORD error_code = GetLastError();
if ((error_code >> 16) != 0x8009)
return WindowsErrorString();
switch (error_code) {
case NTE_BAD_UID:
return "Bad UID.";
case CRYPT_E_MSG_ERROR:
return "An error occurred while performing an operation on a cryptographic message.";
case CRYPT_E_UNKNOWN_ALGO:
return "Unknown cryptographic algorithm.";
case CRYPT_E_INVALID_MSG_TYPE:
return "Invalid cryptographic message type.";
case CRYPT_E_HASH_VALUE:
return "The hash value is not correct";
case CRYPT_E_ISSUER_SERIALNUMBER:
return "Invalid issuer and/or serial number.";
case CRYPT_E_BAD_LEN:
return "The length specified for the output data was insufficient.";
case CRYPT_E_BAD_ENCODE:
return "An error occurred during encode or decode operation.";
case CRYPT_E_FILE_ERROR:
return "An error occurred while reading or writing to a file.";
case CRYPT_E_NOT_FOUND:
return "Cannot find object or property.";
case CRYPT_E_EXISTS:
return "The object or property already exists.";
case CRYPT_E_NO_PROVIDER:
return "No provider was specified for the store or object.";
case CRYPT_E_DELETED_PREV:
return "The previous certificate or CRL context was deleted.";
case CRYPT_E_NO_MATCH:
return "Cannot find the requested object.";
case CRYPT_E_UNEXPECTED_MSG_TYPE:
case CRYPT_E_NO_KEY_PROPERTY:
case CRYPT_E_NO_DECRYPT_CERT:
return "Private key or certificate issue";
case CRYPT_E_BAD_MSG:
return "Not a cryptographic message.";
case CRYPT_E_NO_SIGNER:
return "The signed cryptographic message does not have a signer for the specified signer index.";
case CRYPT_E_REVOKED:
return "The certificate is revoked.";
case CRYPT_E_NO_REVOCATION_DLL:
case CRYPT_E_NO_REVOCATION_CHECK:
case CRYPT_E_REVOCATION_OFFLINE:
case CRYPT_E_NOT_IN_REVOCATION_DATABASE:
return "Cannot check certificate revocation.";
case CRYPT_E_INVALID_NUMERIC_STRING:
case CRYPT_E_INVALID_PRINTABLE_STRING:
case CRYPT_E_INVALID_IA5_STRING:
case CRYPT_E_INVALID_X500_STRING:
case CRYPT_E_NOT_CHAR_STRING:
return "Invalid string.";
case CRYPT_E_SECURITY_SETTINGS:
return "The cryptographic operation failed due to a local security option setting.";
case CRYPT_E_NO_VERIFY_USAGE_CHECK:
case CRYPT_E_VERIFY_USAGE_OFFLINE:
return "Cannot complete usage check.";
case CRYPT_E_NO_TRUSTED_SIGNER:
return "None of the signers of the cryptographic message or certificate trust list is trusted.";
default:
static_sprintf(error_string, "Unknown PKI error 0x%08lX", error_code);
return error_string;
}
}
// Mostly from https://support.microsoft.com/en-us/kb/323809
char* GetSignatureName(const char* path)
{
static char szSubjectName[128];
char *p = NULL, *mpath = NULL;
BOOL r;
HMODULE hm;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
PCCERT_CONTEXT pCertContext = NULL;
DWORD dwSize, dwEncoding, dwContentType, dwFormatType, dwSubjectSize;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
PCMSG_SIGNER_INFO pCounterSignerInfo = NULL;
DWORD dwSignerInfo = 0;
CERT_INFO CertInfo = { 0 };
SPROG_PUBLISHERINFO ProgPubInfo = { 0 };
wchar_t *szFileName;
// If the path is NULL, get the signature of the current runtime
if (path == NULL) {
szFileName = calloc(MAX_PATH, sizeof(wchar_t));
if (szFileName == NULL)
return NULL;
hm = GetModuleHandle(NULL);
if (hm == NULL) {
uprintf("PKI: Could not get current executable handle: %s", WinPKIErrorString());
return NULL;
}
dwSize = GetModuleFileNameW(hm, szFileName, MAX_PATH);
if ((dwSize == 0) || ((dwSize == MAX_PATH) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))) {
uprintf("PKI: Could not get module filename: %s", WinPKIErrorString());
return NULL;
}
mpath = wchar_to_utf8(szFileName);
} else {
szFileName = utf8_to_wchar(path);
}
// Get message handle and store handle from the signed file.
r = CryptQueryObject(CERT_QUERY_OBJECT_FILE, szFileName,
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY,
0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, NULL);
if (!r) {
uprintf("PKI: Failed to get signature for '%s': %s", (path==NULL)?mpath:path, WinPKIErrorString());
goto out;
}
// Get signer information size.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
if (!r) {
uprintf("PKI: Failed to get signer size: %s", WinPKIErrorString());
goto out;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)calloc(dwSignerInfo, 1);
if (!pSignerInfo) {
uprintf("PKI: Could not allocate memory for signer information");
goto out;
}
// Get Signer Information.
r = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, (PVOID)pSignerInfo, &dwSignerInfo);
if (!r) {
uprintf("PKI: Failed to get signer information: %s", WinPKIErrorString());
goto out;
}
// Search for the signer certificate in the temporary certificate store.
CertInfo.Issuer = pSignerInfo->Issuer;
CertInfo.SerialNumber = pSignerInfo->SerialNumber;
pCertContext = CertFindCertificateInStore(hStore, ENCODING, 0, CERT_FIND_SUBJECT_CERT, (PVOID)&CertInfo, NULL);
if (!pCertContext) {
uprintf("PKI: Failed to locate signer certificate in temporary store: %s", WinPKIErrorString());
goto out;
}
// Isolate the signing certificate subject name
dwSubjectSize = CertGetNameStringA(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL,
szSubjectName, sizeof(szSubjectName));
if (dwSubjectSize <= 1) {
uprintf("PKI: Failed to get Subject Name");
goto out;
}
uprintf("Downloaded executable is signed by '%s'", szSubjectName);
p = szSubjectName;
out:
safe_free(mpath);
safe_free(szFileName);
safe_free(ProgPubInfo.lpszProgramName);
safe_free(ProgPubInfo.lpszPublisherLink);
safe_free(ProgPubInfo.lpszMoreInfoLink);
safe_free(pSignerInfo);
safe_free(pCounterSignerInfo);
if (pCertContext != NULL)
CertFreeCertificateContext(pCertContext);
if (hStore != NULL)
CertCloseStore(hStore, 0);
if (hMsg != NULL)
CryptMsgClose(hMsg);
return p;
}
// From https://msdn.microsoft.com/en-us/library/windows/desktop/aa382384.aspx
LONG ValidateSignature(HWND hDlg, const char* path)
{
LONG r;
WINTRUST_DATA trust_data = { 0 };
WINTRUST_FILE_INFO trust_file = { 0 };
GUID guid_generic_verify = // WINTRUST_ACTION_GENERIC_VERIFY_V2
{ 0xaac56b, 0xcd44, 0x11d0,{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } };
char *signature_name;
size_t i, len;
// Check the signature name. Make it specific enough (i.e. don't simply check for "Akeo")
// so that, besides hacking our server, it'll place an extra hurdle on any malicious entity
// into also fooling a C.A. to issue a certificate that passes our test.
signature_name = GetSignatureName(path);
if (signature_name == NULL) {
uprintf("PKI: Could not get signature name");
MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid);
return TRUST_E_NOSIGNATURE;
}
for (i = 0; i < ARRAYSIZE(cert_name); i++) {
len = strlen(cert_name[i]);
if (strncmp(signature_name, cert_name[i], len) == 0) {
// Test for whitespace after the part we match, for added safety
if ((len >= strlen(signature_name)) || isspace(signature_name[len]))
break;
}
}
if (i >= ARRAYSIZE(cert_name)) {
uprintf("PKI: Signature '%s' is unexpected...", signature_name);
if (MessageBoxExU(hDlg, lmprintf(MSG_285, signature_name), lmprintf(MSG_283),
MB_YESNO | MB_ICONWARNING | MB_IS_RTL, selected_langid) != IDYES)
return TRUST_E_EXPLICIT_DISTRUST;
}
trust_file.cbStruct = sizeof(trust_file);
trust_file.pcwszFilePath = utf8_to_wchar(path);
if (trust_file.pcwszFilePath == NULL) {
uprintf("PKI: Unable to convert '%s' to UTF16", path);
return ERROR_SEVERITY_ERROR | FAC(FACILITY_CERT) | ERROR_NOT_ENOUGH_MEMORY;
}
trust_data.cbStruct = sizeof(trust_data);
trust_data.dwUIChoice = WTD_UI_ALL;
// We just downloaded from the Internet, so we should be able to check revocation
trust_data.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN;
// 0x400 = WTD_MOTW for Windows 8.1 or later
trust_data.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN | 0x400;
trust_data.dwUnionChoice = WTD_CHOICE_FILE;
trust_data.pFile = &trust_file;
r = WinVerifyTrust(NULL, &guid_generic_verify, &trust_data);
safe_free(trust_file.pcwszFilePath);
return r;
}
| ./CrossVul/dataset_final_sorted/CWE-494/c/bad_2732_1 |
crossvul-cpp_data_good_2732_3 | /*
* Rufus: The Reliable USB Formatting Utility
* Standard Dialog Routines (Browse for folder, About, etc)
* Copyright © 2011-2017 Pete Batard <pete@akeo.ie>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Memory leaks detection - define _CRTDBG_MAP_ALLOC as preprocessor macro */
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <shlobj.h>
#include <commdlg.h>
#include <richedit.h>
#include "rufus.h"
#include "missing.h"
#include "resource.h"
#include "msapi_utf8.h"
#include "localization.h"
#include "registry.h"
#include "settings.h"
#include "license.h"
PF_TYPE_DECL(WINAPI, HRESULT, SHCreateItemFromParsingName, (PCWSTR, IBindCtx*, REFIID, void **));
PF_TYPE_DECL(WINAPI, LPITEMIDLIST, SHSimpleIDListFromPath, (PCWSTR pszPath));
#define INIT_VISTA_SHELL32 PF_INIT(SHCreateItemFromParsingName, Shell32)
#define INIT_XP_SHELL32 PF_INIT(SHSimpleIDListFromPath, Shell32)
#define IS_VISTA_SHELL32_AVAILABLE (pfSHCreateItemFromParsingName != NULL)
/* Globals */
static HICON hMessageIcon = (HICON)INVALID_HANDLE_VALUE;
static char* szMessageText = NULL;
static char* szMessageTitle = NULL;
static char **szDialogItem;
static int nDialogItems;
static HWND hBrowseEdit;
extern HWND hUpdatesDlg;
static WNDPROC pOrgBrowseWndproc;
static const SETTEXTEX friggin_microsoft_unicode_amateurs = {ST_DEFAULT, CP_UTF8};
static BOOL notification_is_question;
static const notification_info* notification_more_info;
static BOOL settings_commcheck = FALSE;
static WNDPROC update_original_proc = NULL;
static HWINEVENTHOOK fp_weh = NULL;
static char *fp_title_str = "Microsoft Windows", *fp_button_str = "Format disk";
extern loc_cmd* selected_locale;
/*
* https://blogs.msdn.microsoft.com/oldnewthing/20040802-00/?p=38283/
*/
void SetDialogFocus(HWND hDlg, HWND hCtrl)
{
SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)hCtrl, TRUE);
}
/*
* We need a sub-callback to read the content of the edit box on exit and update
* our path, else if what the user typed does match the selection, it is discarded.
* Talk about a convoluted way of producing an intuitive folder selection dialog
*/
INT CALLBACK BrowseDlgCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message) {
case WM_DESTROY:
GetWindowTextU(hBrowseEdit, szFolderPath, sizeof(szFolderPath));
break;
}
return (INT)CallWindowProc(pOrgBrowseWndproc, hDlg, message, wParam, lParam);
}
/*
* Main BrowseInfo callback to set the initial directory and populate the edit control
*/
INT CALLBACK BrowseInfoCallback(HWND hDlg, UINT message, LPARAM lParam, LPARAM pData)
{
char dir[MAX_PATH];
wchar_t* wpath;
LPITEMIDLIST pidl;
switch(message) {
case BFFM_INITIALIZED:
pOrgBrowseWndproc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)BrowseDlgCallback);
// Windows hides the full path in the edit box by default, which is bull.
// Get a handle to the edit control to fix that
hBrowseEdit = FindWindowExA(hDlg, NULL, "Edit", NULL);
SetWindowTextU(hBrowseEdit, szFolderPath);
SetDialogFocus(hDlg, hBrowseEdit);
// On XP, BFFM_SETSELECTION can't be used with a Unicode Path in SendMessageW
// or a pidl (at least with MinGW) => must use SendMessageA
if (nWindowsVersion <= WINDOWS_XP) {
SendMessageLU(hDlg, BFFM_SETSELECTION, (WPARAM)TRUE, szFolderPath);
} else {
// On Windows 7, MinGW only properly selects the specified folder when using a pidl
wpath = utf8_to_wchar(szFolderPath);
pidl = (*pfSHSimpleIDListFromPath)(wpath);
safe_free(wpath);
// NB: see http://connect.microsoft.com/VisualStudio/feedback/details/518103/bffm-setselection-does-not-work-with-shbrowseforfolder-on-windows-7
// for details as to why we send BFFM_SETSELECTION twice.
SendMessageW(hDlg, BFFM_SETSELECTION, (WPARAM)FALSE, (LPARAM)pidl);
Sleep(100);
PostMessageW(hDlg, BFFM_SETSELECTION, (WPARAM)FALSE, (LPARAM)pidl);
}
break;
case BFFM_SELCHANGED:
// Update the status
if (SHGetPathFromIDListU((LPITEMIDLIST)lParam, dir)) {
SendMessageLU(hDlg, BFFM_SETSTATUSTEXT, 0, dir);
SetWindowTextU(hBrowseEdit, dir);
}
break;
}
return 0;
}
/*
* Browse for a folder and update the folder edit box
* Will use the newer IFileOpenDialog if *compiled* for Vista or later
*/
void BrowseForFolder(void) {
BROWSEINFOW bi;
LPITEMIDLIST pidl;
WCHAR *wpath;
size_t i;
HRESULT hr;
IShellItem *psi = NULL;
IShellItem *si_path = NULL; // Automatically freed
IFileOpenDialog *pfod = NULL;
WCHAR *fname;
char* tmp_path = NULL;
dialog_showing++;
if (nWindowsVersion >= WINDOWS_VISTA) {
INIT_VISTA_SHELL32;
if (IS_VISTA_SHELL32_AVAILABLE) {
hr = CoCreateInstance(&CLSID_FileOpenDialog, NULL, CLSCTX_INPROC,
&IID_IFileOpenDialog, (LPVOID)&pfod);
if (FAILED(hr)) {
uprintf("CoCreateInstance for FileOpenDialog failed: error %X\n", hr);
pfod = NULL; // Just in case
goto fallback;
}
hr = pfod->lpVtbl->SetOptions(pfod, FOS_PICKFOLDERS);
if (FAILED(hr)) {
uprintf("Failed to set folder option for FileOpenDialog: error %X\n", hr);
goto fallback;
}
// Set the initial folder (if the path is invalid, will simply use last)
wpath = utf8_to_wchar(szFolderPath);
// The new IFileOpenDialog makes us split the path
fname = NULL;
if ((wpath != NULL) && (wcslen(wpath) >= 1)) {
for (i = wcslen(wpath) - 1; i != 0; i--) {
if (wpath[i] == L'\\') {
wpath[i] = 0;
fname = &wpath[i + 1];
break;
}
}
}
hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path);
if (SUCCEEDED(hr)) {
if (wpath != NULL) {
pfod->lpVtbl->SetFolder(pfod, si_path);
}
if (fname != NULL) {
pfod->lpVtbl->SetFileName(pfod, fname);
}
}
safe_free(wpath);
hr = pfod->lpVtbl->Show(pfod, hMainDialog);
if (SUCCEEDED(hr)) {
hr = pfod->lpVtbl->GetResult(pfod, &psi);
if (SUCCEEDED(hr)) {
psi->lpVtbl->GetDisplayName(psi, SIGDN_FILESYSPATH, &wpath);
tmp_path = wchar_to_utf8(wpath);
CoTaskMemFree(wpath);
if (tmp_path == NULL) {
uprintf("Could not convert path\n");
} else {
static_strcpy(szFolderPath, tmp_path);
safe_free(tmp_path);
}
} else {
uprintf("Failed to set folder option for FileOpenDialog: error %X\n", hr);
}
} else if ((hr & 0xFFFF) != ERROR_CANCELLED) {
// If it's not a user cancel, assume the dialog didn't show and fallback
uprintf("Could not show FileOpenDialog: error %X\n", hr);
goto fallback;
}
pfod->lpVtbl->Release(pfod);
dialog_showing--;
return;
}
fallback:
if (pfod != NULL) {
pfod->lpVtbl->Release(pfod);
}
}
INIT_XP_SHELL32;
memset(&bi, 0, sizeof(BROWSEINFOW));
bi.hwndOwner = hMainDialog;
bi.lpszTitle = utf8_to_wchar(lmprintf(MSG_106));
bi.lpfn = BrowseInfoCallback;
// BIF_NONEWFOLDERBUTTON = 0x00000200 is unknown on MinGW
bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS |
BIF_DONTGOBELOWDOMAIN | BIF_EDITBOX | 0x00000200;
pidl = SHBrowseForFolderW(&bi);
if (pidl != NULL) {
CoTaskMemFree(pidl);
}
safe_free(bi.lpszTitle);
dialog_showing--;
}
/*
* Return the UTF8 path of a file selected through a load or save dialog
* Will use the newer IFileOpenDialog if *compiled* for Vista or later
* All string parameters are UTF-8
* IMPORTANT NOTE: On Vista and later, remember that you need to call
* CoInitializeEx() for *EACH* thread you invoke FileDialog from, as
* GetDisplayName() will return error 0x8001010E otherwise.
*/
char* FileDialog(BOOL save, char* path, const ext_t* ext, DWORD options)
{
DWORD tmp;
OPENFILENAMEA ofn;
char selected_name[MAX_PATH];
char *ext_string = NULL, *all_files = NULL;
size_t i, j, ext_strlen;
BOOL r;
char* filepath = NULL;
HRESULT hr = FALSE;
IFileDialog *pfd = NULL;
IShellItem *psiResult;
COMDLG_FILTERSPEC* filter_spec = NULL;
wchar_t *wpath = NULL, *wfilename = NULL;
IShellItem *si_path = NULL; // Automatically freed
if ((ext == NULL) || (ext->count == 0) || (ext->extension == NULL) || (ext->description == NULL))
return NULL;
dialog_showing++;
if (nWindowsVersion >= WINDOWS_VISTA) {
INIT_VISTA_SHELL32;
filter_spec = (COMDLG_FILTERSPEC*)calloc(ext->count + 1, sizeof(COMDLG_FILTERSPEC));
if ((IS_VISTA_SHELL32_AVAILABLE) && (filter_spec != NULL)) {
// Setup the file extension filter table
for (i = 0; i < ext->count; i++) {
filter_spec[i].pszSpec = utf8_to_wchar(ext->extension[i]);
filter_spec[i].pszName = utf8_to_wchar(ext->description[i]);
}
filter_spec[i].pszSpec = L"*.*";
filter_spec[i].pszName = utf8_to_wchar(lmprintf(MSG_107));
hr = CoCreateInstance(save ? &CLSID_FileSaveDialog : &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC,
&IID_IFileDialog, (LPVOID)&pfd);
if (FAILED(hr)) {
SetLastError(hr);
uprintf("CoCreateInstance for FileOpenDialog failed: %s\n", WindowsErrorString());
pfd = NULL; // Just in case
goto fallback;
}
// Set the file extension filters
pfd->lpVtbl->SetFileTypes(pfd, (UINT)ext->count + 1, filter_spec);
// Set the default directory
wpath = utf8_to_wchar(path);
hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path);
if (SUCCEEDED(hr)) {
pfd->lpVtbl->SetFolder(pfd, si_path);
}
safe_free(wpath);
// Set the default filename
wfilename = utf8_to_wchar((ext->filename == NULL) ? "" : ext->filename);
if (wfilename != NULL) {
pfd->lpVtbl->SetFileName(pfd, wfilename);
}
// Display the dialog
hr = pfd->lpVtbl->Show(pfd, hMainDialog);
// Cleanup
safe_free(wfilename);
for (i = 0; i < ext->count; i++) {
safe_free(filter_spec[i].pszSpec);
safe_free(filter_spec[i].pszName);
}
safe_free(filter_spec[i].pszName);
safe_free(filter_spec);
if (SUCCEEDED(hr)) {
// Obtain the result of the user's interaction with the dialog.
hr = pfd->lpVtbl->GetResult(pfd, &psiResult);
if (SUCCEEDED(hr)) {
hr = psiResult->lpVtbl->GetDisplayName(psiResult, SIGDN_FILESYSPATH, &wpath);
if (SUCCEEDED(hr)) {
filepath = wchar_to_utf8(wpath);
CoTaskMemFree(wpath);
} else {
SetLastError(hr);
uprintf("Unable to access file path: %s\n", WindowsErrorString());
}
psiResult->lpVtbl->Release(psiResult);
}
} else if ((hr & 0xFFFF) != ERROR_CANCELLED) {
// If it's not a user cancel, assume the dialog didn't show and fallback
SetLastError(hr);
uprintf("Could not show FileOpenDialog: %s\n", WindowsErrorString());
goto fallback;
}
pfd->lpVtbl->Release(pfd);
dialog_showing--;
return filepath;
}
fallback:
safe_free(filter_spec);
if (pfd != NULL) {
pfd->lpVtbl->Release(pfd);
}
}
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hMainDialog;
// Selected File name
static_sprintf(selected_name, "%s", (ext->filename == NULL)?"":ext->filename);
ofn.lpstrFile = selected_name;
ofn.nMaxFile = MAX_PATH;
// Set the file extension filters
all_files = lmprintf(MSG_107);
ext_strlen = 0;
for (i=0; i<ext->count; i++) {
ext_strlen += safe_strlen(ext->description[i]) + 2*safe_strlen(ext->extension[i]) + sizeof(" ()\r\r");
}
ext_strlen += safe_strlen(all_files) + sizeof(" (*.*)\r*.*\r");
ext_string = (char*)malloc(ext_strlen+1);
if (ext_string == NULL)
return NULL;
ext_string[0] = 0;
for (i=0, j=0; i<ext->count; i++) {
j += _snprintf(&ext_string[j], ext_strlen-j, "%s (%s)\r%s\r", ext->description[i], ext->extension[i], ext->extension[i]);
}
j = _snprintf(&ext_string[j], ext_strlen-j, "%s (*.*)\r*.*\r", all_files);
// Microsoft could really have picked a better delimiter!
for (i=0; i<ext_strlen; i++) {
// Since the VS Code Analysis tool is dumb...
#if defined(_MSC_VER)
#pragma warning(suppress: 6385)
#endif
if (ext_string[i] == '\r') {
#if defined(_MSC_VER)
#pragma warning(suppress: 6386)
#endif
ext_string[i] = 0;
}
}
ofn.lpstrFilter = ext_string;
ofn.nFilterIndex = 1;
ofn.lpstrInitialDir = path;
ofn.Flags = OFN_OVERWRITEPROMPT | options;
// Show Dialog
if (save) {
r = GetSaveFileNameU(&ofn);
} else {
r = GetOpenFileNameU(&ofn);
}
if (r) {
filepath = safe_strdup(selected_name);
} else {
tmp = CommDlgExtendedError();
if (tmp != 0) {
uprintf("Could not select file for %s. Error %X\n", save?"save":"open", tmp);
}
}
safe_free(ext_string);
dialog_showing--;
return filepath;
}
/*
* Create the application status bar
*/
void CreateStatusBar(void)
{
SIZE sz = {0, 0};
RECT rect;
LONG x, y, width, height;
int edge[3];
TBBUTTON tbbStatusToolbarButtons[1];
TBBUTTONINFO tbi;
HFONT hFont;
HDC hDC;
// Create the status bar (WS_CLIPSIBLINGS since we have an overlapping button)
hStatus = CreateWindowExW(0, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | SBARS_TOOLTIPS | WS_CLIPSIBLINGS,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hMainDialog,
(HMENU)IDC_STATUS, hMainInstance, NULL);
// Keep track of the status bar height
GetClientRect(hStatus, &rect);
height = rect.bottom;
// Set the font we'll use to display the '#' sign in the toolbar button
hFont = CreateFontA(-MulDiv(10, GetDeviceCaps(GetDC(hMainDialog), LOGPIXELSY), 72),
0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
0, 0, PROOF_QUALITY, 0, (nWindowsVersion >= WINDOWS_VISTA)?"Segoe UI":"Arial Unicode MS");
// Find the width of our hash sign
hDC = GetDC(hMainDialog);
SelectObject(hDC, hFont);
GetTextExtentPoint32W(hDC, L"#", 1, &sz);
if (hDC != NULL)
ReleaseDC(hMainDialog, hDC);
// Create 3 status areas
GetClientRect(hMainDialog, &rect);
edge[1] = rect.right - (int)(SB_TIMER_SECTION_SIZE * fScale);
edge[0] = edge[1] - (8 + sz.cx + 8 + 1); // There's 8 absolute pixels on right and left of the text
edge[2] = rect.right;
SendMessage(hStatus, SB_SETPARTS, (WPARAM)ARRAYSIZE(edge), (LPARAM)&edge);
// NB: To add an icon on the status bar, you can use something like this:
// SendMessage(hStatus, SB_SETICON, (WPARAM) 1, (LPARAM)LoadImage(GetLibraryHandle("rasdlg"),
// MAKEINTRESOURCE(50), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR | LR_SHARED));
// This is supposed to create a toolips for a statusbar section (when SBARS_TOOLTIPS is in use)... but doesn't :(
// SendMessageLU(hStatus, SB_SETTIPTEXT, (WPARAM)2, (LPARAM)"HELLO");
// Compute the dimensions for the hash button
x = edge[0];
if (nWindowsVersion <= WINDOWS_XP) {
x -= 1;
height -= 2;
}
y = rect.bottom - height + 1;
width = edge[1] - edge[0] - 1;
// How I wish there was a way to figure out how to make Windows controls look good
// at all scales, without adding all these crappy empirical adjustments...
if ((fScale > 1.20f) && (fScale <2.40f))
height -= 1;
if (nWindowsVersion <= WINDOWS_7)
height += 1;
// Create the status toolbar
hStatusToolbar = CreateWindowExW(WS_EX_TRANSPARENT, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_TABSTOP | WS_DISABLED |
TBSTYLE_LIST | CCS_NOPARENTALIGN | CCS_NODIVIDER | CCS_NORESIZE,
x, y, width, height, hMainDialog, (HMENU)IDC_STATUS_TOOLBAR, hMainInstance, NULL);
// Set the button properties
SendMessage(hStatusToolbar, WM_SETFONT, (WPARAM)hFont, TRUE);
SendMessage(hStatusToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);
SendMessage(hStatusToolbar, TB_SETIMAGELIST, 0, (LPARAM)NULL);
SendMessage(hStatusToolbar, TB_SETDISABLEDIMAGELIST, 0, (LPARAM)NULL);
SendMessage(hStatusToolbar, TB_SETBITMAPSIZE, 0, MAKELONG(0,0));
// Set our text
memset(tbbStatusToolbarButtons, 0, sizeof(TBBUTTON));
tbbStatusToolbarButtons[0].idCommand = IDC_HASH;
tbbStatusToolbarButtons[0].fsStyle = BTNS_SHOWTEXT;
tbbStatusToolbarButtons[0].fsState = TBSTATE_ENABLED;
tbbStatusToolbarButtons[0].iString = (INT_PTR)L"#";
SendMessage(hStatusToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(hStatusToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM)&tbbStatusToolbarButtons);
SendMessage(hStatusToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(width, height - 1));
// Yeah, you'd think that TB_SETBUTTONSIZE would work for the width... but you'd be wrong.
// The only working method that actually enforces the requested width is TB_SETBUTTONINFO
tbi.cbSize = sizeof(tbi);
tbi.dwMask = TBIF_SIZE | TBIF_COMMAND;
tbi.cx = (WORD)width;
tbi.idCommand = IDC_HASH;
SendMessage(hStatusToolbar, TB_SETBUTTONINFO, (WPARAM)IDC_HASH, (LPARAM)&tbi);
// Need to resend the positioning for the toolbar to become active... One of Windows' mysteries
// Also use this opportunity to set our Z-order for tab stop
SetWindowPos(hStatusToolbar, GetDlgItem(hMainDialog, IDCANCEL), x, y, width, height, 0);
ShowWindow(hStatusToolbar, SW_SHOWNORMAL);
}
/*
* Center a dialog with regards to the main application Window or the desktop
* See http://msdn.microsoft.com/en-us/library/windows/desktop/ms644996.aspx#init_box
*/
void CenterDialog(HWND hDlg)
{
HWND hParent;
RECT rc, rcDlg, rcParent;
if ((hParent = GetParent(hDlg)) == NULL) {
hParent = GetDesktopWindow();
}
GetWindowRect(hParent, &rcParent);
GetWindowRect(hDlg, &rcDlg);
CopyRect(&rc, &rcParent);
// Offset the parent and dialog box rectangles so that right and bottom
// values represent the width and height, and then offset the parent again
// to discard space taken up by the dialog box.
OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
OffsetRect(&rc, -rc.left, -rc.top);
OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
SetWindowPos(hDlg, HWND_TOP, rcParent.left + (rc.right / 2), rcParent.top + (rc.bottom / 2) - 25, 0, 0, SWP_NOSIZE);
}
// http://stackoverflow.com/questions/431470/window-border-width-and-height-in-win32-how-do-i-get-it
SIZE GetBorderSize(HWND hDlg)
{
RECT rect = {0, 0, 0, 0};
SIZE size = {0, 0};
WINDOWINFO wi;
wi.cbSize = sizeof(WINDOWINFO);
GetWindowInfo(hDlg, &wi);
AdjustWindowRectEx(&rect, wi.dwStyle, FALSE, wi.dwExStyle);
size.cx = rect.right - rect.left;
size.cy = rect.bottom - rect.top;
return size;
}
void ResizeMoveCtrl(HWND hDlg, HWND hCtrl, int dx, int dy, int dw, int dh, float scale)
{
RECT rect;
POINT point;
SIZE border;
GetWindowRect(hCtrl, &rect);
point.x = (right_to_left_mode && (hDlg != hCtrl))?rect.right:rect.left;
point.y = rect.top;
if (hDlg != hCtrl)
ScreenToClient(hDlg, &point);
GetClientRect(hCtrl, &rect);
// If the control has any borders (dialog, edit box), take them into account
border = GetBorderSize(hCtrl);
MoveWindow(hCtrl, point.x + (int)(scale*(float)dx), point.y + (int)(scale*(float)dy),
(rect.right - rect.left) + (int)(scale*(float)dw + border.cx),
(rect.bottom - rect.top) + (int)(scale*(float)dh + border.cy), TRUE);
InvalidateRect(hCtrl, NULL, TRUE);
}
/*
* License callback
*/
INT_PTR CALLBACK LicenseCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
long style;
HWND hLicense;
switch (message) {
case WM_INITDIALOG:
hLicense = GetDlgItem(hDlg, IDC_LICENSE_TEXT);
apply_localization(IDD_LICENSE, hDlg);
CenterDialog(hDlg);
// Suppress any inherited RTL flags
style = GetWindowLong(hLicense, GWL_EXSTYLE);
style &= ~(WS_EX_RTLREADING | WS_EX_RIGHT | WS_EX_LEFTSCROLLBAR);
SetWindowLong(hLicense, GWL_EXSTYLE, style);
style = GetWindowLong(hLicense, GWL_STYLE);
style &= ~(ES_RIGHT);
SetWindowLong(hLicense, GWL_STYLE, style);
SetDlgItemTextA(hDlg, IDC_LICENSE_TEXT, gplv3);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
reset_localization(IDD_LICENSE);
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
}
/*
* About dialog callback
*/
INT_PTR CALLBACK AboutCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int i, dy;
const int edit_id[2] = {IDC_ABOUT_BLURB, IDC_ABOUT_COPYRIGHTS};
char about_blurb[2048];
const char* edit_text[2] = {about_blurb, additional_copyrights};
HWND hEdit[2];
TEXTRANGEW tr;
ENLINK* enl;
RECT rect;
REQRESIZE* rsz;
wchar_t wUrl[256];
static BOOL resized_already = TRUE;
switch (message) {
case WM_INITDIALOG:
resized_already = FALSE;
// Execute dialog localization
apply_localization(IDD_ABOUTBOX, hDlg);
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
if (settings_commcheck)
ShowWindow(GetDlgItem(hDlg, IDC_ABOUT_UPDATES), SW_SHOW);
static_sprintf(about_blurb, about_blurb_format, lmprintf(MSG_174|MSG_RTF),
lmprintf(MSG_175|MSG_RTF, rufus_version[0], rufus_version[1], rufus_version[2]),
right_to_left_mode?"Akeo \\\\ Pete Batard 2011-2017 © Copyright":"Copyright © 2011-2017 Pete Batard / Akeo",
lmprintf(MSG_176|MSG_RTF), lmprintf(MSG_177|MSG_RTF), lmprintf(MSG_178|MSG_RTF));
for (i=0; i<ARRAYSIZE(hEdit); i++) {
hEdit[i] = GetDlgItem(hDlg, edit_id[i]);
SendMessage(hEdit[i], EM_AUTOURLDETECT, 1, 0);
/* Can't use SetDlgItemText, because it only works with RichEdit20A... and VS insists
* on reverting to RichEdit20W as soon as you edit the dialog. You can try all the W
* methods you want, it JUST WON'T WORK unless you use EM_SETTEXTEX. Also see:
* http://blog.kowalczyk.info/article/eny/Setting-unicode-rtf-text-in-rich-edit-control.html */
SendMessageA(hEdit[i], EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)edit_text[i]);
SendMessage(hEdit[i], EM_SETSEL, -1, -1);
SendMessage(hEdit[i], EM_SETEVENTMASK, 0, ENM_LINK|((i==0)?ENM_REQUESTRESIZE:0));
SendMessage(hEdit[i], EM_SETBKGNDCOLOR, 0, (LPARAM)GetSysColor(COLOR_BTNFACE));
}
// Need to send an explicit SetSel to avoid being positioned at the end of richedit control when tabstop is used
SendMessage(hEdit[1], EM_SETSEL, 0, 0);
SendMessage(hEdit[0], EM_REQUESTRESIZE, 0, 0);
break;
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code) {
case EN_REQUESTRESIZE:
if (!resized_already) {
resized_already = TRUE;
GetWindowRect(GetDlgItem(hDlg, edit_id[0]), &rect);
dy = rect.bottom - rect.top;
rsz = (REQRESIZE *)lParam;
dy -= rsz->rc.bottom - rsz->rc.top;
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, edit_id[0]), 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, edit_id[1]), 0, -dy, 0, dy, 1.0f);
}
break;
case EN_LINK:
enl = (ENLINK*) lParam;
if (enl->msg == WM_LBUTTONUP) {
tr.lpstrText = wUrl;
tr.chrg.cpMin = enl->chrg.cpMin;
tr.chrg.cpMax = enl->chrg.cpMax;
SendMessageW(enl->nmhdr.hwndFrom, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
wUrl[ARRAYSIZE(wUrl)-1] = 0;
ShellExecuteW(hDlg, L"open", wUrl, NULL, NULL, SW_SHOWNORMAL);
}
break;
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
reset_localization(IDD_ABOUTBOX);
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
case IDC_ABOUT_LICENSE:
MyDialogBox(hMainInstance, IDD_LICENSE, hDlg, LicenseCallback);
break;
case IDC_ABOUT_UPDATES:
MyDialogBox(hMainInstance, IDD_UPDATE_POLICY, hDlg, UpdateCallback);
break;
}
break;
}
return (INT_PTR)FALSE;
}
INT_PTR CreateAboutBox(void)
{
INT_PTR r;
dialog_showing++;
r = MyDialogBox(hMainInstance, IDD_ABOUTBOX, hMainDialog, AboutCallback);
dialog_showing--;
return r;
}
/*
* We use our own MessageBox for notifications to have greater control (center, no close button, etc)
*/
INT_PTR CALLBACK NotificationCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
HFONT hDlgFont;
switch (message) {
case WM_INITDIALOG:
if (nWindowsVersion >= WINDOWS_VISTA) { // of course, this stuff doesn't work on XP!
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_NOTIFICATION_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_MORE_INFO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
}
apply_localization(IDD_NOTIFICATION, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon
if (Static_SetIcon(GetDlgItem(hDlg, IDC_NOTIFICATION_ICON), hMessageIcon) == 0) {
uprintf("Could not set dialog icon\n");
}
// Set the dialog title
if (szMessageTitle != NULL) {
SetWindowTextU(hDlg, szMessageTitle);
}
// Enable/disable the buttons and set text
if (!notification_is_question) {
SetWindowTextU(GetDlgItem(hDlg, IDNO), lmprintf(MSG_006));
} else {
ShowWindow(GetDlgItem(hDlg, IDYES), SW_SHOW);
}
if ((notification_more_info != NULL) && (notification_more_info->callback != NULL)) {
ShowWindow(GetDlgItem(hDlg, IDC_MORE_INFO), SW_SHOW);
}
// Set the control text
if (szMessageText != NULL) {
SetWindowTextU(GetDlgItem(hDlg, IDC_NOTIFICATION_TEXT), szMessageText);
}
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for(i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDCANCEL:
case IDYES:
case IDNO:
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
case IDC_MORE_INFO:
if (notification_more_info != NULL)
MyDialogBox(hMainInstance, notification_more_info->id, hDlg, notification_more_info->callback);
break;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display a custom notification
*/
BOOL Notification(int type, const notification_info* more_info, char* title, char* format, ...)
{
BOOL ret;
va_list args;
dialog_showing++;
szMessageText = (char*)malloc(MAX_PATH);
if (szMessageText == NULL) return FALSE;
szMessageTitle = safe_strdup(title);
if (szMessageTitle == NULL) return FALSE;
va_start(args, format);
safe_vsnprintf(szMessageText, MAX_PATH-1, format, args);
va_end(args);
szMessageText[MAX_PATH-1] = 0;
notification_more_info = more_info;
notification_is_question = FALSE;
switch(type) {
case MSG_WARNING_QUESTION:
notification_is_question = TRUE;
// Fall through
case MSG_WARNING:
hMessageIcon = LoadIcon(NULL, IDI_WARNING);
break;
case MSG_ERROR:
hMessageIcon = LoadIcon(NULL, IDI_ERROR);
break;
case MSG_QUESTION:
hMessageIcon = LoadIcon(NULL, IDI_QUESTION);
notification_is_question = TRUE;
break;
case MSG_INFO:
default:
hMessageIcon = LoadIcon(NULL, IDI_INFORMATION);
break;
}
ret = (MyDialogBox(hMainInstance, IDD_NOTIFICATION, hMainDialog, NotificationCallback) == IDYES);
safe_free(szMessageText);
safe_free(szMessageTitle);
dialog_showing--;
return ret;
}
/*
* Custom dialog for radio button selection dialog
*/
INT_PTR CALLBACK SelectionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i, dh, r = -1;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
RECT rect, rect2;
HFONT hDlgFont;
HWND hCtrl;
HDC hDC;
switch (message) {
case WM_INITDIALOG:
// Don't overflow our max radio button
if (nDialogItems > (IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1 + 1)) {
uprintf("Warning: Too many options requested for Selection (%d vs %d)",
nDialogItems, IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1);
nDialogItems = IDC_SELECTION_CHOICEMAX - IDC_SELECTION_CHOICE1;
}
// TODO: This shouldn't be needed when using DS_SHELLFONT
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if (nWindowsVersion >= WINDOWS_VISTA) {
// In versions of Windows prior to Vista, the iPaddedBorderWidth member
// is not present, so we need to subtract its size from cbSize.
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
}
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_SELECTION_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
for (i = 0; i < nDialogItems; i++)
SendMessage(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
apply_localization(IDD_SELECTION, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon and set the text
Static_SetIcon(GetDlgItem(hDlg, IDC_SELECTION_ICON), LoadIcon(NULL, IDI_QUESTION));
SetWindowTextU(hDlg, szMessageTitle);
SetWindowTextU(GetDlgItem(hDlg, IDCANCEL), lmprintf(MSG_007));
SetWindowTextU(GetDlgItem(hDlg, IDC_SELECTION_TEXT), szMessageText);
for (i = 0; i < nDialogItems; i++) {
SetWindowTextU(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), szDialogItem[i]);
ShowWindow(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), SW_SHOW);
}
// Move/Resize the controls as needed to fit our text
hCtrl = GetDlgItem(hDlg, IDC_SELECTION_TEXT);
hDC = GetDC(hCtrl);
SelectFont(hDC, hDlgFont); // Yes, you *MUST* reapply the font to the DC, even after SetWindowText!
GetWindowRect(hCtrl, &rect);
dh = rect.bottom - rect.top;
DrawTextU(hDC, szMessageText, -1, &rect, DT_CALCRECT | DT_WORDBREAK);
dh = rect.bottom - rect.top - dh;
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
ResizeMoveCtrl(hDlg, hCtrl, 0, 0, 0, dh, 1.0f);
for (i = 0; i < nDialogItems; i++)
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i), 0, dh, 0, 0, 1.0f);
if (nDialogItems > 2) {
GetWindowRect(GetDlgItem(hDlg, IDC_SELECTION_CHOICE2), &rect);
GetWindowRect(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + nDialogItems - 1), &rect2);
dh += rect2.top - rect.top;
}
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, dh, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, -1), 0, 0, 0, dh, 1.0f); // IDC_STATIC = -1
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_SELECTION_LINE), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDOK), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, dh, 0, 0, 1.0f);
// Set the radio selection
Button_SetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1), BST_CHECKED);
Button_SetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE2), BST_UNCHECKED);
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for (i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
for (i = 0; (i < nDialogItems) &&
(Button_GetCheck(GetDlgItem(hDlg, IDC_SELECTION_CHOICE1 + i)) != BST_CHECKED); i++);
if (i < nDialogItems)
r = i + 1;
// Fall through
case IDNO:
case IDCANCEL:
EndDialog(hDlg, r);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display an item selection dialog
*/
int SelectionDialog(char* title, char* message, char** choices, int size)
{
int ret;
dialog_showing++;
szMessageTitle = title;
szMessageText = message;
szDialogItem = choices;
nDialogItems = size;
ret = (int)MyDialogBox(hMainInstance, IDD_SELECTION, hMainDialog, SelectionCallback);
dialog_showing--;
return ret;
}
/*
* Custom dialog for list dialog
*/
INT_PTR CALLBACK ListCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT loc;
int i, dh, r = -1;
// Prevent resizing
static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };
static HBRUSH background_brush, separator_brush;
// To use the system message font
NONCLIENTMETRICS ncm;
RECT rect, rect2;
HFONT hDlgFont;
HWND hCtrl;
HDC hDC;
switch (message) {
case WM_INITDIALOG:
// Don't overflow our max radio button
if (nDialogItems > (IDC_LIST_ITEMMAX - IDC_LIST_ITEM1 + 1)) {
uprintf("Warning: Too many items requested for List (%d vs %d)",
nDialogItems, IDC_LIST_ITEMMAX - IDC_LIST_ITEM1);
nDialogItems = IDC_LIST_ITEMMAX - IDC_LIST_ITEM1;
}
// TODO: This shouldn't be needed when using DS_SHELLFONT
// Get the system message box font. See http://stackoverflow.com/a/6057761
ncm.cbSize = sizeof(ncm);
// If we're compiling with the Vista SDK or later, the NONCLIENTMETRICS struct
// will be the wrong size for previous versions, so we need to adjust it.
#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (_WIN32_WINNT >= _WIN32_WINNT_VISTA)
if (nWindowsVersion >= WINDOWS_VISTA) {
// In versions of Windows prior to Vista, the iPaddedBorderWidth member
// is not present, so we need to subtract its size from cbSize.
ncm.cbSize -= sizeof(ncm.iPaddedBorderWidth);
}
#endif
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
hDlgFont = CreateFontIndirect(&(ncm.lfMessageFont));
// Set the dialog to use the system message box font
SendMessage(hDlg, WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDC_LIST_TEXT), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
for (i = 0; i < nDialogItems; i++)
SendMessage(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDYES), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
SendMessage(GetDlgItem(hDlg, IDNO), WM_SETFONT, (WPARAM)hDlgFont, MAKELPARAM(TRUE, 0));
apply_localization(IDD_LIST, hDlg);
background_brush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
separator_brush = CreateSolidBrush(GetSysColor(COLOR_3DLIGHT));
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Change the default icon and set the text
Static_SetIcon(GetDlgItem(hDlg, IDC_LIST_ICON), LoadIcon(NULL, IDI_EXCLAMATION));
SetWindowTextU(hDlg, szMessageTitle);
SetWindowTextU(GetDlgItem(hDlg, IDCANCEL), lmprintf(MSG_007));
SetWindowTextU(GetDlgItem(hDlg, IDC_LIST_TEXT), szMessageText);
for (i = 0; i < nDialogItems; i++) {
SetWindowTextU(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), szDialogItem[i]);
ShowWindow(GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), SW_SHOW);
}
// Move/Resize the controls as needed to fit our text
hCtrl = GetDlgItem(hDlg, IDC_LIST_TEXT);
hDC = GetDC(hCtrl);
SelectFont(hDC, hDlgFont); // Yes, you *MUST* reapply the font to the DC, even after SetWindowText!
GetWindowRect(hCtrl, &rect);
dh = rect.bottom - rect.top;
DrawTextU(hDC, szMessageText, -1, &rect, DT_CALCRECT | DT_WORDBREAK);
dh = rect.bottom - rect.top - dh;
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
ResizeMoveCtrl(hDlg, hCtrl, 0, 0, 0, dh, 1.0f);
for (i = 0; i < nDialogItems; i++)
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_LIST_ITEM1 + i), 0, dh, 0, 0, 1.0f);
if (nDialogItems > 1) {
GetWindowRect(GetDlgItem(hDlg, IDC_LIST_ITEM1), &rect);
GetWindowRect(GetDlgItem(hDlg, IDC_LIST_ITEM1 + nDialogItems - 1), &rect2);
dh += rect2.top - rect.top;
}
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, dh, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, -1), 0, 0, 0, dh, 1.0f); // IDC_STATIC = -1
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_LIST_LINE), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDOK), 0, dh, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, dh, 0, 0, 1.0f);
return (INT_PTR)TRUE;
case WM_CTLCOLORSTATIC:
// Change the background colour for static text and icon
SetBkMode((HDC)wParam, TRANSPARENT);
if ((HWND)lParam == GetDlgItem(hDlg, IDC_NOTIFICATION_LINE)) {
return (INT_PTR)separator_brush;
}
return (INT_PTR)background_brush;
case WM_NCHITTEST:
// Check coordinates to prevent resize actions
loc = DefWindowProc(hDlg, message, wParam, lParam);
for (i = 0; i < 9; i++) {
if (loc == disabled[i]) {
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
case IDNO:
case IDCANCEL:
EndDialog(hDlg, r);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Display a dialog with a list of items
*/
void ListDialog(char* title, char* message, char** items, int size)
{
dialog_showing++;
szMessageTitle = title;
szMessageText = message;
szDialogItem = items;
nDialogItems = size;
MyDialogBox(hMainInstance, IDD_LIST, hMainDialog, ListCallback);
dialog_showing--;
}
static struct {
HWND hTip; // Tooltip handle
HWND hCtrl; // Handle of the control the tooltip belongs to
WNDPROC original_proc;
LPWSTR wstring;
} ttlist[MAX_TOOLTIPS] = { {0} };
INT_PTR CALLBACK TooltipCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
LPNMTTDISPINFOW lpnmtdi;
int i = MAX_TOOLTIPS;
// Make sure we have an original proc
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == hDlg) break;
}
if (i == MAX_TOOLTIPS)
return (INT_PTR)FALSE;
switch (message) {
case WM_NOTIFY:
switch (((LPNMHDR)lParam)->code) {
case TTN_GETDISPINFOW:
lpnmtdi = (LPNMTTDISPINFOW)lParam;
lpnmtdi->lpszText = ttlist[i].wstring;
SendMessage(hDlg, TTM_SETMAXTIPWIDTH, 0, 300);
return (INT_PTR)TRUE;
}
break;
}
#ifdef _DEBUG
// comctl32 causes issues if the tooltips are not being manipulated from the same thread as their parent controls
if (GetCurrentThreadId() != MainThreadId)
uprintf("Warning: Tooltip callback is being called from wrong thread");
#endif
return CallWindowProc(ttlist[i].original_proc, hDlg, message, wParam, lParam);
}
/*
* Create a tooltip for the control passed as first parameter
* duration sets the duration in ms. Use -1 for default
* message is an UTF-8 string
*/
BOOL CreateTooltip(HWND hControl, const char* message, int duration)
{
TOOLINFOW toolInfo = {0};
int i;
if ( (hControl == NULL) || (message == NULL) ) {
return FALSE;
}
// Destroy existing tooltip if any
DestroyTooltip(hControl);
// Find an empty slot
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == NULL) break;
}
if (i >= MAX_TOOLTIPS) {
uprintf("Maximum number of tooltips reached (%d)\n", MAX_TOOLTIPS);
return FALSE;
}
// Create the tooltip window
ttlist[i].hTip = CreateWindowExW(0, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hMainDialog, NULL,
hMainInstance, NULL);
if (ttlist[i].hTip == NULL) {
return FALSE;
}
ttlist[i].hCtrl = hControl;
// Subclass the tooltip to handle multiline
ttlist[i].original_proc = (WNDPROC)SetWindowLongPtr(ttlist[i].hTip, GWLP_WNDPROC, (LONG_PTR)TooltipCallback);
// Set the string to display (can be multiline)
ttlist[i].wstring = utf8_to_wchar(message);
// Set tooltip duration (ms)
PostMessage(ttlist[i].hTip, TTM_SETDELAYTIME, (WPARAM)TTDT_AUTOPOP, (LPARAM)duration);
// Associate the tooltip to the control
toolInfo.cbSize = sizeof(toolInfo);
toolInfo.hwnd = ttlist[i].hTip; // Set to the tooltip itself to ease up subclassing
toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS | ((right_to_left_mode)?TTF_RTLREADING:0);
// set TTF_NOTBUTTON and TTF_CENTERTIP if it isn't a button
if (!(SendMessage(hControl, WM_GETDLGCODE, 0, 0) & DLGC_BUTTON))
toolInfo.uFlags |= 0x80000000L | TTF_CENTERTIP;
toolInfo.uId = (UINT_PTR)hControl;
toolInfo.lpszText = LPSTR_TEXTCALLBACKW;
SendMessageW(ttlist[i].hTip, TTM_ADDTOOLW, 0, (LPARAM)&toolInfo);
return TRUE;
}
/* Destroy a tooltip. hCtrl = handle of the control the tooltip is associated with */
void DestroyTooltip(HWND hControl)
{
int i;
if (hControl == NULL) return;
for (i=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hCtrl == hControl) break;
}
if (i >= MAX_TOOLTIPS) return;
DestroyWindow(ttlist[i].hTip);
safe_free(ttlist[i].wstring);
ttlist[i].original_proc = NULL;
ttlist[i].hTip = NULL;
ttlist[i].hCtrl = NULL;
}
void DestroyAllTooltips(void)
{
int i, j;
for (i=0, j=0; i<MAX_TOOLTIPS; i++) {
if (ttlist[i].hTip == NULL) continue;
j++;
DestroyWindow(ttlist[i].hTip);
safe_free(ttlist[i].wstring);
ttlist[i].original_proc = NULL;
ttlist[i].hTip = NULL;
ttlist[i].hCtrl = NULL;
}
}
/* Determine if a Windows is being displayed or not */
BOOL IsShown(HWND hDlg)
{
WINDOWPLACEMENT placement = {0};
placement.length = sizeof(WINDOWPLACEMENT);
if (!GetWindowPlacement(hDlg, &placement))
return FALSE;
switch (placement.showCmd) {
case SW_SHOWNORMAL:
case SW_SHOWMAXIMIZED:
case SW_SHOW:
case SW_SHOWDEFAULT:
return TRUE;
default:
return FALSE;
}
}
/* Compute the width of a dropdown list entry */
LONG GetEntryWidth(HWND hDropDown, const char *entry)
{
HDC hDC;
HFONT hFont, hDefFont = NULL;
SIZE size;
hDC = GetDC(hDropDown);
hFont = (HFONT)SendMessage(hDropDown, WM_GETFONT, 0, 0);
if (hFont != NULL)
hDefFont = (HFONT)SelectObject(hDC, hFont);
if (!GetTextExtentPointU(hDC, entry, &size))
size.cx = 0;
if (hFont != NULL)
SelectObject(hDC, hDefFont);
if (hDC != NULL)
ReleaseDC(hDropDown, hDC);
return size.cx;
}
/*
* Windows 7 taskbar icon handling (progress bar overlay, etc)
* Some platforms don't have these, so we redefine
*/
typedef enum MY_STPFLAG
{
MY_STPF_NONE = 0,
MY_STPF_USEAPPTHUMBNAILALWAYS = 0x1,
MY_STPF_USEAPPTHUMBNAILWHENACTIVE = 0x2,
MY_STPF_USEAPPPEEKALWAYS = 0x4,
MY_STPF_USEAPPPEEKWHENACTIVE = 0x8
} MY_STPFLAG;
typedef enum MY_THUMBBUTTONMASK
{
MY_THB_BITMAP = 0x1,
MY_THB_ICON = 0x2,
MY_THB_TOOLTIP = 0x4,
MY_THB_FLAGS = 0x8
} MY_THUMBBUTTONMASK;
typedef enum MY_THUMBBUTTONFLAGS
{
MY_THBF_ENABLED = 0,
MY_THBF_DISABLED = 0x1,
MY_THBF_DISMISSONCLICK = 0x2,
MY_THBF_NOBACKGROUND = 0x4,
MY_THBF_HIDDEN = 0x8,
MY_THBF_NONINTERACTIVE = 0x10
} MY_THUMBBUTTONFLAGS;
typedef struct MY_THUMBBUTTON
{
MY_THUMBBUTTONMASK dwMask;
UINT iId;
UINT iBitmap;
HICON hIcon;
WCHAR szTip[260];
MY_THUMBBUTTONFLAGS dwFlags;
} MY_THUMBBUTTON;
/*
typedef enum MY_TBPFLAG
{
TASKBAR_NOPROGRESS = 0,
TASKBAR_INDETERMINATE = 0x1,
TASKBAR_NORMAL = 0x2,
TASKBAR_ERROR = 0x4,
TASKBAR_PAUSED = 0x8
} MY_TBPFLAG;
*/
#pragma push_macro("INTERFACE")
#undef INTERFACE
#define INTERFACE my_ITaskbarList3
DECLARE_INTERFACE_(my_ITaskbarList3, IUnknown) {
STDMETHOD (QueryInterface) (THIS_ REFIID riid, LPVOID *ppvObj) PURE;
STDMETHOD_(ULONG, AddRef) (THIS) PURE;
STDMETHOD_(ULONG, Release) (THIS) PURE;
STDMETHOD (HrInit) (THIS) PURE;
STDMETHOD (AddTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (DeleteTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (ActivateTab) (THIS_ HWND hwnd) PURE;
STDMETHOD (SetActiveAlt) (THIS_ HWND hwnd) PURE;
STDMETHOD (MarkFullscreenWindow) (THIS_ HWND hwnd, int fFullscreen) PURE;
STDMETHOD (SetProgressValue) (THIS_ HWND hwnd, ULONGLONG ullCompleted, ULONGLONG ullTotal) PURE;
STDMETHOD (SetProgressState) (THIS_ HWND hwnd, TASKBAR_PROGRESS_FLAGS tbpFlags) PURE;
STDMETHOD (RegisterTab) (THIS_ HWND hwndTab,HWND hwndMDI) PURE;
STDMETHOD (UnregisterTab) (THIS_ HWND hwndTab) PURE;
STDMETHOD (SetTabOrder) (THIS_ HWND hwndTab, HWND hwndInsertBefore) PURE;
STDMETHOD (SetTabActive) (THIS_ HWND hwndTab, HWND hwndMDI, DWORD dwReserved) PURE;
STDMETHOD (ThumbBarAddButtons) (THIS_ HWND hwnd, UINT cButtons, MY_THUMBBUTTON* pButton) PURE;
STDMETHOD (ThumbBarUpdateButtons) (THIS_ HWND hwnd, UINT cButtons, MY_THUMBBUTTON* pButton) PURE;
STDMETHOD (ThumbBarSetImageList) (THIS_ HWND hwnd, HIMAGELIST himl) PURE;
STDMETHOD (SetOverlayIcon) (THIS_ HWND hwnd, HICON hIcon, LPCWSTR pszDescription) PURE;
STDMETHOD (SetThumbnailTooltip) (THIS_ HWND hwnd, LPCWSTR pszTip) PURE;
STDMETHOD (SetThumbnailClip) (THIS_ HWND hwnd, RECT *prcClip) PURE;
};
const IID my_IID_ITaskbarList3 =
{ 0xea1afb91, 0x9e28, 0x4b86, { 0x90, 0xe9, 0x9e, 0x9f, 0x8a, 0x5e, 0xef, 0xaf } };
const IID my_CLSID_TaskbarList =
{ 0x56fdf344, 0xfd6d, 0x11d0, { 0x95, 0x8a ,0x0, 0x60, 0x97, 0xc9, 0xa0 ,0x90 } };
static my_ITaskbarList3* ptbl = NULL;
// Create a taskbar icon progressbar
BOOL CreateTaskbarList(void)
{
HRESULT hr;
if (nWindowsVersion < WINDOWS_7)
// Only valid for Windows 7 or later
return FALSE;
hr = CoCreateInstance(&my_CLSID_TaskbarList, NULL, CLSCTX_ALL, &my_IID_ITaskbarList3, (LPVOID)&ptbl);
if (FAILED(hr)) {
uprintf("CoCreateInstance for TaskbarList failed: error %X\n", hr);
ptbl = NULL;
return FALSE;
}
return TRUE;
}
BOOL SetTaskbarProgressState(TASKBAR_PROGRESS_FLAGS tbpFlags)
{
if (ptbl == NULL)
return FALSE;
return !FAILED(ptbl->lpVtbl->SetProgressState(ptbl, hMainDialog, tbpFlags));
}
BOOL SetTaskbarProgressValue(ULONGLONG ullCompleted, ULONGLONG ullTotal)
{
if (ptbl == NULL)
return FALSE;
return !FAILED(ptbl->lpVtbl->SetProgressValue(ptbl, hMainDialog, ullCompleted, ullTotal));
}
#pragma pop_macro("INTERFACE")
/*
* Update policy and settings dialog callback
*/
INT_PTR CALLBACK UpdateCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int dy;
RECT rect;
REQRESIZE* rsz;
HWND hPolicy;
static HWND hFrequency, hBeta;
int32_t freq;
char update_policy_text[4096];
static BOOL resized_already = TRUE;
switch (message) {
case WM_INITDIALOG:
resized_already = FALSE;
hUpdatesDlg = hDlg;
apply_localization(IDD_UPDATE_POLICY, hDlg);
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
hFrequency = GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY);
hBeta = GetDlgItem(hDlg, IDC_INCLUDE_BETAS);
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_013)), -1));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_030, lmprintf(MSG_014))), 86400));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_015)), 604800));
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_016)), 2629800));
freq = ReadSetting32(SETTING_UPDATE_INTERVAL);
EnableWindow(GetDlgItem(hDlg, IDC_CHECK_NOW), (freq != 0));
EnableWindow(hBeta, (freq >= 0));
switch(freq) {
case -1:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 0));
break;
case 0:
case 86400:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 1));
break;
case 604800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 2));
break;
case 2629800:
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 3));
break;
default:
IGNORE_RETVAL(ComboBox_SetItemData(hFrequency, ComboBox_AddStringU(hFrequency, lmprintf(MSG_017)), freq));
IGNORE_RETVAL(ComboBox_SetCurSel(hFrequency, 4));
break;
}
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_008)));
IGNORE_RETVAL(ComboBox_AddStringU(hBeta, lmprintf(MSG_009)));
IGNORE_RETVAL(ComboBox_SetCurSel(hBeta, ReadSettingBool(SETTING_INCLUDE_BETAS)?0:1));
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
SendMessage(hPolicy, EM_AUTOURLDETECT, 1, 0);
static_sprintf(update_policy_text, update_policy, lmprintf(MSG_179|MSG_RTF),
lmprintf(MSG_180|MSG_RTF), lmprintf(MSG_181|MSG_RTF), lmprintf(MSG_182|MSG_RTF), lmprintf(MSG_183|MSG_RTF),
lmprintf(MSG_184|MSG_RTF), lmprintf(MSG_185|MSG_RTF), lmprintf(MSG_186|MSG_RTF));
SendMessageA(hPolicy, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update_policy_text);
SendMessage(hPolicy, EM_SETSEL, -1, -1);
SendMessage(hPolicy, EM_SETEVENTMASK, 0, ENM_LINK|ENM_REQUESTRESIZE);
SendMessageA(hPolicy, EM_SETBKGNDCOLOR, 0, (LPARAM)GetSysColor(COLOR_BTNFACE));
SendMessage(hPolicy, EM_REQUESTRESIZE, 0, 0);
break;
case WM_NOTIFY:
if ((((LPNMHDR)lParam)->code == EN_REQUESTRESIZE) && (!resized_already)) {
resized_already = TRUE;
hPolicy = GetDlgItem(hDlg, IDC_POLICY);
GetWindowRect(hPolicy, &rect);
dy = rect.bottom - rect.top;
rsz = (REQRESIZE *)lParam;
dy -= rsz->rc.bottom - rsz->rc.top + 6; // add the border
ResizeMoveCtrl(hDlg, hDlg, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, hPolicy, 0, 0, 0, -dy, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_SETTINGS_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_UPDATE_FREQUENCY_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_UPDATE_FREQUENCY), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_INCLUDE_BETAS_TXT), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_INCLUDE_BETAS), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDS_CHECK_NOW_GRP), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDC_CHECK_NOW), 0, -dy, 0, 0, 1.0f);
ResizeMoveCtrl(hDlg, GetDlgItem(hDlg, IDCANCEL), 0, -dy, 0, 0, 1.0f);
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
reset_localization(IDD_UPDATE_POLICY);
EndDialog(hDlg, LOWORD(wParam));
hUpdatesDlg = NULL;
return (INT_PTR)TRUE;
case IDC_CHECK_NOW:
CheckForUpdates(TRUE);
return (INT_PTR)TRUE;
case IDC_UPDATE_FREQUENCY:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
freq = (int32_t)ComboBox_GetItemData(hFrequency, ComboBox_GetCurSel(hFrequency));
WriteSetting32(SETTING_UPDATE_INTERVAL, (DWORD)freq);
EnableWindow(hBeta, (freq >= 0));
return (INT_PTR)TRUE;
case IDC_INCLUDE_BETAS:
if (HIWORD(wParam) != CBN_SELCHANGE)
break;
WriteSettingBool(SETTING_INCLUDE_BETAS, ComboBox_GetCurSel(hBeta) == 0);
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
/*
* Initial update check setup
*/
BOOL SetUpdateCheck(void)
{
BOOL enable_updates;
uint64_t commcheck = _GetTickCount64();
notification_info more_info = { IDD_UPDATE_POLICY, UpdateCallback };
char filename[MAX_PATH] = "", exename[] = APPLICATION_NAME ".exe";
size_t fn_len, exe_len;
// Test if we can read and write settings. If not, forget it.
WriteSetting64(SETTING_COMM_CHECK, commcheck);
if (ReadSetting64(SETTING_COMM_CHECK) != commcheck)
return FALSE;
settings_commcheck = TRUE;
// If the update interval is not set, this is the first time we run so prompt the user
if (ReadSetting32(SETTING_UPDATE_INTERVAL) == 0) {
// Add a hack for people who'd prefer the app not to prompt about update settings on first run.
// If the executable is called "rufus.exe", without version, we disable the prompt
GetModuleFileNameU(NULL, filename, sizeof(filename));
fn_len = safe_strlen(filename);
exe_len = safe_strlen(exename);
#if !defined(_DEBUG) // Don't allow disabling update prompt, unless it's a release
if ((fn_len > exe_len) && (safe_stricmp(&filename[fn_len-exe_len], exename) == 0)) {
uprintf("Short name used - Disabling initial update policy prompt\n");
enable_updates = TRUE;
} else {
#endif
enable_updates = Notification(MSG_QUESTION, &more_info, lmprintf(MSG_004), lmprintf(MSG_005));
#if !defined(_DEBUG)
}
#endif
if (!enable_updates) {
WriteSetting32(SETTING_UPDATE_INTERVAL, -1);
return FALSE;
}
// If the user hasn't set the interval in the dialog, set to default
if ( (ReadSetting32(SETTING_UPDATE_INTERVAL) == 0) ||
((ReadSetting32(SETTING_UPDATE_INTERVAL) == -1) && enable_updates) )
WriteSetting32(SETTING_UPDATE_INTERVAL, 86400);
}
return TRUE;
}
static void CreateStaticFont(HDC dc, HFONT* hyperlink_font) {
TEXTMETRIC tm;
LOGFONT lf;
if (*hyperlink_font != NULL)
return;
GetTextMetrics(dc, &tm);
lf.lfHeight = tm.tmHeight;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = tm.tmWeight;
lf.lfItalic = tm.tmItalic;
lf.lfUnderline = TRUE;
lf.lfStrikeOut = tm.tmStruckOut;
lf.lfCharSet = tm.tmCharSet;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = tm.tmPitchAndFamily;
GetTextFace(dc, LF_FACESIZE, lf.lfFaceName);
*hyperlink_font = CreateFontIndirect(&lf);
}
/*
* Work around the limitations of edit control, to display a hand cursor for hyperlinks
* NB: The LTEXT control must have SS_NOTIFY attribute for this to work
*/
INT_PTR CALLBACK update_subclass_callback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_SETCURSOR:
if ((HWND)wParam == GetDlgItem(hDlg, IDC_WEBSITE)) {
SetCursor(LoadCursor(NULL, IDC_HAND));
return (INT_PTR)TRUE;
}
break;
}
return CallWindowProc(update_original_proc, hDlg, message, wParam, lParam);
}
/*
* New version notification dialog
*/
INT_PTR CALLBACK NewVersionCallback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
char cmdline[] = APPLICATION_NAME " -w 150";
static char* filepath = NULL;
static int download_status = 0;
LONG i;
HWND hNotes;
STARTUPINFOA si;
PROCESS_INFORMATION pi;
HFONT hyperlink_font = NULL;
EXT_DECL(dl_ext, NULL, __VA_GROUP__("*.exe"), __VA_GROUP__(lmprintf(MSG_037)));
switch (message) {
case WM_INITDIALOG:
apply_localization(IDD_NEW_VERSION, hDlg);
download_status = 0;
SetTitleBarIcon(hDlg);
CenterDialog(hDlg);
// Subclass the callback so that we can change the cursor
update_original_proc = (WNDPROC)SetWindowLongPtr(hDlg, GWLP_WNDPROC, (LONG_PTR)update_subclass_callback);
hNotes = GetDlgItem(hDlg, IDC_RELEASE_NOTES);
SendMessage(hNotes, EM_AUTOURLDETECT, 1, 0);
SendMessageA(hNotes, EM_SETTEXTEX, (WPARAM)&friggin_microsoft_unicode_amateurs, (LPARAM)update.release_notes);
SendMessage(hNotes, EM_SETSEL, -1, -1);
SendMessage(hNotes, EM_SETEVENTMASK, 0, ENM_LINK);
SetWindowTextU(GetDlgItem(hDlg, IDC_YOUR_VERSION), lmprintf(MSG_018,
rufus_version[0], rufus_version[1], rufus_version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_LATEST_VERSION), lmprintf(MSG_019,
update.version[0], update.version[1], update.version[2]));
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD_URL), update.download_url);
SendMessage(GetDlgItem(hDlg, IDC_PROGRESS), PBM_SETRANGE, 0, (MAX_PROGRESS<<16) & 0xFFFF0000);
if (update.download_url == NULL)
EnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);
break;
case WM_CTLCOLORSTATIC:
if ((HWND)lParam != GetDlgItem(hDlg, IDC_WEBSITE))
return FALSE;
// Change the font for the hyperlink
SetBkMode((HDC)wParam, TRANSPARENT);
CreateStaticFont((HDC)wParam, &hyperlink_font);
SelectObject((HDC)wParam, hyperlink_font);
SetTextColor((HDC)wParam, RGB(0,0,125)); // DARK_BLUE
return (INT_PTR)CreateSolidBrush(GetSysColor(COLOR_BTNFACE));
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDCLOSE:
case IDCANCEL:
if (download_status != 1) {
reset_localization(IDD_NEW_VERSION);
safe_free(filepath);
EndDialog(hDlg, LOWORD(wParam));
}
return (INT_PTR)TRUE;
case IDC_WEBSITE:
ShellExecuteA(hDlg, "open", RUFUS_URL, NULL, NULL, SW_SHOWNORMAL);
break;
case IDC_DOWNLOAD: // Also doubles as abort and launch function
switch(download_status) {
case 1: // Abort
FormatStatus = ERROR_SEVERITY_ERROR|FAC(FACILITY_STORAGE)|ERROR_CANCELLED;
download_status = 0;
break;
case 2: // Launch newer version and close this one
Sleep(1000); // Add a delay on account of antivirus scanners
if (ValidateSignature(hDlg, filepath) != NO_ERROR) {
// Unconditionally delete the download and disable the "Launch" control
_unlinkU(filepath);
EnableWindow(GetDlgItem(hDlg, IDC_DOWNLOAD), FALSE);
break;
}
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
if (!CreateProcessU(filepath, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
PrintInfo(0, MSG_214);
uprintf("Failed to launch new application: %s\n", WindowsErrorString());
} else {
PrintInfo(0, MSG_213);
PostMessage(hDlg, WM_COMMAND, (WPARAM)IDCLOSE, 0);
PostMessage(hMainDialog, WM_CLOSE, 0, 0);
}
break;
default: // Download
if (update.download_url == NULL) {
uprintf("Could not get download URL\n");
break;
}
for (i=(int)strlen(update.download_url); (i>0)&&(update.download_url[i]!='/'); i--);
dl_ext.filename = &update.download_url[i+1];
filepath = FileDialog(TRUE, app_dir, &dl_ext, OFN_NOCHANGEDIR);
if (filepath == NULL) {
uprintf("Could not get save path\n");
break;
}
// Opening the File Dialog will make us lose tabbing focus - set it back
SendMessage(hDlg, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(hDlg, IDC_DOWNLOAD), TRUE);
DownloadFileThreaded(update.download_url, filepath, hDlg);
break;
}
return (INT_PTR)TRUE;
}
break;
case UM_PROGRESS_INIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), FALSE);
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_038));
FormatStatus = 0;
download_status = 1;
return (INT_PTR)TRUE;
case UM_PROGRESS_EXIT:
EnableWindow(GetDlgItem(hDlg, IDCANCEL), TRUE);
if (wParam) {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_039));
download_status = 2;
} else {
SetWindowTextU(GetDlgItem(hDlg, IDC_DOWNLOAD), lmprintf(MSG_040));
download_status = 0;
}
return (INT_PTR)TRUE;
}
return (INT_PTR)FALSE;
}
void DownloadNewVersion(void)
{
MyDialogBox(hMainInstance, IDD_NEW_VERSION, hMainDialog, NewVersionCallback);
}
void SetTitleBarIcon(HWND hDlg)
{
int i16, s16, s32;
HICON hSmallIcon, hBigIcon;
// High DPI scaling
i16 = GetSystemMetrics(SM_CXSMICON);
// Adjust icon size lookup
s16 = i16;
s32 = (int)(32.0f*fScale);
if (s16 >= 54)
s16 = 64;
else if (s16 >= 40)
s16 = 48;
else if (s16 >= 28)
s16 = 32;
else if (s16 >= 20)
s16 = 24;
if (s32 >= 54)
s32 = 64;
else if (s32 >= 40)
s32 = 48;
else if (s32 >= 28)
s32 = 32;
else if (s32 >= 20)
s32 = 24;
// Create the title bar icon
hSmallIcon = (HICON)LoadImage(hMainInstance, MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, s16, s16, 0);
SendMessage (hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hSmallIcon);
hBigIcon = (HICON)LoadImage(hMainInstance, MAKEINTRESOURCE(IDI_ICON), IMAGE_ICON, s32, s32, 0);
SendMessage (hDlg, WM_SETICON, ICON_BIG, (LPARAM)hBigIcon);
}
// Return the onscreen size of the text displayed by a control
SIZE GetTextSize(HWND hCtrl)
{
SIZE sz = {0, 0};
HDC hDC;
wchar_t *wstr = NULL;
int len;
HFONT hFont;
// Compute the size of the text
hDC = GetDC(hCtrl);
if (hDC == NULL)
goto out;
hFont = (HFONT)SendMessageA(hCtrl, WM_GETFONT, 0, 0);
if (hFont == NULL)
goto out;
SelectObject(hDC, hFont);
len = GetWindowTextLengthW(hCtrl);
if (len <= 0)
goto out;
wstr = calloc(len + 1, sizeof(wchar_t));
if (wstr == NULL)
goto out;
if (GetWindowTextW(hCtrl, wstr, len + 1) > 0)
GetTextExtentPoint32W(hDC, wstr, len, &sz);
out:
safe_free(wstr);
if (hDC != NULL)
ReleaseDC(hCtrl, hDC);
return sz;
}
/*
* The following is used to work around dialog template limitations when switching from LTR to RTL
* or switching the font. This avoids having to multiply similar templates in the RC.
* TODO: Can we use http://stackoverflow.com/questions/6057239/which-font-is-the-default-for-mfc-dialog-controls?
* TODO: We are supposed to use Segoe with font size 9 in Vista or later
*/
// Produce a dialog template from our RC, and update its RTL and Font settings dynamically
// See http://blogs.msdn.com/b/oldnewthing/archive/2004/06/21/163596.aspx as well as
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms645389.aspx for a description
// of the Dialog structure
LPCDLGTEMPLATE GetDialogTemplate(int Dialog_ID)
{
int i;
const char thai_id[] = "th-TH";
size_t len;
DWORD size;
DWORD* dwBuf;
WCHAR* wBuf;
LPCDLGTEMPLATE rcTemplate = (LPCDLGTEMPLATE) GetResource(hMainInstance, MAKEINTRESOURCEA(Dialog_ID),
_RT_DIALOG, get_name_from_id(Dialog_ID), &size, TRUE);
if ((size == 0) || (rcTemplate == NULL)) {
safe_free(rcTemplate);
return NULL;
}
if (right_to_left_mode) {
// Add the RTL styles into our RC copy, so that we don't have to multiply dialog definitions in the RC
dwBuf = (DWORD*)rcTemplate;
dwBuf[2] = WS_EX_RTLREADING | WS_EX_APPWINDOW | WS_EX_LAYOUTRTL;
}
// All our dialogs are set to use 'Segoe UI Symbol' by default:
// 1. So that we can replace the font name with 'MS Shell Dlg' (XP) or 'Segoe UI'
// 2. So that Thai displays properly on RTF controls as it won't work with regular
// 'Segoe UI'... but Cyrillic won't work with 'Segoe UI Symbol'
// If 'Segoe UI Symbol' is available, and we are using Thai, we're done here
if (IsFontAvailable("Segoe UI Symbol") && (selected_locale != NULL)
&& (safe_strcmp(selected_locale->txt[0], thai_id) == 0))
return rcTemplate;
// 'Segoe UI Symbol' cannot be used => Fall back to the best we have
wBuf = (WCHAR*)rcTemplate;
wBuf = &wBuf[14]; // Move to class name
// Skip class name and title
for (i = 0; i<2; i++) {
if (*wBuf == 0xFFFF)
wBuf = &wBuf[2]; // Ordinal
else
wBuf = &wBuf[wcslen(wBuf) + 1]; // String
}
// NB: to change the font size to 9, you can use
// wBuf[0] = 0x0009;
wBuf = &wBuf[3];
// Make sure we are where we want to be and adjust the font
if (wcscmp(L"Segoe UI Symbol", wBuf) == 0) {
uintptr_t src, dst, start = (uintptr_t)rcTemplate;
// We can't simply zero the characters we don't want, as the size of the font
// string determines the next item lookup. So we must memmove the remaining of
// our buffer. Oh, and those items are DWORD aligned.
if ((nWindowsVersion > WINDOWS_XP) && IsFontAvailable("Segoe UI")) {
// 'Segoe UI Symbol' -> 'Segoe UI'
wBuf[8] = 0;
} else {
wcscpy(wBuf, L"MS Shell Dlg");
}
len = wcslen(wBuf);
wBuf[len + 1] = 0;
dst = (uintptr_t)&wBuf[len + 2];
dst &= ~3;
src = (uintptr_t)&wBuf[17];
src &= ~3;
memmove((void*)dst, (void*)src, size - (src - start));
} else {
uprintf("Could not locate font for %s!", get_name_from_id(Dialog_ID));
}
return rcTemplate;
}
HWND MyCreateDialog(HINSTANCE hInstance, int Dialog_ID, HWND hWndParent, DLGPROC lpDialogFunc)
{
LPCDLGTEMPLATE rcTemplate = GetDialogTemplate(Dialog_ID);
HWND hDlg = CreateDialogIndirect(hInstance, rcTemplate, hWndParent, lpDialogFunc);
safe_free(rcTemplate);
return hDlg;
}
INT_PTR MyDialogBox(HINSTANCE hInstance, int Dialog_ID, HWND hWndParent, DLGPROC lpDialogFunc)
{
INT_PTR ret;
LPCDLGTEMPLATE rcTemplate = GetDialogTemplate(Dialog_ID);
// A DialogBox doesn't handle reduce/restore so it won't pass restore messages to the
// main dialog if the main dialog was minimized. This can result in situations where the
// user cannot restore the main window if a new dialog prompt was triggered while the
// main dialog was reduced => Ensure the main dialog is visible before we display anything.
ShowWindow(hMainDialog, SW_NORMAL);
ret = DialogBoxIndirect(hMainInstance, rcTemplate, hWndParent, lpDialogFunc);
safe_free(rcTemplate);
return ret;
}
/*
* The following function calls are used to automatically detect and close the native
* Windows format prompt "You must format the disk in drive X:". To do that, we use an
* event hook that gets triggered whenever a window is placed in the foreground.
* In that hook, we look for a dialog that has style WS_POPUPWINDOW and has the relevant
* title. However, because the title in itself is too generic (the expectation is that
* it will be "Microsoft Windows") we also enumerate all the child controls from that
* prompt, using another callback, until we find one that contains the text we expect
* for the "Format disk" button.
* Oh, and since all of these strings are localized, we must first pick them up from
* the relevant mui (something like "C:\Windows\System32\en-GB\shell32.dll.mui")
*/
static BOOL CALLBACK FormatPromptCallback(HWND hWnd, LPARAM lParam)
{
char str[128];
BOOL *found = (BOOL*)lParam;
if (GetWindowTextU(hWnd, str, sizeof(str)) == 0)
return TRUE;
if (safe_strcmp(str, fp_button_str) == 0)
*found = TRUE;
return TRUE;
}
static void CALLBACK FormatPromptHook(HWINEVENTHOOK hWinEventHook, DWORD Event, HWND hWnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime)
{
char str[128];
BOOL found;
if (Event == EVENT_SYSTEM_FOREGROUND) {
if (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUPWINDOW) {
str[0] = 0;
GetWindowTextU(hWnd, str, sizeof(str));
if (safe_strcmp(str, fp_title_str) == 0) {
found = FALSE;
EnumChildWindows(hWnd, FormatPromptCallback, (LPARAM)&found);
if (found) {
SendMessage(hWnd, WM_COMMAND, (WPARAM)IDCANCEL, (LPARAM)0);
uprintf("Closed Windows format prompt");
}
}
}
}
}
BOOL SetFormatPromptHook(void)
{
HMODULE mui_lib;
char mui_path[MAX_PATH];
static char title_str[128], button_str[128];
if (fp_weh != NULL)
return TRUE; // No need to set again if active
// Fetch the localized strings in the relevant
static_sprintf(mui_path, "%s\\%s\\shell32.dll.mui", system_dir, GetCurrentMUI());
mui_lib = LoadLibraryU(mui_path);
if (mui_lib != NULL) {
// 4097 = "You need to format the disk in drive %c: before you can use it." (dialog text)
// 4125 = "Microsoft Windows" (dialog title)
// 4126 = "Format disk" (button)
if (LoadStringU(mui_lib, 4125, title_str, sizeof(title_str)) > 0)
fp_title_str = title_str;
else
uprintf("Warning: Could not locate localized format prompt title string in '%s': %s", mui_path, WindowsErrorString());
if (LoadStringU(mui_lib, 4126, button_str, sizeof(button_str)) > 0)
fp_button_str = button_str;
else
uprintf("Warning: Could not locate localized format prompt button string in '%s': %s", mui_path, WindowsErrorString());
FreeLibrary(mui_lib);
}
fp_weh = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL,
FormatPromptHook, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
return (fp_weh != NULL);
}
void ClrFormatPromptHook(void) {
UnhookWinEvent(fp_weh);
fp_weh = NULL;
}
void FlashTaskbar(HANDLE handle)
{
FLASHWINFO pf;
if (handle == NULL)
return;
pf.cbSize = sizeof(FLASHWINFO);
pf.hwnd = handle;
// Could also use FLASHW_ALL to flash the main dialog)
pf.dwFlags = FLASHW_TIMER | FLASHW_TRAY;
pf.uCount = 5;
pf.dwTimeout = 75;
FlashWindowEx(&pf);
}
#ifdef RUFUS_TEST
static __inline LPWORD lpwAlign(LPWORD addr)
{
return (LPWORD)((((uintptr_t)addr) + 3) & (~3));
}
INT_PTR CALLBACK SelectionDynCallback(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
int r = -1;
switch (message) {
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDOK:
r = 0;
case IDCANCEL:
EndDialog(hwndDlg, r);
return (INT_PTR)TRUE;
}
}
return FALSE;
}
int SelectionDyn(char* title, char* message, char** szChoice, int nChoices)
{
#define ID_RADIO 12345
LPCWSTR lpwszTypeFace = L"MS Shell Dlg";
LPDLGTEMPLATEA lpdt;
LPDLGITEMTEMPLATEA lpdit;
LPCWSTR lpwszCaption;
LPWORD lpw;
LPWSTR lpwsz;
int i, ret, nchar;
lpdt = (LPDLGTEMPLATE)calloc(512 + nChoices * 256, 1);
// Set up a dialog window
lpdt->style = WS_POPUP | WS_BORDER | WS_SYSMENU | WS_CAPTION | DS_MODALFRAME | DS_CENTER | DS_SHELLFONT;
lpdt->cdit = 2 + nChoices;
lpdt->x = 10;
lpdt->y = 10;
lpdt->cx = 300;
lpdt->cy = 100;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms645394.aspx:
// In a standard template for a dialog box, the DLGTEMPLATE structure is always immediately followed by
// three variable-length arrays that specify the menu, class, and title for the dialog box.
// When the DS_SETFONT style is specified, these arrays are also followed by a 16-bit value specifying
// point size and another variable-length array specifying a typeface name. Each array consists of one
// or more 16-bit elements. The menu, class, title, and font arrays must be aligned on WORD boundaries.
lpw = (LPWORD)(&lpdt[1]);
*lpw++ = 0; // No menu
*lpw++ = 0; // Default dialog class
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, title, -1, lpwsz, 50);
lpw += nchar;
// Set point size and typeface name if required
if (lpdt->style & (DS_SETFONT | DS_SHELLFONT)) {
*lpw++ = 8;
for (lpwsz = (LPWSTR)lpw, lpwszCaption = lpwszTypeFace; (*lpwsz++ = *lpwszCaption++) != 0; );
lpw = (LPWORD)lpwsz;
}
// Add an OK button
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON;
lpdit->x = 10;
lpdit->y = 70;
lpdit->cx = 50;
lpdit->cy = 14;
lpdit->id = IDOK;
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080; // Button class
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, "OK", -1, lpwsz, 50);
lpw += nchar;
*lpw++ = 0; // No creation data
// Add a Cancel button
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->x = 90;
lpdit->y = 70;
lpdit->cx = 50;
lpdit->cy = 14;
lpdit->id = IDCANCEL;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON;
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080;
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, lmprintf(MSG_007), -1, lpwsz, 50);
lpw += nchar;
*lpw++ = 0;
// Add radio buttons
for (i = 0; i < nChoices; i++) {
lpw = lpwAlign(lpw);
lpdit = (LPDLGITEMTEMPLATE)lpw;
lpdit->x = 10;
lpdit->y = 10 + 15 * i;
lpdit->cx = 40;
lpdit->cy = 20;
lpdit->id = ID_RADIO;
lpdit->style = WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON | (i == 0 ? WS_GROUP : 0);
lpw = (LPWORD)(&lpdit[1]);
*lpw++ = 0xFFFF;
*lpw++ = 0x0080;
lpwsz = (LPWSTR)lpw;
nchar = MultiByteToWideChar(CP_UTF8, 0, szChoice[i], -1, lpwsz, 150);
lpw += nchar;
*lpw++ = 0;
}
ret = (int)DialogBoxIndirect(hMainInstance, (LPDLGTEMPLATE)lpdt, hMainDialog, (DLGPROC)SelectionDynCallback);
free(lpdt);
return ret;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-494/c/good_2732_3 |
crossvul-cpp_data_good_581_1 | /*
Copyright 2008-2018 LibRaw LLC (info@libraw.org)
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
This file is generated from Dave Coffin's dcraw.c
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net
Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/)
for more information
*/
#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"
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)
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, unsigned 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]);
}
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,
47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
int bypp = tiff_bps <= 8 ? 1 : 2;
int bufsize = width * 3 * bypp;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width > 32767 || raw_height > 32767)
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixel = raw_width*(raw_height+7);
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)
if(todo[i] < maxpixel)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
else
derror();
}
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)
{
#ifdef LIBRAW_LIBRARY_BUILD
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
int row, col;
#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);
}
}
if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF;
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[0x4002];
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(width>640 || height > 480)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
// All kodak radc images are 768x512
if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if (!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
if(col>=0)
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[272]; /* 264 looks enough */
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
{
int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
if (idx >= 0 && idx < 0xffff)
{
if ((RAW(row, col + i) = curve[idx]) >> 12)
derror();
}
else
derror();
}
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixels = raw_width*(raw_height+7);
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)];
unsigned idest = RAWINDEX(row, col + c);
unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);
if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion
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);
else
derror();
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
}
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
}
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++)
if(fabs(num)>0.00001f)
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 & 0x55555555U) << 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)
{
#ifdef LIBRAW_IOSPACE_CHECK
INT64 pos = ftell(ifp);
INT64 fsize = ifp->size();
if(fsize < 12 || (fsize-pos) < 12)
throw LIBRAW_EXCEPTION_IO_EOF;
#endif
*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);
}
}
static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); }
static float libraw_powf64l(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 libraw_powf64l(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
unsigned CLASS setCanonBodyFeatures(unsigned id)
{
if (id == 0x03740000) // EOS M3
id = 0x80000374;
else if (id == 0x03840000) // EOS M10
id = 0x80000384;
else if (id == 0x03940000) // EOS M5
id = 0x80000394;
else if (id == 0x04070000) // EOS M6
id = 0x80000407;
else if (id == 0x03980000) // EOS M100
id = 0x80000398;
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) || // M6
(id == 0x80000398) // M100
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return id;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
if (maxlen < 16)
return; // too short
CameraInfo[0] = 0;
CameraInfo[1] = 0;
if (type == 4)
{
if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) ||
(maxlen == 171) || (maxlen == 264) || (maxlen > 400))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2));
else if (maxlen == 72)
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2));
else if ((maxlen == 85) || (maxlen == 93))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2));
else if ((maxlen == 96) || (maxlen == 104))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2));
}
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
imgdata.other.CameraTemperature = 0.0f;
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x80000398) || // M100
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000))) // G1 X Mark III
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if (id == 0x5330303638ULL)
{
strcpy(model, "E-M10MarkIII");
}
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 24, SEEK_CUR);
tempAp = get2();
if (tempAp != 0)
imgdata.other.CameraTemperature = (float)(tempAp - 128);
tempAp = get2();
if (tempAp != -1)
imgdata.other.FlashGN = ((float)tempAp) / 32;
get2();
// fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x000c)
{
unsigned tS = get4();
sprintf (imgdata.shootinginfo.BodySerial, "%d", tS);
}
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 == 0x009a)
{
get4();
imgdata.sizes.raw_crop.cwidth = get4();
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cleft = get4();
imgdata.sizes.raw_crop.ctop = get4();
}
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 == 0x4013)
{
get4();
imgdata.makernotes.canon.AFMicroAdjMode = get4();
imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4());
}
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 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2cf << 1), SEEK_SET); // offset 719 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000) || // G1 X Mark III
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000398) || // EOS M100
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x1fc << 1), SEEK_SET); // offset 508 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2dc << 1), SEEK_SET); // offset 732 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x230 << 1), SEEK_SET); // offset 560 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
libraw_powf64l(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 =
libraw_powf64l(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 =
libraw_powf64l(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)
{
ushort idx;
static const struct
{
ushort scf[8];
/*
scf[0] camera id
scf[1] camera format
scf[2] camera mount: Minolta A, Sony E, fixed,
scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC
scf[4] lens mount
scf[5] tag 0x2010 group (0 if not used)
scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid
scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid
*/
} SonyCamFeatures[] = {
{256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{267, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{268, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{271, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{272, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{276, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{277, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd},
{289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd},
{294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa},
{295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff},
{298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{301, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa},
{303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa},
{304, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa},
{306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff},
{309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa},
{314, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{315, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{316, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{320, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{321, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{322, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{323, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{324, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{325, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{326, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{327, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{328, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{329, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{330, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{331, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{332, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{333, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{334, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{335, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{336, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{337, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{338, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{343, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{345, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{348, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{349, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{351, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{352, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd},
{355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{359, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{361, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{363, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 0, 0x0320, 0x019f},
{364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff},
};
imgdata.lens.makernotes.CamID = id;
if (id == 2)
{
imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
imgdata.makernotes.sony.group2010 = 0;
imgdata.makernotes.sony.real_iso_offset = 0xffff;
imgdata.makernotes.sony.ImageCount3_offset = 0xffff;
return;
}
else
idx = id - 256;
if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures))
{
if (!SonyCamFeatures[idx].scf[2])
return;
imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1];
imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2];
imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3];
if (SonyCamFeatures[idx].scf[4])
imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4];
imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5];
imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6];
imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7];
}
char *sbstr = strstr(software, " v");
if (sbstr != NULL)
{
sbstr += 2;
imgdata.makernotes.sony.firmware = atof(sbstr);
if ((id == 306) || (id == 311))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if (id == 312)
{
if (imgdata.makernotes.sony.firmware < 2.0f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if ((id == 318) || (id == 340))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01a0;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01b6;
}
}
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id)
{
short bufx;
if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2))
bufx = buf[1];
else if ((id >= 273) && (len >= 3))
bufx = buf[2];
else
return;
imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f;
}
void CLASS process_Sony_0x2010(uchar *buf, ushort len)
{
if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) ||
(len < (imgdata.makernotes.sony.real_iso_offset + 2)))
return;
if (imgdata.other.real_ISO < 0.1f)
{
uchar s[2];
s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]];
s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id)
{
ushort lid;
uchar s[4];
int c;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (len < 2)
return;
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(libraw_powf64l(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(libraw_powf64l(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 (len <= 0x106)
return;
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = libraw_powf64l(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)
{
if (len <= 0x108)
return;
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if (len <= 0x10a)
return;
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))
{
if (len <= 0x116)
return;
// "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)
{
if (len <= 0x117)
return;
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
}
if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362) || (id == 363))
{
if (len <= 0x8d)
return;
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)
{
if (len <= 0xf4)
return;
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))
{
if (len <= 0x7f)
return;
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);
}
if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) &&
(len >= (imgdata.makernotes.sony.ImageCount3_offset + 4)))
{
FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]];
imgdata.makernotes.sony.ImageCount3 = sget4(s);
}
if (id == 362)
{
for (c = 0; c < 6; c++)
{
imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]];
}
}
return;
}
void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id)
{
uchar s[4];
int c;
short bufx = buf[0];
if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f))
{ // 0x9400 'c' version
if ((id == 358) || (id == 362) || (id == 363) || (id == 365))
{
imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]];
}
else
{
FORC4 s[c] = SonySubstitution[buf[0x0a + c]];
imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s);
}
imgdata.makernotes.sony.Sony0x9400_version = 0xc;
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]];
FORC4 s[c] = SonySubstitution[buf[0x12 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots
FORC4 s[c] = SonySubstitution[buf[0x1a + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files
}
else if ((bufx == 0x0c) && (len >= 0x1f))
{ // 0x9400 'b' version
imgdata.makernotes.sony.Sony0x9400_version = 0xb;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]];
}
else if ((bufx == 0x0a) && (len >= 0x23))
{ // 0x9400 'a' version
imgdata.makernotes.sony.Sony0x9400_version = 0xa;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]];
}
else
return;
}
void CLASS process_Sony_0x9402(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) ||
(imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA))
return;
if (len < 5)
return;
short bufx = buf[0x00];
if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff))
return;
imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]);
return;
}
void CLASS process_Sony_0x9403(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = SonySubstitution[buf[4]];
if ((bufx == 0x00) || (bufx == 0x94))
return;
imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]);
return;
}
void CLASS process_Sony_0x9406(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = buf[0];
if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b))
return;
bufx = buf[2];
if ((bufx != 0x08) && (bufx != 0x1b))
return;
imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f;
return;
}
void CLASS process_Sony_0x940c(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) &&
(imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX))
return;
if (len <= 0x000a)
return;
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_0x940e(uchar *buf, ushort len, unsigned id)
{
if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]];
}
else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]];
}
else
return;
if (imgdata.makernotes.sony.AFMicroAdjValue != 0)
imgdata.makernotes.sony.AFMicroAdjOn = 1;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116,
ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400,
ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406,
ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len,
uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_len)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
if (table_buf_0x2010_len)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
if (table_buf_0x9050_len)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
if (table_buf_0x9400_len)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
if (table_buf_0x9402_len)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
if (table_buf_0x9403_len)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
if (table_buf_0x9406_len)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
if (table_buf_0x940c_len)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
if (table_buf_0x940e_len)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id);
free(table_buf_0x940e);
table_buf_0x940e_len = 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]);
if (len == 5478)
{
imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20;
imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0);
imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f;
}
}
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 = libraw_powf64l(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 == 0x3000) && (len < 256000))
{
uchar *table_buf_0x3000;
table_buf_0x3000 = (uchar *)malloc(len);
fread(table_buf_0x3000, len, 1, ifp);
for (int i = 0; i < 20; i++)
imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i];
}
else if (tag == 0x0116 && len < 256000)
{
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_len = len;
fread(table_buf_0x0116, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
}
else if (tag == 0x2010 && len < 256000)
{
table_buf_0x2010 = (uchar *)malloc(len);
table_buf_0x2010_len = len;
fread(table_buf_0x2010, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
}
else if (tag == 0x201a)
{
imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4();
}
else if (tag == 0x201b)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.shootinginfo.FocusMode = (short)uc;
}
else if (tag == 0x202c)
{
imgdata.makernotes.sony.MeteringMode2 = get2();
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_len = len;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
}
else if (tag == 0x9400 && len < 256000)
{
table_buf_0x9400 = (uchar *)malloc(len);
table_buf_0x9400_len = len;
fread(table_buf_0x9400, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
}
else if (tag == 0x9402 && len < 256000)
{
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_len = len;
fread(table_buf_0x9402, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
}
else if (tag == 0x9403 && len < 256000)
{
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_len = len;
fread(table_buf_0x9403, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
}
else if ((tag == 0x9405) && (len < 256000) && (len > 0x64))
{
uchar *table_buf_0x9405;
table_buf_0x9405 = (uchar *)malloc(len);
fread(table_buf_0x9405, len, 1, ifp);
uchar bufx = table_buf_0x9405[0x0];
if (imgdata.other.real_ISO < 0.1f)
{
if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) ||
(bufx == 0xb3) || (bufx == 0xe1))
{
uchar s[2];
s[0] = SonySubstitution[table_buf_0x9405[0x04]];
s[1] = SonySubstitution[table_buf_0x9405[0x05]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
free(table_buf_0x9405);
}
else if (tag == 0x9406 && len < 256000)
{
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_len = len;
fread(table_buf_0x9406, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_len = len;
fread(table_buf_0x940c, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
}
else if (tag == 0x940e && len < 256000)
{
table_buf_0x940e = (uchar *)malloc(len);
table_buf_0x940e_len = len;
fread(table_buf_0x940e, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x940e);
table_buf_0x940e_len = 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);
}
else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2))
{
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cwidth = get4();
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
short nWB, tWB;
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) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) ||
(tag == 0x2050) || (tag == 0x3000))
{
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;
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
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;
}
}
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];
}
}
}
else 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;
}
else 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;
}
else 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();
}
}
else 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;
}
}
else 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();
}
else
{
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(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 0x20200306:
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
break;
case 0x20200307:
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{ /*placeholder */
}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) ||
!strncasecmp(model, "KODAK P712", 10))
{
if (tag == 0xf90b)
{
imgdata.makernotes.kodak.clipBlack = get2();
}
else if (tag == 0xf90c)
{
imgdata.makernotes.kodak.clipWhite = get2();
}
}
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) ||
!strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0045)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2);
break;
case 0x20400612:
case 0x30000612:
imgdata.sizes.raw_crop.cleft = get2();
break;
case 0x20400613:
case 0x30000613:
imgdata.sizes.raw_crop.ctop = get2();
break;
case 0x20400614:
case 0x30000614:
imgdata.sizes.raw_crop.cwidth = get2();
break;
case 0x20400615:
case 0x30000615:
imgdata.sizes.raw_crop.cheight = get2();
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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
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 * libraw_powf64l(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 * libraw_powf64l(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = libraw_powf64l(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = libraw_powf64l(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 == 0x20200306)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
if (tag == 0x20200307)
{
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(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 = libraw_powf64l(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = libraw_powf64l(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, MIN(len,511), ifp);
mn_text[511] = 0;
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=");
if(pos)
{
pos +=4;
char *pos2 = strstr(pos, " ");
if(pos2)
{
l = pos2 - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
#if defined WIN32 || defined(__MINGW32__)
// Win32 strtok is already thread-safe
pos = strtok(ccms, ",");
#else
char *last=0;
pos = strtok_r(ccms, ",",&last);
#endif
if(pos)
{
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];
#if defined WIN32 || defined(__MINGW32__)
pos = strtok(NULL, ",");
#else
pos = strtok_r(NULL, ",",&last);
#endif
if(!pos) goto end; // broken
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
}
}
end:;
}
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) * 0x01010101U << 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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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) * 0x01010101U * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
else if(len < 1)
return;
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 j, c, wbi = -2, romm_camTemp[9], romm_camScale[3];
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1003)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 1004)
imgdata.sizes.raw_crop.ctop = get2();
if (tag == 1005)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 1006)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 1007)
imgdata.makernotes.kodak.BlackLevelTop = get2();
if (tag == 1008)
imgdata.makernotes.kodak.BlackLevelBottom = get2();
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 1030) && (len == 1))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 1043) && (len == 1))
imgdata.other.SensorTemperature = getreal(type);
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9))
{
short validM = 0;
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type);
}
validM = 1;
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
validM = 1;
}
}
if (validM)
{
romm_coeff(imgdata.makernotes.kodak.romm_camDaylight);
}
}
if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
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 == 0xfa13)
width = getint(type);
if (tag == 0xfa14)
height = (getint(type) + 1) & -2;
/*
height = getint(type);
if (tag == 0xfa16)
raw_width = get2();
if (tag == 0xfa17)
raw_height = get2();
*/
if (tag == 0xfa18)
{
imgdata.makernotes.kodak.offset_left = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_left += 1;
}
if (tag == 0xfa19)
{
imgdata.makernotes.kodak.offset_top = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_top += 1;
}
if (tag == 0xfa31)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 0xfa32)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 0xfa3e)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 0xfa3f)
imgdata.sizes.raw_crop.ctop = get2();
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
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 && savepos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), 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:
if (len == 3)
{
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
else if (len == 1)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here??
}
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;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 10:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_bpp = get2();
}
break;
#endif
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;
case 0x0120:
if (pana_raw)
{
unsigned sorder = order;
unsigned long sbase = base;
base = ftell(ifp);
order = get2();
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, get4()-8, SEEK_CUR);
parse_tiff_ifd (base);
base = sbase;
order = sorder;
}
break;
case 0x2009:
if ((libraw_internal_data.unpacker_data.pana_encoding == 4) ||
(libraw_internal_data.unpacker_data.pana_encoding == 5))
{
int n = MIN (8, len);
int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4};
imgdata.makernotes.panasonic.BlackLevelDim = len;
for (int i=0; i < n; i++)
{
imgdata.makernotes.panasonic.BlackLevel[permut[i]] =
(float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp));
}
}
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;
#ifdef LIBRAW_LIBRARY_BUILD
case 45:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_encoding = get2();
}
break;
#endif
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 */
if ((pana_raw) && (tag == 11) && (type == 3))
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.makernotes.panasonic.Compression = get2();
#endif
break;
}
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++)
{
if(cfa_pat[i] > 31) continue; // Skip wrong data
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4
{
int q = get2();
if(q > 0) cam_mul[c ^ 1] = 4096.0 / q;
}
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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);
if(len>0)
{
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 */
{
float q1 = getreal(type);
float q2 = getreal(type);
if(q1 > 0.00001f && q2 > 0.00001f)
{
pixel_aspect = q1/q2;
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0];
imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1];
}
}
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2];
imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3];
}
}
break;
case 0x74c7:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cleft = get4();
imgdata.makernotes.sony.raw_crop.ctop = get4();
}
break;
case 0x74c8:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cwidth = get4();
imgdata.makernotes.sony.raw_crop.cheight = get4();
}
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;
INT64 save_pos = ifp->tell();
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
curr_pos = save_pos + MakN_length - 6;
fseek(ifp, curr_pos, SEEK_SET);
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "SR2 ", 4))
{
order = 0x4d4d;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
unsigned *buf_SR2;
uchar *cbuf_SR2;
unsigned icbuf_SR2;
unsigned entries, tag, type, len, save;
int ival;
unsigned SR2SubIFDOffset = 0;
unsigned SR2SubIFDLength = 0;
unsigned SR2SubIFDKey = 0;
int base = curr_pos + 6 - pos_in_original_raw;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 0x7200)
{
SR2SubIFDOffset = get4();
}
else if (tag == 0x7201)
{
SR2SubIFDLength = get4();
}
else if (tag == 0x7221)
{
SR2SubIFDKey = get4();
}
fseek(ifp, save, SEEK_SET);
}
if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety
{
fseek(ifp, SR2SubIFDOffset + base, SEEK_SET);
fread(buf_SR2, SR2SubIFDLength, 1, ifp);
sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey);
cbuf_SR2 = (uchar *)buf_SR2;
entries = sget2(cbuf_SR2);
icbuf_SR2 = 2;
while (entries--)
{
tag = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
type = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
len = sget4(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 4;
if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4)
{
ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset;
}
else
{
ival = icbuf_SR2;
}
if(ival > SR2SubIFDLength) // points out of orig. buffer size
break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter
icbuf_SR2 += 4;
switch (tag)
{
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c);
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] =
sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
}
}
free(buf_SR2);
}
} /* SR2 processed */
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
if(fabs(asn[c])>0.0001)
cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC if(fabs(cc[c][c])>0.0001) 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( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535
|| tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535)
continue; /* wrong image dimensions */
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:
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height))
#else
if (tiff_ifd[raw].bytes == raw_width * raw_height)
#endif
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
#else
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
#endif
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps))
#else
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
#endif
{
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) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 &&
INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ
{
tiff_bps = 14;
tiff_samples = 4;
load_raw = &CLASS sony_arq_load_raw;
filters = 0;
strcpy(cdesc, "RGBG");
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL)
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
#endif
load_flags = 24;
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL)
#else
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
#endif
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height))
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
#endif
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:
#ifdef LIBRAW_LIBRARY_BUILD
if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes))
#else
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
#endif
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
{
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 (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL)
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(offset>ifp->size()-8) // At least 8 bytes for tag/len
offset = ifp->size()-8;
#endif
while ((save = ftell(ifp)) < offset)
{
for (tag = i = 0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
if(len < 0)
return; // just ignore wrong len?? or raise bad file exception?
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 = libraw_powf64l(2.0f, -int_to_float((get4(), get4())));
aperture = libraw_powf64l(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 = libraw_powf64l(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 = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = libraw_powf64l(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
{
ushort q = get2();
cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024;
}
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
unique_id = setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0211:
imgdata.other.SensorTemperature2 = int_to_float(data);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.SensorTemperature = ph1.tag_210;
#endif
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED;
#endif
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/
}
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x110)
{
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cleft = get2();
}
else if (tag == 0x111)
{
imgdata.sizes.raw_crop.cheight = get2();
imgdata.sizes.raw_crop.cwidth = get2();
}
else if ((tag == 0x122) && !strcmp(model, "DBP for GX680"))
{
int k = get2();
int l = get2(); /* margins? */
int m = get2(); /* margins? */
int n = get2();
// printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n);
}
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") ||
!strcmp(model, "X-A5") ||
!strcmp(model, "X-A20"))
{
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();
}
}
/*
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,
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82,
{7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M100", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark III", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A20", 0, 0, /* temp */
{ 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-A5", 0, 0, /* temp */
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-E3", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-H1", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D850", 0, 0,
{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL9", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-G9", -15, 0,
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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-GH5s", -15, 0,
{ 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } },
{ "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-GF10", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "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 DC-GX9", -15, 0, /* temp */
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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 } },
{ "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// {3984,0,0,0,10000,0,0,0,7666}},
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
// {2423,0,0,0,9901,0,0,0,7989}},
{ 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10M4", -800, 0,
{ 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{"Sony DSC-RX0", -800, 0, /* temp */
{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 16596,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 16596,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A550", 0, 16596,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */
{ 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-7M3", 0, 0,
{ 7374,-2389,-551,-5435,13162,2519,-1006,1795,6552 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM3", 0, 0,
{ 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } },
{ "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};
if(width > 2064) return 0.f; // too wide
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((unsigned char)string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x398, "EOS M100"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16b, "ILCE-7M3"}, {0x16c, "DSC-RX0"},
{0x16d, "DSC-RX10M4"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 =
imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature =
imgdata.other.exifAmbientTemperature = -1000.0f;
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT;
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 = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = libraw_powf64l(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 = libraw_powf64l(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
strncpy(model, head + 0x1c,0x20);
model[0x20]=0;
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4(); // bytes count
width = get2();
height = get2();
#ifdef LIBRAW_LIBRARY_BUILD
// Data integrity check
if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height))
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
/* no foveon support for dcraw build from libraw source */
parse_x3f();
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
break;
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
memmove(model, model + 8,strlen(model)-7);
if (!strncmp(model, "Digital Camera ", 15))
memmove(model, model + 15,strlen(model)-14);
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] * 0x01010101U;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c, A6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
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 = 0x01010101U * (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
/* alloc in unpack() may be fooled by size adjust */
|| ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535))
{
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 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&
tiff_ifd[sidx].dng_levels.default_crop[3] > 0)
{
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
}
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;
}
void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val)
{
struct libraw_tiff_tag *tt;
int c;
tt = (struct libraw_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(×tamp);
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);
}
| ./CrossVul/dataset_final_sorted/CWE-835/cpp/good_581_1 |
crossvul-cpp_data_good_1367_0 | // ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2018 Exiv2 authors
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
// *****************************************************************************
// included header files
#include "config.h"
#include "jp2image.hpp"
#include "tiffimage.hpp"
#include "image.hpp"
#include "image_int.hpp"
#include "basicio.hpp"
#include "error.hpp"
#include "futils.hpp"
#include "types.hpp"
#include "safe_op.hpp"
// + standard includes
#include <string>
#include <cstring>
#include <iostream>
#include <cassert>
#include <cstdio>
// JPEG-2000 box types
const uint32_t kJp2BoxTypeJp2Header = 0x6a703268; // 'jp2h'
const uint32_t kJp2BoxTypeImageHeader = 0x69686472; // 'ihdr'
const uint32_t kJp2BoxTypeColorHeader = 0x636f6c72; // 'colr'
const uint32_t kJp2BoxTypeUuid = 0x75756964; // 'uuid'
const uint32_t kJp2BoxTypeClose = 0x6a703263; // 'jp2c'
// from openjpeg-2.1.2/src/lib/openjp2/jp2.h
/*#define JPIP_JPIP 0x6a706970*/
#define JP2_JP 0x6a502020 /**< JPEG 2000 signature box */
#define JP2_FTYP 0x66747970 /**< File type box */
#define JP2_JP2H 0x6a703268 /**< JP2 header box (super-box) */
#define JP2_IHDR 0x69686472 /**< Image header box */
#define JP2_COLR 0x636f6c72 /**< Colour specification box */
#define JP2_JP2C 0x6a703263 /**< Contiguous codestream box */
#define JP2_URL 0x75726c20 /**< Data entry URL box */
#define JP2_PCLR 0x70636c72 /**< Palette box */
#define JP2_CMAP 0x636d6170 /**< Component Mapping box */
#define JP2_CDEF 0x63646566 /**< Channel Definition box */
#define JP2_DTBL 0x6474626c /**< Data Reference box */
#define JP2_BPCC 0x62706363 /**< Bits per component box */
#define JP2_JP2 0x6a703220 /**< File type fields */
/* For the future */
/* #define JP2_RES 0x72657320 */ /**< Resolution box (super-box) */
/* #define JP2_JP2I 0x6a703269 */ /**< Intellectual property box */
/* #define JP2_XML 0x786d6c20 */ /**< XML box */
/* #define JP2_UUID 0x75756994 */ /**< UUID box */
/* #define JP2_UINF 0x75696e66 */ /**< UUID info box (super-box) */
/* #define JP2_ULST 0x756c7374 */ /**< UUID list box */
// JPEG-2000 UUIDs for embedded metadata
//
// See http://www.jpeg.org/public/wg1n2600.doc for information about embedding IPTC-NAA data in JPEG-2000 files
// See http://www.adobe.com/devnet/xmp/pdfs/xmp_specification.pdf for information about embedding XMP data in JPEG-2000 files
const unsigned char kJp2UuidExif[] = "JpgTiffExif->JP2";
const unsigned char kJp2UuidIptc[] = "\x33\xc7\xa4\xd2\xb8\x1d\x47\x23\xa0\xba\xf1\xa3\xe0\x97\xad\x38";
const unsigned char kJp2UuidXmp[] = "\xbe\x7a\xcf\xcb\x97\xa9\x42\xe8\x9c\x71\x99\x94\x91\xe3\xaf\xac";
// See section B.1.1 (JPEG 2000 Signature box) of JPEG-2000 specification
const unsigned char Jp2Signature[12] = { 0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a };
const unsigned char Jp2Blank[] = { 0x00,0x00,0x00,0x0c,0x6a,0x50,0x20,0x20,0x0d,0x0a,0x87,0x0a,0x00,0x00,0x00,0x14,
0x66,0x74,0x79,0x70,0x6a,0x70,0x32,0x20,0x00,0x00,0x00,0x00,0x6a,0x70,0x32,0x20,
0x00,0x00,0x00,0x2d,0x6a,0x70,0x32,0x68,0x00,0x00,0x00,0x16,0x69,0x68,0x64,0x72,
0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x01,0x07,0x07,0x00,0x00,0x00,0x00,
0x00,0x0f,0x63,0x6f,0x6c,0x72,0x01,0x00,0x00,0x00,0x00,0x00,0x11,0x00,0x00,0x00,
0x00,0x6a,0x70,0x32,0x63,0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,
0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,
0x01,0x01,0xff,0x64,0x00,0x23,0x00,0x01,0x43,0x72,0x65,0x61,0x74,0x6f,0x72,0x3a,
0x20,0x4a,0x61,0x73,0x50,0x65,0x72,0x20,0x56,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,
0x31,0x2e,0x39,0x30,0x30,0x2e,0x31,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,
0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,
0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x90,0x00,0x0a,0x00,0x00,
0x00,0x00,0x00,0x2d,0x00,0x01,0xff,0x5d,0x00,0x14,0x00,0x40,0x40,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x93,0xcf,0xb4,
0x04,0x00,0x80,0x80,0x80,0x80,0x80,0xff,0xd9
};
//! @cond IGNORE
struct Jp2BoxHeader
{
uint32_t length;
uint32_t type;
};
struct Jp2ImageHeaderBox
{
uint32_t imageHeight;
uint32_t imageWidth;
uint16_t componentCount;
uint8_t bitsPerComponent;
uint8_t compressionType;
uint8_t colorspaceIsUnknown;
uint8_t intellectualPropertyFlag;
uint16_t compressionTypeProfile;
};
struct Jp2UuidBox
{
uint8_t uuid[16];
};
//! @endcond
// *****************************************************************************
// class member definitions
namespace Exiv2
{
Jp2Image::Jp2Image(BasicIo::AutoPtr io, bool create)
: Image(ImageType::jp2, mdExif | mdIptc | mdXmp, io)
{
if (create)
{
if (io_->open() == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image:: Creating JPEG2000 image to memory" << std::endl;
#endif
IoCloser closer(*io_);
if (io_->write(Jp2Blank, sizeof(Jp2Blank)) != sizeof(Jp2Blank))
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image:: Failed to create JPEG2000 image on memory" << std::endl;
#endif
}
}
}
} // Jp2Image::Jp2Image
std::string Jp2Image::mimeType() const
{
return "image/jp2";
}
void Jp2Image::setComment(const std::string& /*comment*/)
{
// Todo: implement me!
throw(Error(kerInvalidSettingForImage, "Image comment", "JP2"));
} // Jp2Image::setComment
static void lf(std::ostream& out,bool& bLF)
{
if ( bLF ) {
out << std::endl;
out.flush();
bLF = false ;
}
}
static bool isBigEndian()
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0]?true:false;
}
static std::string toAscii(long n)
{
const char* p = (const char*) &n;
std::string result;
bool bBigEndian = isBigEndian();
for ( int i = 0 ; i < 4 ; i++) {
result += p[ bBigEndian ? i : (3-i) ];
}
return result;
}
static void boxes_check(size_t b,size_t m)
{
if ( b > m ) {
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata box maximum exceeded" << std::endl;
#endif
throw Error(kerCorruptedMetadata);
}
}
void Jp2Image::readMetadata()
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image::readMetadata: Reading JPEG-2000 file " << io_->path() << std::endl;
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isJp2Type(*io_, true))
{
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAnImage, "JPEG-2000");
}
long position = 0;
Jp2BoxHeader box = {0,0};
Jp2BoxHeader subBox = {0,0};
Jp2ImageHeaderBox ihdr = {0,0,0,0,0,0,0,0};
Jp2UuidBox uuid = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
size_t boxes = 0 ;
size_t boxem = 1000 ; // boxes max
while (io_->read((byte*)&box, sizeof(box)) == sizeof(box))
{
boxes_check(boxes++,boxem );
position = io_->tell();
box.length = getLong((byte*)&box.length, bigEndian);
box.type = getLong((byte*)&box.type, bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "Position: " << position
<< " box type: " << toAscii(box.type)
<< " length: " << box.length
<< std::endl;
#endif
if (box.length == 0) return ;
if (box.length == 1)
{
// FIXME. Special case. the real box size is given in another place.
}
switch(box.type)
{
case kJp2BoxTypeJp2Header:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: JP2Header box found" << std::endl;
#endif
long restore = io_->tell();
while (io_->read((byte*)&subBox, sizeof(subBox)) == sizeof(subBox) && subBox.length )
{
boxes_check(boxes++, boxem) ;
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type, bigEndian);
if (subBox.length > io_->size() ) {
throw Error(kerCorruptedMetadata);
}
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "subBox = " << toAscii(subBox.type) << " length = " << subBox.length << std::endl;
#endif
if(subBox.type == kJp2BoxTypeColorHeader && subBox.length != 15)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "Color data found" << std::endl;
#endif
const long pad = 3 ; // 3 padding bytes 2 0 0
const size_t data_length = Safe::add(subBox.length, static_cast<uint32_t>(8));
// data_length makes no sense if it is larger than the rest of the file
if (data_length > io_->size() - io_->tell()) {
throw Error(kerCorruptedMetadata);
}
DataBuf data(static_cast<long>(data_length));
io_->read(data.pData_,data.size_);
const long iccLength = getULong(data.pData_+pad, bigEndian);
// subtracting pad from data.size_ is safe:
// size_ is at least 8 and pad = 3
if (iccLength > data.size_ - pad) {
throw Error(kerCorruptedMetadata);
}
DataBuf icc(iccLength);
::memcpy(icc.pData_,data.pData_+pad,icc.size_);
#ifdef EXIV2_DEBUG_MESSAGES
const char* iccPath = "/tmp/libexiv2_jp2.icc";
FILE* f = fopen(iccPath,"wb");
if ( f ) {
fwrite(icc.pData_,icc.size_,1,f);
fclose(f);
}
std::cout << "Exiv2::Jp2Image::readMetadata: wrote iccProfile " << icc.size_<< " bytes to " << iccPath << std::endl ;
#endif
setIccProfile(icc);
}
if( subBox.type == kJp2BoxTypeImageHeader)
{
io_->read((byte*)&ihdr, sizeof(ihdr));
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Ihdr data found" << std::endl;
#endif
ihdr.imageHeight = getLong((byte*)&ihdr.imageHeight, bigEndian);
ihdr.imageWidth = getLong((byte*)&ihdr.imageWidth, bigEndian);
ihdr.componentCount = getShort((byte*)&ihdr.componentCount, bigEndian);
ihdr.compressionTypeProfile = getShort((byte*)&ihdr.compressionTypeProfile, bigEndian);
pixelWidth_ = ihdr.imageWidth;
pixelHeight_ = ihdr.imageHeight;
}
io_->seek(restore,BasicIo::beg);
if ( io_->seek(subBox.length, Exiv2::BasicIo::cur) != 0 ) {
throw Error(kerCorruptedMetadata);
}
restore = io_->tell();
}
break;
}
case kJp2BoxTypeUuid:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: UUID box found" << std::endl;
#endif
if (io_->read((byte*)&uuid, sizeof(uuid)) == sizeof(uuid))
{
DataBuf rawData;
long bufRead;
bool bIsExif = memcmp(uuid.uuid, kJp2UuidExif, sizeof(uuid))==0;
bool bIsIPTC = memcmp(uuid.uuid, kJp2UuidIptc, sizeof(uuid))==0;
bool bIsXMP = memcmp(uuid.uuid, kJp2UuidXmp , sizeof(uuid))==0;
if(bIsExif)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Exif data found" << std::endl ;
#endif
rawData.alloc(box.length - (sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
if (rawData.size_ > 0)
{
// Find the position of Exif header in bytes array.
long pos = ( (rawData.pData_[0] == rawData.pData_[1])
&& (rawData.pData_[0]=='I' || rawData.pData_[0]=='M')
) ? 0 : -1;
// #1242 Forgive having Exif\0\0 in rawData.pData_
const byte exifHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 };
for (long i=0 ; pos < 0 && i < rawData.size_-(long)sizeof(exifHeader) ; i++)
{
if (memcmp(exifHeader, &rawData.pData_[i], sizeof(exifHeader)) == 0)
{
pos = i+sizeof(exifHeader);
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Reading non-standard UUID-EXIF_bad box in " << io_->path() << std::endl;
#endif
}
}
// If found it, store only these data at from this place.
if (pos >= 0 )
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Exif header found at position " << pos << std::endl;
#endif
ByteOrder bo = TiffParser::decode(exifData(),
iptcData(),
xmpData(),
rawData.pData_ + pos,
rawData.size_ - pos);
setByteOrder(bo);
}
}
else
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode Exif metadata." << std::endl;
#endif
exifData_.clear();
}
}
if(bIsIPTC)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Iptc data found" << std::endl;
#endif
rawData.alloc(box.length - (sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
if (IptcParser::decode(iptcData_, rawData.pData_, rawData.size_))
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode IPTC metadata." << std::endl;
#endif
iptcData_.clear();
}
}
if(bIsXMP)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Xmp data found" << std::endl;
#endif
rawData.alloc(box.length - (uint32_t)(sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
xmpPacket_.assign(reinterpret_cast<char *>(rawData.pData_), rawData.size_);
std::string::size_type idx = xmpPacket_.find_first_of('<');
if (idx != std::string::npos && idx > 0)
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Removing " << static_cast<uint32_t>(idx)
<< " characters from the beginning of the XMP packet" << std::endl;
#endif
xmpPacket_ = xmpPacket_.substr(idx);
}
if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_))
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode XMP metadata." << std::endl;
#endif
}
}
}
break;
}
default:
{
break;
}
}
// Move to the next box.
io_->seek(static_cast<long>(position - sizeof(box) + box.length), BasicIo::beg);
if (io_->error()) throw Error(kerFailedToReadImageData);
}
} // Jp2Image::readMetadata
void Jp2Image::printStructure(std::ostream& out, PrintStructureOption option, int depth)
{
if (io_->open() != 0)
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
// Ensure that this is the correct image type
if (!isJp2Type(*io_, false)) {
if (io_->error() || io_->eof())
throw Error(kerFailedToReadImageData);
throw Error(kerNotAJpeg);
}
bool bPrint = option == kpsBasic || option == kpsRecursive;
bool bRecursive = option == kpsRecursive;
bool bICC = option == kpsIccProfile;
bool bXMP = option == kpsXMP;
bool bIPTCErase = option == kpsIptcErase;
if (bPrint) {
out << "STRUCTURE OF JPEG2000 FILE: " << io_->path() << std::endl;
out << " address | length | box | data" << std::endl;
}
if ( bPrint || bXMP || bICC || bIPTCErase ) {
long position = 0;
Jp2BoxHeader box = {1,1};
Jp2BoxHeader subBox = {1,1};
Jp2UuidBox uuid = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
bool bLF = false;
while (box.length && box.type != kJp2BoxTypeClose && io_->read((byte*)&box, sizeof(box)) == sizeof(box))
{
position = io_->tell();
box.length = getLong((byte*)&box.length, bigEndian);
box.type = getLong((byte*)&box.type, bigEndian);
if (bPrint) {
out << Internal::stringFormat("%8ld | %8ld | ", (size_t)(position - sizeof(box)),
(size_t)box.length)
<< toAscii(box.type) << " | ";
bLF = true;
if (box.type == kJp2BoxTypeClose)
lf(out, bLF);
}
if (box.type == kJp2BoxTypeClose)
break;
switch (box.type) {
case kJp2BoxTypeJp2Header: {
lf(out, bLF);
while (io_->read((byte*)&subBox, sizeof(subBox)) == sizeof(subBox) &&
io_->tell() < position + (long)box.length) // don't read beyond the box!
{
int address = io_->tell() - sizeof(subBox);
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type, bigEndian);
if (subBox.length < sizeof(box) || subBox.length > io_->size() - io_->tell()) {
throw Error(kerCorruptedMetadata);
}
DataBuf data(subBox.length - sizeof(box));
io_->read(data.pData_, data.size_);
if (bPrint) {
out << Internal::stringFormat("%8ld | %8ld | sub:", (size_t)address,
(size_t)subBox.length)
<< toAscii(subBox.type) << " | "
<< Internal::binaryToString(makeSlice(data, 0, std::min(30l, data.size_)));
bLF = true;
}
if (subBox.type == kJp2BoxTypeColorHeader) {
long pad = 3; // don't know why there are 3 padding bytes
if (bPrint) {
out << " | pad:";
for (int i = 0; i < 3; i++)
out << " " << (int)data.pData_[i];
}
long iccLength = getULong(data.pData_ + pad, bigEndian);
if (bPrint) {
out << " | iccLength:" << iccLength;
}
if (bICC) {
out.write((const char*)data.pData_ + pad, iccLength);
}
}
lf(out, bLF);
}
} break;
case kJp2BoxTypeUuid: {
if (io_->read((byte*)&uuid, sizeof(uuid)) == sizeof(uuid)) {
bool bIsExif = memcmp(uuid.uuid, kJp2UuidExif, sizeof(uuid)) == 0;
bool bIsIPTC = memcmp(uuid.uuid, kJp2UuidIptc, sizeof(uuid)) == 0;
bool bIsXMP = memcmp(uuid.uuid, kJp2UuidXmp, sizeof(uuid)) == 0;
bool bUnknown = !(bIsExif || bIsIPTC || bIsXMP);
if (bPrint) {
if (bIsExif)
out << "Exif: ";
if (bIsIPTC)
out << "IPTC: ";
if (bIsXMP)
out << "XMP : ";
if (bUnknown)
out << "????: ";
}
DataBuf rawData;
rawData.alloc(box.length - sizeof(uuid) - sizeof(box));
long bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error())
throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_)
throw Error(kerInputDataReadFailed);
if (bPrint) {
out << Internal::binaryToString(makeSlice(rawData, 0, 40));
out.flush();
}
lf(out, bLF);
if (bIsExif && bRecursive && rawData.size_ > 0) {
if ((rawData.pData_[0] == rawData.pData_[1]) &&
(rawData.pData_[0] == 'I' || rawData.pData_[0] == 'M')) {
BasicIo::AutoPtr p = BasicIo::AutoPtr(new MemIo(rawData.pData_, rawData.size_));
printTiffStructure(*p, out, option, depth);
}
}
if (bIsIPTC && bRecursive) {
IptcData::printStructure(out, makeSlice(rawData.pData_, 0, rawData.size_), depth);
}
if (bIsXMP && bXMP) {
out.write((const char*)rawData.pData_, rawData.size_);
}
}
} break;
default:
break;
}
// Move to the next box.
io_->seek(static_cast<long>(position - sizeof(box) + box.length), BasicIo::beg);
if (io_->error())
throw Error(kerFailedToReadImageData);
if (bPrint)
lf(out, bLF);
}
}
} // JpegBase::printStructure
void Jp2Image::writeMetadata()
{
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
BasicIo::AutoPtr tempIo(new MemIo);
assert (tempIo.get() != 0);
doWriteMetadata(*tempIo); // may throw
io_->close();
io_->transfer(*tempIo); // may throw
} // Jp2Image::writeMetadata
#ifdef __clang__
// ignore cast align errors. dataBuf.pData_ is allocated by malloc() and 4 (or 8 byte aligned).
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
#endif
void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)
{
DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space
int outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?
int inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?
Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;
int32_t length = getLong((byte*)&pBox->length, bigEndian);
int32_t count = sizeof (Jp2BoxHeader);
char* p = (char*) boxBuf.pData_;
bool bWroteColor = false ;
while ( count < length || !bWroteColor ) {
Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;
// copy data. pointer could be into a memory mapped file which we will decode!
Jp2BoxHeader subBox = *pSubBox ;
Jp2BoxHeader newBox = subBox;
if ( count < length ) {
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type , bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Jp2Image::encodeJp2Header subbox: "<< toAscii(subBox.type) << " length = " << subBox.length << std::endl;
#endif
count += subBox.length;
newBox.type = subBox.type;
} else {
subBox.length=0;
newBox.type = kJp2BoxTypeColorHeader;
count = length;
}
int32_t newlen = subBox.length;
if ( newBox.type == kJp2BoxTypeColorHeader ) {
bWroteColor = true ;
if ( ! iccProfileDefined() ) {
const char* pad = "\x01\x00\x00\x00\x00\x00\x10\x00\x00\x05\x1cuuid";
uint32_t psize = 15;
ul2Data((byte*)&newBox.length,psize ,bigEndian);
ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);
::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));
::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );
newlen = psize ;
} else {
const char* pad = "\0x02\x00\x00";
uint32_t psize = 3;
ul2Data((byte*)&newBox.length,psize+iccProfile_.size_,bigEndian);
ul2Data((byte*)&newBox.type,newBox.type,bigEndian);
::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );
::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );
::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);
newlen = psize + iccProfile_.size_;
}
} else {
::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);
}
outlen += newlen;
inlen += subBox.length;
}
// allocate the correct number of bytes, copy the data and update the box header
outBuf.alloc(outlen);
::memcpy(outBuf.pData_,output.pData_,outlen);
pBox = (Jp2BoxHeader*) outBuf.pData_;
ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);
ul2Data((byte*)&pBox->length,outlen,bigEndian);
} // Jp2Image::encodeJp2Header
#ifdef __clang__
#pragma clang diagnostic pop
#endif
void Jp2Image::doWriteMetadata(BasicIo& outIo)
{
if (!io_->isopen()) throw Error(kerInputDataReadFailed);
if (!outIo.isopen()) throw Error(kerImageWriteFailed);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Writing JPEG-2000 file " << io_->path() << std::endl;
std::cout << "Exiv2::Jp2Image::doWriteMetadata: tmp file created " << outIo.path() << std::endl;
#endif
// Ensure that this is the correct image type
if (!isJp2Type(*io_, true))
{
if (io_->error() || io_->eof()) throw Error(kerInputDataReadFailed);
throw Error(kerNoImageInInputData);
}
// Write JPEG2000 Signature.
if (outIo.write(Jp2Signature, 12) != 12) throw Error(kerImageWriteFailed);
Jp2BoxHeader box = {0,0};
byte boxDataSize[4];
byte boxUUIDtype[4];
DataBuf bheaderBuf(8); // Box header : 4 bytes (data size) + 4 bytes (box type).
// FIXME: Andreas, why the loop do not stop when EOF is taken from _io. The loop go out by an exception
// generated by a zero size data read.
while(io_->tell() < (long) io_->size())
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Position: " << io_->tell() << " / " << io_->size() << std::endl;
#endif
// Read chunk header.
std::memset(bheaderBuf.pData_, 0x00, bheaderBuf.size_);
long bufRead = io_->read(bheaderBuf.pData_, bheaderBuf.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != bheaderBuf.size_) throw Error(kerInputDataReadFailed);
// Decode box header.
box.length = getLong(bheaderBuf.pData_, bigEndian);
box.type = getLong(bheaderBuf.pData_ + 4, bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: box type: " << toAscii(box.type)
<< " length: " << box.length << std::endl;
#endif
if (box.length == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Null Box size has been found. "
"This is the last box of file." << std::endl;
#endif
box.length = (uint32_t) (io_->size() - io_->tell() + 8);
}
if (box.length == 1)
{
// FIXME. Special case. the real box size is given in another place.
}
// Read whole box : Box header + Box data (not fixed size - can be null).
DataBuf boxBuf(box.length); // Box header (8 bytes) + box data.
memcpy(boxBuf.pData_, bheaderBuf.pData_, 8); // Copy header.
bufRead = io_->read(boxBuf.pData_ + 8, box.length - 8); // Extract box data.
if (io_->error())
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Error reading source file" << std::endl;
#endif
throw Error(kerFailedToReadImageData);
}
if (bufRead != (long)(box.length - 8))
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Cannot read source file data" << std::endl;
#endif
throw Error(kerInputDataReadFailed);
}
switch(box.type)
{
case kJp2BoxTypeJp2Header:
{
DataBuf newBuf;
encodeJp2Header(boxBuf,newBuf);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write JP2Header box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(newBuf.pData_, newBuf.size_) != newBuf.size_) throw Error(kerImageWriteFailed);
// Write all updated metadata here, just after JP2Header.
if (exifData_.count() > 0)
{
// Update Exif data to a new UUID box
Blob blob;
ExifParser::encode(blob, littleEndian, exifData_);
if (blob.size())
{
DataBuf rawExif(static_cast<long>(blob.size()));
memcpy(rawExif.pData_, &blob[0], blob.size());
DataBuf boxData(8 + 16 + rawExif.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidExif, 16);
memcpy(boxData.pData_ + 8 + 16, rawExif.pData_, rawExif.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Exif metadata (length: "
<< boxData.size_ << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
}
if (iptcData_.count() > 0)
{
// Update Iptc data to a new UUID box
DataBuf rawIptc = IptcParser::encode(iptcData_);
if (rawIptc.size_ > 0)
{
DataBuf boxData(8 + 16 + rawIptc.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidIptc, 16);
memcpy(boxData.pData_ + 8 + 16, rawIptc.pData_, rawIptc.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Iptc metadata (length: "
<< boxData.size_ << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
}
if (writeXmpFromPacket() == false)
{
if (XmpParser::encode(xmpPacket_, xmpData_) > 1)
{
#ifndef SUPPRESS_WARNINGS
EXV_ERROR << "Failed to encode XMP metadata." << std::endl;
#endif
}
}
if (xmpPacket_.size() > 0)
{
// Update Xmp data to a new UUID box
DataBuf xmp(reinterpret_cast<const byte*>(xmpPacket_.data()), static_cast<long>(xmpPacket_.size()));
DataBuf boxData(8 + 16 + xmp.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidXmp, 16);
memcpy(boxData.pData_ + 8 + 16, xmp.pData_, xmp.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with XMP metadata (length: "
<< boxData.size_ << ")" << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
break;
}
case kJp2BoxTypeUuid:
{
if(memcmp(boxBuf.pData_ + 8, kJp2UuidExif, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Exif Uuid box" << std::endl;
#endif
}
else if(memcmp(boxBuf.pData_ + 8, kJp2UuidIptc, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Iptc Uuid box" << std::endl;
#endif
}
else if(memcmp(boxBuf.pData_ + 8, kJp2UuidXmp, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Xmp Uuid box" << std::endl;
#endif
}
else
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: write Uuid box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);
}
break;
}
default:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: write box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);
break;
}
}
}
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: EOF" << std::endl;
#endif
} // Jp2Image::doWriteMetadata
// *************************************************************************
// free functions
Image::AutoPtr newJp2Instance(BasicIo::AutoPtr io, bool create)
{
Image::AutoPtr image(new Jp2Image(io, create));
if (!image->good())
{
image.reset();
}
return image;
}
bool isJp2Type(BasicIo& iIo, bool advance)
{
const int32_t len = 12;
byte buf[len];
iIo.read(buf, len);
if (iIo.error() || iIo.eof())
{
return false;
}
bool matched = (memcmp(buf, Jp2Signature, len) == 0);
if (!advance || !matched)
{
iIo.seek(-len, BasicIo::cur);
}
return matched;
}
} // namespace Exiv2
| ./CrossVul/dataset_final_sorted/CWE-835/cpp/good_1367_0 |
crossvul-cpp_data_bad_1367_0 | // ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2018 Exiv2 authors
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*
File: jp2image.cpp
*/
// *****************************************************************************
// included header files
#include "config.h"
#include "jp2image.hpp"
#include "tiffimage.hpp"
#include "image.hpp"
#include "image_int.hpp"
#include "basicio.hpp"
#include "error.hpp"
#include "futils.hpp"
#include "types.hpp"
#include "safe_op.hpp"
// + standard includes
#include <string>
#include <cstring>
#include <iostream>
#include <cassert>
#include <cstdio>
// JPEG-2000 box types
const uint32_t kJp2BoxTypeJp2Header = 0x6a703268; // 'jp2h'
const uint32_t kJp2BoxTypeImageHeader = 0x69686472; // 'ihdr'
const uint32_t kJp2BoxTypeColorHeader = 0x636f6c72; // 'colr'
const uint32_t kJp2BoxTypeUuid = 0x75756964; // 'uuid'
const uint32_t kJp2BoxTypeClose = 0x6a703263; // 'jp2c'
// from openjpeg-2.1.2/src/lib/openjp2/jp2.h
/*#define JPIP_JPIP 0x6a706970*/
#define JP2_JP 0x6a502020 /**< JPEG 2000 signature box */
#define JP2_FTYP 0x66747970 /**< File type box */
#define JP2_JP2H 0x6a703268 /**< JP2 header box (super-box) */
#define JP2_IHDR 0x69686472 /**< Image header box */
#define JP2_COLR 0x636f6c72 /**< Colour specification box */
#define JP2_JP2C 0x6a703263 /**< Contiguous codestream box */
#define JP2_URL 0x75726c20 /**< Data entry URL box */
#define JP2_PCLR 0x70636c72 /**< Palette box */
#define JP2_CMAP 0x636d6170 /**< Component Mapping box */
#define JP2_CDEF 0x63646566 /**< Channel Definition box */
#define JP2_DTBL 0x6474626c /**< Data Reference box */
#define JP2_BPCC 0x62706363 /**< Bits per component box */
#define JP2_JP2 0x6a703220 /**< File type fields */
/* For the future */
/* #define JP2_RES 0x72657320 */ /**< Resolution box (super-box) */
/* #define JP2_JP2I 0x6a703269 */ /**< Intellectual property box */
/* #define JP2_XML 0x786d6c20 */ /**< XML box */
/* #define JP2_UUID 0x75756994 */ /**< UUID box */
/* #define JP2_UINF 0x75696e66 */ /**< UUID info box (super-box) */
/* #define JP2_ULST 0x756c7374 */ /**< UUID list box */
// JPEG-2000 UUIDs for embedded metadata
//
// See http://www.jpeg.org/public/wg1n2600.doc for information about embedding IPTC-NAA data in JPEG-2000 files
// See http://www.adobe.com/devnet/xmp/pdfs/xmp_specification.pdf for information about embedding XMP data in JPEG-2000 files
const unsigned char kJp2UuidExif[] = "JpgTiffExif->JP2";
const unsigned char kJp2UuidIptc[] = "\x33\xc7\xa4\xd2\xb8\x1d\x47\x23\xa0\xba\xf1\xa3\xe0\x97\xad\x38";
const unsigned char kJp2UuidXmp[] = "\xbe\x7a\xcf\xcb\x97\xa9\x42\xe8\x9c\x71\x99\x94\x91\xe3\xaf\xac";
// See section B.1.1 (JPEG 2000 Signature box) of JPEG-2000 specification
const unsigned char Jp2Signature[12] = { 0x00, 0x00, 0x00, 0x0c, 0x6a, 0x50, 0x20, 0x20, 0x0d, 0x0a, 0x87, 0x0a };
const unsigned char Jp2Blank[] = { 0x00,0x00,0x00,0x0c,0x6a,0x50,0x20,0x20,0x0d,0x0a,0x87,0x0a,0x00,0x00,0x00,0x14,
0x66,0x74,0x79,0x70,0x6a,0x70,0x32,0x20,0x00,0x00,0x00,0x00,0x6a,0x70,0x32,0x20,
0x00,0x00,0x00,0x2d,0x6a,0x70,0x32,0x68,0x00,0x00,0x00,0x16,0x69,0x68,0x64,0x72,
0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x01,0x07,0x07,0x00,0x00,0x00,0x00,
0x00,0x0f,0x63,0x6f,0x6c,0x72,0x01,0x00,0x00,0x00,0x00,0x00,0x11,0x00,0x00,0x00,
0x00,0x6a,0x70,0x32,0x63,0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,
0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,
0x01,0x01,0xff,0x64,0x00,0x23,0x00,0x01,0x43,0x72,0x65,0x61,0x74,0x6f,0x72,0x3a,
0x20,0x4a,0x61,0x73,0x50,0x65,0x72,0x20,0x56,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,
0x31,0x2e,0x39,0x30,0x30,0x2e,0x31,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,
0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,
0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x90,0x00,0x0a,0x00,0x00,
0x00,0x00,0x00,0x2d,0x00,0x01,0xff,0x5d,0x00,0x14,0x00,0x40,0x40,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x93,0xcf,0xb4,
0x04,0x00,0x80,0x80,0x80,0x80,0x80,0xff,0xd9
};
//! @cond IGNORE
struct Jp2BoxHeader
{
uint32_t length;
uint32_t type;
};
struct Jp2ImageHeaderBox
{
uint32_t imageHeight;
uint32_t imageWidth;
uint16_t componentCount;
uint8_t bitsPerComponent;
uint8_t compressionType;
uint8_t colorspaceIsUnknown;
uint8_t intellectualPropertyFlag;
uint16_t compressionTypeProfile;
};
struct Jp2UuidBox
{
uint8_t uuid[16];
};
//! @endcond
// *****************************************************************************
// class member definitions
namespace Exiv2
{
Jp2Image::Jp2Image(BasicIo::AutoPtr io, bool create)
: Image(ImageType::jp2, mdExif | mdIptc | mdXmp, io)
{
if (create)
{
if (io_->open() == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image:: Creating JPEG2000 image to memory" << std::endl;
#endif
IoCloser closer(*io_);
if (io_->write(Jp2Blank, sizeof(Jp2Blank)) != sizeof(Jp2Blank))
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image:: Failed to create JPEG2000 image on memory" << std::endl;
#endif
}
}
}
} // Jp2Image::Jp2Image
std::string Jp2Image::mimeType() const
{
return "image/jp2";
}
void Jp2Image::setComment(const std::string& /*comment*/)
{
// Todo: implement me!
throw(Error(kerInvalidSettingForImage, "Image comment", "JP2"));
} // Jp2Image::setComment
static void lf(std::ostream& out,bool& bLF)
{
if ( bLF ) {
out << std::endl;
out.flush();
bLF = false ;
}
}
static bool isBigEndian()
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0]?true:false;
}
static std::string toAscii(long n)
{
const char* p = (const char*) &n;
std::string result;
bool bBigEndian = isBigEndian();
for ( int i = 0 ; i < 4 ; i++) {
result += p[ bBigEndian ? i : (3-i) ];
}
return result;
}
void Jp2Image::readMetadata()
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cerr << "Exiv2::Jp2Image::readMetadata: Reading JPEG-2000 file " << io_->path() << std::endl;
#endif
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
// Ensure that this is the correct image type
if (!isJp2Type(*io_, true))
{
if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
throw Error(kerNotAnImage, "JPEG-2000");
}
long position = 0;
Jp2BoxHeader box = {0,0};
Jp2BoxHeader subBox = {0,0};
Jp2ImageHeaderBox ihdr = {0,0,0,0,0,0,0,0};
Jp2UuidBox uuid = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
while (io_->read((byte*)&box, sizeof(box)) == sizeof(box))
{
position = io_->tell();
box.length = getLong((byte*)&box.length, bigEndian);
box.type = getLong((byte*)&box.type, bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "Position: " << position
<< " box type: " << toAscii(box.type)
<< " length: " << box.length
<< std::endl;
#endif
if (box.length == 0) return ;
if (box.length == 1)
{
// FIXME. Special case. the real box size is given in another place.
}
switch(box.type)
{
case kJp2BoxTypeJp2Header:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: JP2Header box found" << std::endl;
#endif
long restore = io_->tell();
while (io_->read((byte*)&subBox, sizeof(subBox)) == sizeof(subBox) && subBox.length )
{
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type, bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "subBox = " << toAscii(subBox.type) << " length = " << subBox.length << std::endl;
#endif
if(subBox.type == kJp2BoxTypeColorHeader && subBox.length != 15)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: "
<< "Color data found" << std::endl;
#endif
const long pad = 3 ; // 3 padding bytes 2 0 0
const size_t data_length = Safe::add(subBox.length, static_cast<uint32_t>(8));
// data_length makes no sense if it is larger than the rest of the file
if (data_length > io_->size() - io_->tell()) {
throw Error(kerCorruptedMetadata);
}
DataBuf data(static_cast<long>(data_length));
io_->read(data.pData_,data.size_);
const long iccLength = getULong(data.pData_+pad, bigEndian);
// subtracting pad from data.size_ is safe:
// size_ is at least 8 and pad = 3
if (iccLength > data.size_ - pad) {
throw Error(kerCorruptedMetadata);
}
DataBuf icc(iccLength);
::memcpy(icc.pData_,data.pData_+pad,icc.size_);
#ifdef EXIV2_DEBUG_MESSAGES
const char* iccPath = "/tmp/libexiv2_jp2.icc";
FILE* f = fopen(iccPath,"wb");
if ( f ) {
fwrite(icc.pData_,icc.size_,1,f);
fclose(f);
}
std::cout << "Exiv2::Jp2Image::readMetadata: wrote iccProfile " << icc.size_<< " bytes to " << iccPath << std::endl ;
#endif
setIccProfile(icc);
}
if( subBox.type == kJp2BoxTypeImageHeader)
{
io_->read((byte*)&ihdr, sizeof(ihdr));
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Ihdr data found" << std::endl;
#endif
ihdr.imageHeight = getLong((byte*)&ihdr.imageHeight, bigEndian);
ihdr.imageWidth = getLong((byte*)&ihdr.imageWidth, bigEndian);
ihdr.componentCount = getShort((byte*)&ihdr.componentCount, bigEndian);
ihdr.compressionTypeProfile = getShort((byte*)&ihdr.compressionTypeProfile, bigEndian);
pixelWidth_ = ihdr.imageWidth;
pixelHeight_ = ihdr.imageHeight;
}
io_->seek(restore,BasicIo::beg);
io_->seek(subBox.length, Exiv2::BasicIo::cur);
restore = io_->tell();
}
break;
}
case kJp2BoxTypeUuid:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: UUID box found" << std::endl;
#endif
if (io_->read((byte*)&uuid, sizeof(uuid)) == sizeof(uuid))
{
DataBuf rawData;
long bufRead;
bool bIsExif = memcmp(uuid.uuid, kJp2UuidExif, sizeof(uuid))==0;
bool bIsIPTC = memcmp(uuid.uuid, kJp2UuidIptc, sizeof(uuid))==0;
bool bIsXMP = memcmp(uuid.uuid, kJp2UuidXmp , sizeof(uuid))==0;
if(bIsExif)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Exif data found" << std::endl ;
#endif
rawData.alloc(box.length - (sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
if (rawData.size_ > 0)
{
// Find the position of Exif header in bytes array.
long pos = ( (rawData.pData_[0] == rawData.pData_[1])
&& (rawData.pData_[0]=='I' || rawData.pData_[0]=='M')
) ? 0 : -1;
// #1242 Forgive having Exif\0\0 in rawData.pData_
const byte exifHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 };
for (long i=0 ; pos < 0 && i < rawData.size_-(long)sizeof(exifHeader) ; i++)
{
if (memcmp(exifHeader, &rawData.pData_[i], sizeof(exifHeader)) == 0)
{
pos = i+sizeof(exifHeader);
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Reading non-standard UUID-EXIF_bad box in " << io_->path() << std::endl;
#endif
}
}
// If found it, store only these data at from this place.
if (pos >= 0 )
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Exif header found at position " << pos << std::endl;
#endif
ByteOrder bo = TiffParser::decode(exifData(),
iptcData(),
xmpData(),
rawData.pData_ + pos,
rawData.size_ - pos);
setByteOrder(bo);
}
}
else
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode Exif metadata." << std::endl;
#endif
exifData_.clear();
}
}
if(bIsIPTC)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Iptc data found" << std::endl;
#endif
rawData.alloc(box.length - (sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
if (IptcParser::decode(iptcData_, rawData.pData_, rawData.size_))
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode IPTC metadata." << std::endl;
#endif
iptcData_.clear();
}
}
if(bIsXMP)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::readMetadata: Xmp data found" << std::endl;
#endif
rawData.alloc(box.length - (uint32_t)(sizeof(box) + sizeof(uuid)));
bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_) throw Error(kerInputDataReadFailed);
xmpPacket_.assign(reinterpret_cast<char *>(rawData.pData_), rawData.size_);
std::string::size_type idx = xmpPacket_.find_first_of('<');
if (idx != std::string::npos && idx > 0)
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Removing " << static_cast<uint32_t>(idx)
<< " characters from the beginning of the XMP packet" << std::endl;
#endif
xmpPacket_ = xmpPacket_.substr(idx);
}
if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_))
{
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << "Failed to decode XMP metadata." << std::endl;
#endif
}
}
}
break;
}
default:
{
break;
}
}
// Move to the next box.
io_->seek(static_cast<long>(position - sizeof(box) + box.length), BasicIo::beg);
if (io_->error()) throw Error(kerFailedToReadImageData);
}
} // Jp2Image::readMetadata
void Jp2Image::printStructure(std::ostream& out, PrintStructureOption option, int depth)
{
if (io_->open() != 0)
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
// Ensure that this is the correct image type
if (!isJp2Type(*io_, false)) {
if (io_->error() || io_->eof())
throw Error(kerFailedToReadImageData);
throw Error(kerNotAJpeg);
}
bool bPrint = option == kpsBasic || option == kpsRecursive;
bool bRecursive = option == kpsRecursive;
bool bICC = option == kpsIccProfile;
bool bXMP = option == kpsXMP;
bool bIPTCErase = option == kpsIptcErase;
if (bPrint) {
out << "STRUCTURE OF JPEG2000 FILE: " << io_->path() << std::endl;
out << " address | length | box | data" << std::endl;
}
if ( bPrint || bXMP || bICC || bIPTCErase ) {
long position = 0;
Jp2BoxHeader box = {1,1};
Jp2BoxHeader subBox = {1,1};
Jp2UuidBox uuid = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
bool bLF = false;
while (box.length && box.type != kJp2BoxTypeClose && io_->read((byte*)&box, sizeof(box)) == sizeof(box))
{
position = io_->tell();
box.length = getLong((byte*)&box.length, bigEndian);
box.type = getLong((byte*)&box.type, bigEndian);
if (bPrint) {
out << Internal::stringFormat("%8ld | %8ld | ", (size_t)(position - sizeof(box)),
(size_t)box.length)
<< toAscii(box.type) << " | ";
bLF = true;
if (box.type == kJp2BoxTypeClose)
lf(out, bLF);
}
if (box.type == kJp2BoxTypeClose)
break;
switch (box.type) {
case kJp2BoxTypeJp2Header: {
lf(out, bLF);
while (io_->read((byte*)&subBox, sizeof(subBox)) == sizeof(subBox) &&
io_->tell() < position + (long)box.length) // don't read beyond the box!
{
int address = io_->tell() - sizeof(subBox);
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type, bigEndian);
if (subBox.length < sizeof(box) || subBox.length > io_->size() - io_->tell()) {
throw Error(kerCorruptedMetadata);
}
DataBuf data(subBox.length - sizeof(box));
io_->read(data.pData_, data.size_);
if (bPrint) {
out << Internal::stringFormat("%8ld | %8ld | sub:", (size_t)address,
(size_t)subBox.length)
<< toAscii(subBox.type) << " | "
<< Internal::binaryToString(makeSlice(data, 0, std::min(30l, data.size_)));
bLF = true;
}
if (subBox.type == kJp2BoxTypeColorHeader) {
long pad = 3; // don't know why there are 3 padding bytes
if (bPrint) {
out << " | pad:";
for (int i = 0; i < 3; i++)
out << " " << (int)data.pData_[i];
}
long iccLength = getULong(data.pData_ + pad, bigEndian);
if (bPrint) {
out << " | iccLength:" << iccLength;
}
if (bICC) {
out.write((const char*)data.pData_ + pad, iccLength);
}
}
lf(out, bLF);
}
} break;
case kJp2BoxTypeUuid: {
if (io_->read((byte*)&uuid, sizeof(uuid)) == sizeof(uuid)) {
bool bIsExif = memcmp(uuid.uuid, kJp2UuidExif, sizeof(uuid)) == 0;
bool bIsIPTC = memcmp(uuid.uuid, kJp2UuidIptc, sizeof(uuid)) == 0;
bool bIsXMP = memcmp(uuid.uuid, kJp2UuidXmp, sizeof(uuid)) == 0;
bool bUnknown = !(bIsExif || bIsIPTC || bIsXMP);
if (bPrint) {
if (bIsExif)
out << "Exif: ";
if (bIsIPTC)
out << "IPTC: ";
if (bIsXMP)
out << "XMP : ";
if (bUnknown)
out << "????: ";
}
DataBuf rawData;
rawData.alloc(box.length - sizeof(uuid) - sizeof(box));
long bufRead = io_->read(rawData.pData_, rawData.size_);
if (io_->error())
throw Error(kerFailedToReadImageData);
if (bufRead != rawData.size_)
throw Error(kerInputDataReadFailed);
if (bPrint) {
out << Internal::binaryToString(makeSlice(rawData, 0, 40));
out.flush();
}
lf(out, bLF);
if (bIsExif && bRecursive && rawData.size_ > 0) {
if ((rawData.pData_[0] == rawData.pData_[1]) &&
(rawData.pData_[0] == 'I' || rawData.pData_[0] == 'M')) {
BasicIo::AutoPtr p = BasicIo::AutoPtr(new MemIo(rawData.pData_, rawData.size_));
printTiffStructure(*p, out, option, depth);
}
}
if (bIsIPTC && bRecursive) {
IptcData::printStructure(out, makeSlice(rawData.pData_, 0, rawData.size_), depth);
}
if (bIsXMP && bXMP) {
out.write((const char*)rawData.pData_, rawData.size_);
}
}
} break;
default:
break;
}
// Move to the next box.
io_->seek(static_cast<long>(position - sizeof(box) + box.length), BasicIo::beg);
if (io_->error())
throw Error(kerFailedToReadImageData);
if (bPrint)
lf(out, bLF);
}
}
} // JpegBase::printStructure
void Jp2Image::writeMetadata()
{
if (io_->open() != 0)
{
throw Error(kerDataSourceOpenFailed, io_->path(), strError());
}
IoCloser closer(*io_);
BasicIo::AutoPtr tempIo(new MemIo);
assert (tempIo.get() != 0);
doWriteMetadata(*tempIo); // may throw
io_->close();
io_->transfer(*tempIo); // may throw
} // Jp2Image::writeMetadata
#ifdef __clang__
// ignore cast align errors. dataBuf.pData_ is allocated by malloc() and 4 (or 8 byte aligned).
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
#endif
void Jp2Image::encodeJp2Header(const DataBuf& boxBuf,DataBuf& outBuf)
{
DataBuf output(boxBuf.size_ + iccProfile_.size_ + 100); // allocate sufficient space
int outlen = sizeof(Jp2BoxHeader) ; // now many bytes have we written to output?
int inlen = sizeof(Jp2BoxHeader) ; // how many bytes have we read from boxBuf?
Jp2BoxHeader* pBox = (Jp2BoxHeader*) boxBuf.pData_;
int32_t length = getLong((byte*)&pBox->length, bigEndian);
int32_t count = sizeof (Jp2BoxHeader);
char* p = (char*) boxBuf.pData_;
bool bWroteColor = false ;
while ( count < length || !bWroteColor ) {
Jp2BoxHeader* pSubBox = (Jp2BoxHeader*) (p+count) ;
// copy data. pointer could be into a memory mapped file which we will decode!
Jp2BoxHeader subBox = *pSubBox ;
Jp2BoxHeader newBox = subBox;
if ( count < length ) {
subBox.length = getLong((byte*)&subBox.length, bigEndian);
subBox.type = getLong((byte*)&subBox.type , bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Jp2Image::encodeJp2Header subbox: "<< toAscii(subBox.type) << " length = " << subBox.length << std::endl;
#endif
count += subBox.length;
newBox.type = subBox.type;
} else {
subBox.length=0;
newBox.type = kJp2BoxTypeColorHeader;
count = length;
}
int32_t newlen = subBox.length;
if ( newBox.type == kJp2BoxTypeColorHeader ) {
bWroteColor = true ;
if ( ! iccProfileDefined() ) {
const char* pad = "\x01\x00\x00\x00\x00\x00\x10\x00\x00\x05\x1cuuid";
uint32_t psize = 15;
ul2Data((byte*)&newBox.length,psize ,bigEndian);
ul2Data((byte*)&newBox.type ,newBox.type,bigEndian);
::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox));
::memcpy(output.pData_+outlen+sizeof(newBox) ,pad ,psize );
newlen = psize ;
} else {
const char* pad = "\0x02\x00\x00";
uint32_t psize = 3;
ul2Data((byte*)&newBox.length,psize+iccProfile_.size_,bigEndian);
ul2Data((byte*)&newBox.type,newBox.type,bigEndian);
::memcpy(output.pData_+outlen ,&newBox ,sizeof(newBox) );
::memcpy(output.pData_+outlen+sizeof(newBox) , pad ,psize );
::memcpy(output.pData_+outlen+sizeof(newBox)+psize,iccProfile_.pData_,iccProfile_.size_);
newlen = psize + iccProfile_.size_;
}
} else {
::memcpy(output.pData_+outlen,boxBuf.pData_+inlen,subBox.length);
}
outlen += newlen;
inlen += subBox.length;
}
// allocate the correct number of bytes, copy the data and update the box header
outBuf.alloc(outlen);
::memcpy(outBuf.pData_,output.pData_,outlen);
pBox = (Jp2BoxHeader*) outBuf.pData_;
ul2Data((byte*)&pBox->type,kJp2BoxTypeJp2Header,bigEndian);
ul2Data((byte*)&pBox->length,outlen,bigEndian);
} // Jp2Image::encodeJp2Header
#ifdef __clang__
#pragma clang diagnostic pop
#endif
void Jp2Image::doWriteMetadata(BasicIo& outIo)
{
if (!io_->isopen()) throw Error(kerInputDataReadFailed);
if (!outIo.isopen()) throw Error(kerImageWriteFailed);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Writing JPEG-2000 file " << io_->path() << std::endl;
std::cout << "Exiv2::Jp2Image::doWriteMetadata: tmp file created " << outIo.path() << std::endl;
#endif
// Ensure that this is the correct image type
if (!isJp2Type(*io_, true))
{
if (io_->error() || io_->eof()) throw Error(kerInputDataReadFailed);
throw Error(kerNoImageInInputData);
}
// Write JPEG2000 Signature.
if (outIo.write(Jp2Signature, 12) != 12) throw Error(kerImageWriteFailed);
Jp2BoxHeader box = {0,0};
byte boxDataSize[4];
byte boxUUIDtype[4];
DataBuf bheaderBuf(8); // Box header : 4 bytes (data size) + 4 bytes (box type).
// FIXME: Andreas, why the loop do not stop when EOF is taken from _io. The loop go out by an exception
// generated by a zero size data read.
while(io_->tell() < (long) io_->size())
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Position: " << io_->tell() << " / " << io_->size() << std::endl;
#endif
// Read chunk header.
std::memset(bheaderBuf.pData_, 0x00, bheaderBuf.size_);
long bufRead = io_->read(bheaderBuf.pData_, bheaderBuf.size_);
if (io_->error()) throw Error(kerFailedToReadImageData);
if (bufRead != bheaderBuf.size_) throw Error(kerInputDataReadFailed);
// Decode box header.
box.length = getLong(bheaderBuf.pData_, bigEndian);
box.type = getLong(bheaderBuf.pData_ + 4, bigEndian);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: box type: " << toAscii(box.type)
<< " length: " << box.length << std::endl;
#endif
if (box.length == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Null Box size has been found. "
"This is the last box of file." << std::endl;
#endif
box.length = (uint32_t) (io_->size() - io_->tell() + 8);
}
if (box.length == 1)
{
// FIXME. Special case. the real box size is given in another place.
}
// Read whole box : Box header + Box data (not fixed size - can be null).
DataBuf boxBuf(box.length); // Box header (8 bytes) + box data.
memcpy(boxBuf.pData_, bheaderBuf.pData_, 8); // Copy header.
bufRead = io_->read(boxBuf.pData_ + 8, box.length - 8); // Extract box data.
if (io_->error())
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Error reading source file" << std::endl;
#endif
throw Error(kerFailedToReadImageData);
}
if (bufRead != (long)(box.length - 8))
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Cannot read source file data" << std::endl;
#endif
throw Error(kerInputDataReadFailed);
}
switch(box.type)
{
case kJp2BoxTypeJp2Header:
{
DataBuf newBuf;
encodeJp2Header(boxBuf,newBuf);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write JP2Header box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(newBuf.pData_, newBuf.size_) != newBuf.size_) throw Error(kerImageWriteFailed);
// Write all updated metadata here, just after JP2Header.
if (exifData_.count() > 0)
{
// Update Exif data to a new UUID box
Blob blob;
ExifParser::encode(blob, littleEndian, exifData_);
if (blob.size())
{
DataBuf rawExif(static_cast<long>(blob.size()));
memcpy(rawExif.pData_, &blob[0], blob.size());
DataBuf boxData(8 + 16 + rawExif.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidExif, 16);
memcpy(boxData.pData_ + 8 + 16, rawExif.pData_, rawExif.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Exif metadata (length: "
<< boxData.size_ << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
}
if (iptcData_.count() > 0)
{
// Update Iptc data to a new UUID box
DataBuf rawIptc = IptcParser::encode(iptcData_);
if (rawIptc.size_ > 0)
{
DataBuf boxData(8 + 16 + rawIptc.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidIptc, 16);
memcpy(boxData.pData_ + 8 + 16, rawIptc.pData_, rawIptc.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with Iptc metadata (length: "
<< boxData.size_ << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
}
if (writeXmpFromPacket() == false)
{
if (XmpParser::encode(xmpPacket_, xmpData_) > 1)
{
#ifndef SUPPRESS_WARNINGS
EXV_ERROR << "Failed to encode XMP metadata." << std::endl;
#endif
}
}
if (xmpPacket_.size() > 0)
{
// Update Xmp data to a new UUID box
DataBuf xmp(reinterpret_cast<const byte*>(xmpPacket_.data()), static_cast<long>(xmpPacket_.size()));
DataBuf boxData(8 + 16 + xmp.size_);
ul2Data(boxDataSize, boxData.size_, Exiv2::bigEndian);
ul2Data(boxUUIDtype, kJp2BoxTypeUuid, Exiv2::bigEndian);
memcpy(boxData.pData_, boxDataSize, 4);
memcpy(boxData.pData_ + 4, boxUUIDtype, 4);
memcpy(boxData.pData_ + 8, kJp2UuidXmp, 16);
memcpy(boxData.pData_ + 8 + 16, xmp.pData_, xmp.size_);
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: Write box with XMP metadata (length: "
<< boxData.size_ << ")" << std::endl;
#endif
if (outIo.write(boxData.pData_, boxData.size_) != boxData.size_) throw Error(kerImageWriteFailed);
}
break;
}
case kJp2BoxTypeUuid:
{
if(memcmp(boxBuf.pData_ + 8, kJp2UuidExif, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Exif Uuid box" << std::endl;
#endif
}
else if(memcmp(boxBuf.pData_ + 8, kJp2UuidIptc, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Iptc Uuid box" << std::endl;
#endif
}
else if(memcmp(boxBuf.pData_ + 8, kJp2UuidXmp, 16) == 0)
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: strip Xmp Uuid box" << std::endl;
#endif
}
else
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: write Uuid box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);
}
break;
}
default:
{
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: write box (length: " << box.length << ")" << std::endl;
#endif
if (outIo.write(boxBuf.pData_, boxBuf.size_) != boxBuf.size_) throw Error(kerImageWriteFailed);
break;
}
}
}
#ifdef EXIV2_DEBUG_MESSAGES
std::cout << "Exiv2::Jp2Image::doWriteMetadata: EOF" << std::endl;
#endif
} // Jp2Image::doWriteMetadata
// *************************************************************************
// free functions
Image::AutoPtr newJp2Instance(BasicIo::AutoPtr io, bool create)
{
Image::AutoPtr image(new Jp2Image(io, create));
if (!image->good())
{
image.reset();
}
return image;
}
bool isJp2Type(BasicIo& iIo, bool advance)
{
const int32_t len = 12;
byte buf[len];
iIo.read(buf, len);
if (iIo.error() || iIo.eof())
{
return false;
}
bool matched = (memcmp(buf, Jp2Signature, len) == 0);
if (!advance || !matched)
{
iIo.seek(-len, BasicIo::cur);
}
return matched;
}
} // namespace Exiv2
| ./CrossVul/dataset_final_sorted/CWE-835/cpp/bad_1367_0 |
crossvul-cpp_data_bad_581_1 | /*
Copyright 2008-2018 LibRaw LLC (info@libraw.org)
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
This file is generated from Dave Coffin's dcraw.c
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net
Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/)
for more information
*/
#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"
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)
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, unsigned 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]);
}
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,
47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
int bypp = tiff_bps <= 8 ? 1 : 2;
int bufsize = width * 3 * bypp;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width > 32767 || raw_height > 32767)
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixel = raw_width*(raw_height+7);
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)
if(todo[i] < maxpixel)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
else
derror();
}
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)
{
#ifdef LIBRAW_LIBRARY_BUILD
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
int row, col;
#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);
}
}
if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF;
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[0x4002];
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(width>640 || height > 480)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
// All kodak radc images are 768x512
if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if (!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
if(col>=0)
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[272]; /* 264 looks enough */
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
{
int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
if (idx >= 0 && idx < 0xffff)
{
if ((RAW(row, col + i) = curve[idx]) >> 12)
derror();
}
else
derror();
}
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixels = raw_width*(raw_height+7);
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)];
unsigned idest = RAWINDEX(row, col + c);
unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);
if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion
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);
else
derror();
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
}
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
}
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++)
if(fabs(num)>0.00001f)
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 & 0x55555555U) << 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)
{
#ifdef LIBRAW_IOSPACE_CHECK
INT64 pos = ftell(ifp);
INT64 fsize = ifp->size();
if(fsize < 12 || (fsize-pos) < 12)
throw LIBRAW_EXCEPTION_IO_EOF;
#endif
*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);
}
}
static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); }
static float libraw_powf64l(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 libraw_powf64l(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
unsigned CLASS setCanonBodyFeatures(unsigned id)
{
if (id == 0x03740000) // EOS M3
id = 0x80000374;
else if (id == 0x03840000) // EOS M10
id = 0x80000384;
else if (id == 0x03940000) // EOS M5
id = 0x80000394;
else if (id == 0x04070000) // EOS M6
id = 0x80000407;
else if (id == 0x03980000) // EOS M100
id = 0x80000398;
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) || // M6
(id == 0x80000398) // M100
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return id;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
if (maxlen < 16)
return; // too short
CameraInfo[0] = 0;
CameraInfo[1] = 0;
if (type == 4)
{
if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) ||
(maxlen == 171) || (maxlen == 264) || (maxlen > 400))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2));
else if (maxlen == 72)
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2));
else if ((maxlen == 85) || (maxlen == 93))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2));
else if ((maxlen == 96) || (maxlen == 104))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2));
}
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
imgdata.other.CameraTemperature = 0.0f;
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x80000398) || // M100
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000))) // G1 X Mark III
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if (id == 0x5330303638ULL)
{
strcpy(model, "E-M10MarkIII");
}
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 24, SEEK_CUR);
tempAp = get2();
if (tempAp != 0)
imgdata.other.CameraTemperature = (float)(tempAp - 128);
tempAp = get2();
if (tempAp != -1)
imgdata.other.FlashGN = ((float)tempAp) / 32;
get2();
// fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x000c)
{
unsigned tS = get4();
sprintf (imgdata.shootinginfo.BodySerial, "%d", tS);
}
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 == 0x009a)
{
get4();
imgdata.sizes.raw_crop.cwidth = get4();
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cleft = get4();
imgdata.sizes.raw_crop.ctop = get4();
}
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 == 0x4013)
{
get4();
imgdata.makernotes.canon.AFMicroAdjMode = get4();
imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4());
}
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 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2cf << 1), SEEK_SET); // offset 719 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000) || // G1 X Mark III
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000398) || // EOS M100
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x1fc << 1), SEEK_SET); // offset 508 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2dc << 1), SEEK_SET); // offset 732 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x230 << 1), SEEK_SET); // offset 560 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
libraw_powf64l(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 =
libraw_powf64l(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 =
libraw_powf64l(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)
{
ushort idx;
static const struct
{
ushort scf[8];
/*
scf[0] camera id
scf[1] camera format
scf[2] camera mount: Minolta A, Sony E, fixed,
scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC
scf[4] lens mount
scf[5] tag 0x2010 group (0 if not used)
scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid
scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid
*/
} SonyCamFeatures[] = {
{256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{267, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{268, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{271, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{272, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{276, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{277, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd},
{289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd},
{294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa},
{295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff},
{298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{301, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa},
{303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa},
{304, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa},
{306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff},
{309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa},
{314, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{315, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{316, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{320, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{321, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{322, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{323, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{324, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{325, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{326, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{327, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{328, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{329, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{330, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{331, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{332, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{333, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{334, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{335, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{336, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{337, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{338, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{343, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{345, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{348, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{349, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{351, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{352, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd},
{355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{359, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{361, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{363, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 0, 0x0320, 0x019f},
{364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff},
};
imgdata.lens.makernotes.CamID = id;
if (id == 2)
{
imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
imgdata.makernotes.sony.group2010 = 0;
imgdata.makernotes.sony.real_iso_offset = 0xffff;
imgdata.makernotes.sony.ImageCount3_offset = 0xffff;
return;
}
else
idx = id - 256;
if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures))
{
if (!SonyCamFeatures[idx].scf[2])
return;
imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1];
imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2];
imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3];
if (SonyCamFeatures[idx].scf[4])
imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4];
imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5];
imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6];
imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7];
}
char *sbstr = strstr(software, " v");
if (sbstr != NULL)
{
sbstr += 2;
imgdata.makernotes.sony.firmware = atof(sbstr);
if ((id == 306) || (id == 311))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if (id == 312)
{
if (imgdata.makernotes.sony.firmware < 2.0f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if ((id == 318) || (id == 340))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01a0;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01b6;
}
}
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id)
{
short bufx;
if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2))
bufx = buf[1];
else if ((id >= 273) && (len >= 3))
bufx = buf[2];
else
return;
imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f;
}
void CLASS process_Sony_0x2010(uchar *buf, ushort len)
{
if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) ||
(len < (imgdata.makernotes.sony.real_iso_offset + 2)))
return;
if (imgdata.other.real_ISO < 0.1f)
{
uchar s[2];
s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]];
s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id)
{
ushort lid;
uchar s[4];
int c;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (len < 2)
return;
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(libraw_powf64l(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(libraw_powf64l(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 (len <= 0x106)
return;
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = libraw_powf64l(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)
{
if (len <= 0x108)
return;
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if (len <= 0x10a)
return;
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))
{
if (len <= 0x116)
return;
// "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)
{
if (len <= 0x117)
return;
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
}
if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362) || (id == 363))
{
if (len <= 0x8d)
return;
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)
{
if (len <= 0xf4)
return;
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))
{
if (len <= 0x7f)
return;
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);
}
if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) &&
(len >= (imgdata.makernotes.sony.ImageCount3_offset + 4)))
{
FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]];
imgdata.makernotes.sony.ImageCount3 = sget4(s);
}
if (id == 362)
{
for (c = 0; c < 6; c++)
{
imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]];
}
}
return;
}
void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id)
{
uchar s[4];
int c;
short bufx = buf[0];
if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f))
{ // 0x9400 'c' version
if ((id == 358) || (id == 362) || (id == 363) || (id == 365))
{
imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]];
}
else
{
FORC4 s[c] = SonySubstitution[buf[0x0a + c]];
imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s);
}
imgdata.makernotes.sony.Sony0x9400_version = 0xc;
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]];
FORC4 s[c] = SonySubstitution[buf[0x12 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots
FORC4 s[c] = SonySubstitution[buf[0x1a + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files
}
else if ((bufx == 0x0c) && (len >= 0x1f))
{ // 0x9400 'b' version
imgdata.makernotes.sony.Sony0x9400_version = 0xb;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]];
}
else if ((bufx == 0x0a) && (len >= 0x23))
{ // 0x9400 'a' version
imgdata.makernotes.sony.Sony0x9400_version = 0xa;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]];
}
else
return;
}
void CLASS process_Sony_0x9402(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) ||
(imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA))
return;
if (len < 5)
return;
short bufx = buf[0x00];
if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff))
return;
imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]);
return;
}
void CLASS process_Sony_0x9403(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = SonySubstitution[buf[4]];
if ((bufx == 0x00) || (bufx == 0x94))
return;
imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]);
return;
}
void CLASS process_Sony_0x9406(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = buf[0];
if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b))
return;
bufx = buf[2];
if ((bufx != 0x08) && (bufx != 0x1b))
return;
imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f;
return;
}
void CLASS process_Sony_0x940c(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) &&
(imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX))
return;
if (len <= 0x000a)
return;
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_0x940e(uchar *buf, ushort len, unsigned id)
{
if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]];
}
else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]];
}
else
return;
if (imgdata.makernotes.sony.AFMicroAdjValue != 0)
imgdata.makernotes.sony.AFMicroAdjOn = 1;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116,
ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400,
ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406,
ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len,
uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_len)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
if (table_buf_0x2010_len)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
if (table_buf_0x9050_len)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
if (table_buf_0x9400_len)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
if (table_buf_0x9402_len)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
if (table_buf_0x9403_len)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
if (table_buf_0x9406_len)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
if (table_buf_0x940c_len)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
if (table_buf_0x940e_len)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id);
free(table_buf_0x940e);
table_buf_0x940e_len = 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]);
if (len == 5478)
{
imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20;
imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0);
imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f;
}
}
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 = libraw_powf64l(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 == 0x3000) && (len < 256000))
{
uchar *table_buf_0x3000;
table_buf_0x3000 = (uchar *)malloc(len);
fread(table_buf_0x3000, len, 1, ifp);
for (int i = 0; i < 20; i++)
imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i];
}
else if (tag == 0x0116 && len < 256000)
{
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_len = len;
fread(table_buf_0x0116, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
}
else if (tag == 0x2010 && len < 256000)
{
table_buf_0x2010 = (uchar *)malloc(len);
table_buf_0x2010_len = len;
fread(table_buf_0x2010, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
}
else if (tag == 0x201a)
{
imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4();
}
else if (tag == 0x201b)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.shootinginfo.FocusMode = (short)uc;
}
else if (tag == 0x202c)
{
imgdata.makernotes.sony.MeteringMode2 = get2();
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_len = len;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
}
else if (tag == 0x9400 && len < 256000)
{
table_buf_0x9400 = (uchar *)malloc(len);
table_buf_0x9400_len = len;
fread(table_buf_0x9400, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
}
else if (tag == 0x9402 && len < 256000)
{
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_len = len;
fread(table_buf_0x9402, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
}
else if (tag == 0x9403 && len < 256000)
{
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_len = len;
fread(table_buf_0x9403, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
}
else if ((tag == 0x9405) && (len < 256000) && (len > 0x64))
{
uchar *table_buf_0x9405;
table_buf_0x9405 = (uchar *)malloc(len);
fread(table_buf_0x9405, len, 1, ifp);
uchar bufx = table_buf_0x9405[0x0];
if (imgdata.other.real_ISO < 0.1f)
{
if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) ||
(bufx == 0xb3) || (bufx == 0xe1))
{
uchar s[2];
s[0] = SonySubstitution[table_buf_0x9405[0x04]];
s[1] = SonySubstitution[table_buf_0x9405[0x05]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
free(table_buf_0x9405);
}
else if (tag == 0x9406 && len < 256000)
{
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_len = len;
fread(table_buf_0x9406, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_len = len;
fread(table_buf_0x940c, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
}
else if (tag == 0x940e && len < 256000)
{
table_buf_0x940e = (uchar *)malloc(len);
table_buf_0x940e_len = len;
fread(table_buf_0x940e, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x940e);
table_buf_0x940e_len = 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);
}
else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2))
{
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cwidth = get4();
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
short nWB, tWB;
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) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) ||
(tag == 0x2050) || (tag == 0x3000))
{
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;
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
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;
}
}
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];
}
}
}
else 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;
}
else 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;
}
else 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();
}
}
else 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;
}
}
else 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();
}
else
{
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(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 0x20200306:
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
break;
case 0x20200307:
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{ /*placeholder */
}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) ||
!strncasecmp(model, "KODAK P712", 10))
{
if (tag == 0xf90b)
{
imgdata.makernotes.kodak.clipBlack = get2();
}
else if (tag == 0xf90c)
{
imgdata.makernotes.kodak.clipWhite = get2();
}
}
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) ||
!strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0045)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2);
break;
case 0x20400612:
case 0x30000612:
imgdata.sizes.raw_crop.cleft = get2();
break;
case 0x20400613:
case 0x30000613:
imgdata.sizes.raw_crop.ctop = get2();
break;
case 0x20400614:
case 0x30000614:
imgdata.sizes.raw_crop.cwidth = get2();
break;
case 0x20400615:
case 0x30000615:
imgdata.sizes.raw_crop.cheight = get2();
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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
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 * libraw_powf64l(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 * libraw_powf64l(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = libraw_powf64l(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = libraw_powf64l(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 == 0x20200306)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
if (tag == 0x20200307)
{
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(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 = libraw_powf64l(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = libraw_powf64l(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, MIN(len,511), ifp);
mn_text[511] = 0;
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=");
if(pos)
{
pos +=4;
char *pos2 = strstr(pos, " ");
if(pos2)
{
l = pos2 - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
#if defined WIN32 || defined(__MINGW32__)
// Win32 strtok is already thread-safe
pos = strtok(ccms, ",");
#else
char *last=0;
pos = strtok_r(ccms, ",",&last);
#endif
if(pos)
{
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];
#if defined WIN32 || defined(__MINGW32__)
pos = strtok(NULL, ",");
#else
pos = strtok_r(NULL, ",",&last);
#endif
if(!pos) goto end; // broken
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
}
}
end:;
}
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) * 0x01010101U << 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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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) * 0x01010101U * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
else if(len < 1)
return;
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 j, c, wbi = -2, romm_camTemp[9], romm_camScale[3];
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1003)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 1004)
imgdata.sizes.raw_crop.ctop = get2();
if (tag == 1005)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 1006)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 1007)
imgdata.makernotes.kodak.BlackLevelTop = get2();
if (tag == 1008)
imgdata.makernotes.kodak.BlackLevelBottom = get2();
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 1030) && (len == 1))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 1043) && (len == 1))
imgdata.other.SensorTemperature = getreal(type);
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9))
{
short validM = 0;
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type);
}
validM = 1;
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
validM = 1;
}
}
if (validM)
{
romm_coeff(imgdata.makernotes.kodak.romm_camDaylight);
}
}
if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
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 == 0xfa13)
width = getint(type);
if (tag == 0xfa14)
height = (getint(type) + 1) & -2;
/*
height = getint(type);
if (tag == 0xfa16)
raw_width = get2();
if (tag == 0xfa17)
raw_height = get2();
*/
if (tag == 0xfa18)
{
imgdata.makernotes.kodak.offset_left = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_left += 1;
}
if (tag == 0xfa19)
{
imgdata.makernotes.kodak.offset_top = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_top += 1;
}
if (tag == 0xfa31)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 0xfa32)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 0xfa3e)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 0xfa3f)
imgdata.sizes.raw_crop.ctop = get2();
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
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 && savepos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), 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:
if (len == 3)
{
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
else if (len == 1)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here??
}
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;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 10:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_bpp = get2();
}
break;
#endif
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;
case 0x0120:
if (pana_raw)
{
unsigned sorder = order;
unsigned long sbase = base;
base = ftell(ifp);
order = get2();
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, get4()-8, SEEK_CUR);
parse_tiff_ifd (base);
base = sbase;
order = sorder;
}
break;
case 0x2009:
if ((libraw_internal_data.unpacker_data.pana_encoding == 4) ||
(libraw_internal_data.unpacker_data.pana_encoding == 5))
{
int n = MIN (8, len);
int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4};
imgdata.makernotes.panasonic.BlackLevelDim = len;
for (int i=0; i < n; i++)
{
imgdata.makernotes.panasonic.BlackLevel[permut[i]] =
(float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp));
}
}
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;
#ifdef LIBRAW_LIBRARY_BUILD
case 45:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_encoding = get2();
}
break;
#endif
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 */
if ((pana_raw) && (tag == 11) && (type == 3))
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.makernotes.panasonic.Compression = get2();
#endif
break;
}
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++)
{
if(cfa_pat[i] > 31) continue; // Skip wrong data
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4
{
int q = get2();
if(q > 0) cam_mul[c ^ 1] = 4096.0 / q;
}
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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);
if(len>0)
{
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 */
{
float q1 = getreal(type);
float q2 = getreal(type);
if(q1 > 0.00001f && q2 > 0.00001f)
{
pixel_aspect = q1/q2;
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0];
imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1];
}
}
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2];
imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3];
}
}
break;
case 0x74c7:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cleft = get4();
imgdata.makernotes.sony.raw_crop.ctop = get4();
}
break;
case 0x74c8:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cwidth = get4();
imgdata.makernotes.sony.raw_crop.cheight = get4();
}
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;
INT64 save_pos = ifp->tell();
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
curr_pos = save_pos + MakN_length - 6;
fseek(ifp, curr_pos, SEEK_SET);
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "SR2 ", 4))
{
order = 0x4d4d;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
unsigned *buf_SR2;
uchar *cbuf_SR2;
unsigned icbuf_SR2;
unsigned entries, tag, type, len, save;
int ival;
unsigned SR2SubIFDOffset = 0;
unsigned SR2SubIFDLength = 0;
unsigned SR2SubIFDKey = 0;
int base = curr_pos + 6 - pos_in_original_raw;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 0x7200)
{
SR2SubIFDOffset = get4();
}
else if (tag == 0x7201)
{
SR2SubIFDLength = get4();
}
else if (tag == 0x7221)
{
SR2SubIFDKey = get4();
}
fseek(ifp, save, SEEK_SET);
}
if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety
{
fseek(ifp, SR2SubIFDOffset + base, SEEK_SET);
fread(buf_SR2, SR2SubIFDLength, 1, ifp);
sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey);
cbuf_SR2 = (uchar *)buf_SR2;
entries = sget2(cbuf_SR2);
icbuf_SR2 = 2;
while (entries--)
{
tag = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
type = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
len = sget4(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 4;
if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4)
{
ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset;
}
else
{
ival = icbuf_SR2;
}
if(ival > SR2SubIFDLength) // points out of orig. buffer size
break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter
icbuf_SR2 += 4;
switch (tag)
{
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c);
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] =
sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
}
}
free(buf_SR2);
}
} /* SR2 processed */
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
if(fabs(asn[c])>0.0001)
cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC if(fabs(cc[c][c])>0.0001) 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( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535
|| tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535)
continue; /* wrong image dimensions */
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:
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height))
#else
if (tiff_ifd[raw].bytes == raw_width * raw_height)
#endif
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
#else
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
#endif
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps))
#else
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
#endif
{
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) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 &&
INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ
{
tiff_bps = 14;
tiff_samples = 4;
load_raw = &CLASS sony_arq_load_raw;
filters = 0;
strcpy(cdesc, "RGBG");
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL)
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
#endif
load_flags = 24;
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL)
#else
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
#endif
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height))
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
#endif
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:
#ifdef LIBRAW_LIBRARY_BUILD
if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes))
#else
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
#endif
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
{
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 (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL)
{
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 = libraw_powf64l(2.0f, -int_to_float((get4(), get4())));
aperture = libraw_powf64l(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 = libraw_powf64l(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 = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = libraw_powf64l(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
{
ushort q = get2();
cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024;
}
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
unique_id = setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0211:
imgdata.other.SensorTemperature2 = int_to_float(data);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.SensorTemperature = ph1.tag_210;
#endif
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED;
#endif
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/
}
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x110)
{
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cleft = get2();
}
else if (tag == 0x111)
{
imgdata.sizes.raw_crop.cheight = get2();
imgdata.sizes.raw_crop.cwidth = get2();
}
else if ((tag == 0x122) && !strcmp(model, "DBP for GX680"))
{
int k = get2();
int l = get2(); /* margins? */
int m = get2(); /* margins? */
int n = get2();
// printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n);
}
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") ||
!strcmp(model, "X-A5") ||
!strcmp(model, "X-A20"))
{
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();
}
}
/*
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,
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82,
{7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M100", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark III", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A20", 0, 0, /* temp */
{ 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-A5", 0, 0, /* temp */
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-E3", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-H1", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D850", 0, 0,
{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL9", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-G9", -15, 0,
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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-GH5s", -15, 0,
{ 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } },
{ "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-GF10", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "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 DC-GX9", -15, 0, /* temp */
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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 } },
{ "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// {3984,0,0,0,10000,0,0,0,7666}},
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
// {2423,0,0,0,9901,0,0,0,7989}},
{ 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10M4", -800, 0,
{ 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{"Sony DSC-RX0", -800, 0, /* temp */
{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 16596,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 16596,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A550", 0, 16596,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */
{ 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-7M3", 0, 0,
{ 7374,-2389,-551,-5435,13162,2519,-1006,1795,6552 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM3", 0, 0,
{ 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } },
{ "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};
if(width > 2064) return 0.f; // too wide
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((unsigned char)string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x398, "EOS M100"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16b, "ILCE-7M3"}, {0x16c, "DSC-RX0"},
{0x16d, "DSC-RX10M4"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 =
imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature =
imgdata.other.exifAmbientTemperature = -1000.0f;
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT;
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 = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = libraw_powf64l(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 = libraw_powf64l(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
strncpy(model, head + 0x1c,0x20);
model[0x20]=0;
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4(); // bytes count
width = get2();
height = get2();
#ifdef LIBRAW_LIBRARY_BUILD
// Data integrity check
if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height))
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
/* no foveon support for dcraw build from libraw source */
parse_x3f();
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
break;
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
memmove(model, model + 8,strlen(model)-7);
if (!strncmp(model, "Digital Camera ", 15))
memmove(model, model + 15,strlen(model)-14);
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] * 0x01010101U;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c, A6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
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 = 0x01010101U * (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
/* alloc in unpack() may be fooled by size adjust */
|| ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535))
{
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 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&
tiff_ifd[sidx].dng_levels.default_crop[3] > 0)
{
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
}
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;
}
void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val)
{
struct libraw_tiff_tag *tt;
int c;
tt = (struct libraw_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(×tamp);
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);
}
| ./CrossVul/dataset_final_sorted/CWE-835/cpp/bad_581_1 |
crossvul-cpp_data_good_2584_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.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/constitute.h"
#include "MagickCore/draw.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/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MagickPathExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
geometry[MagickPathExtent],
*p,
text[MagickPathExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->resolution.x)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->resolution.y)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MagickPathExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image,exception);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics,exception);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MagickPathExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture,exception);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info,exception);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MagickPathExtent);
(void) SetImageBackgroundColor(image,exception);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture,exception);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info,exception);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MagickPathExtent],
text[MagickPathExtent];
Image
*image;
long
x_offset,
y_offset;
PixelInfo
pixel;
MagickBooleanType
status;
QuantumAny
range;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->alpha_trait=UndefinedPixelTrait;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->alpha_trait=BlendPixelTrait;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,(ColorspaceType) type,exception);
GetPixelInfo(image,&pixel);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
alpha,
black,
blue,
green,
red;
red=0.0;
green=0.0;
blue=0.0;
black=0.0;
alpha=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&alpha);
green=red;
blue=red;
break;
}
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,
&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&black,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&black);
break;
}
default:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
black*=0.01*range;
alpha*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),
range);
pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),
range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
SetPixelViaPixelInfo(image,&pixel,q);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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 (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("TXT","SPARSE-COLOR","Sparse Color");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TXT","TEXT","Text");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->format_type=ImplicitFormatType;
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TXT","TXT","Text");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->magick=(IsImageFormatHandler *) IsTXT;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("SPARSE-COLOR");
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(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 WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&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++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
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-835/c/good_2584_0 |
crossvul-cpp_data_good_4059_0 | /*
* Copyright (C) 2011-2012 Christian Beier <dontmind@freeshell.org>
* 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.
*/
/*
* sockets.c - functions to deal with sockets.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#ifdef __linux__
/* Setting this on other systems hides definitions such as INADDR_LOOPBACK.
* The check should be for __GLIBC__ in fact. */
# define _POSIX_SOURCE
#endif
#endif
#if LIBVNCSERVER_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#include <rfb/rfbclient.h>
#include "sockets.h"
#include "tls.h"
#include "sasl.h"
void PrintInHex(char *buf, int len);
rfbBool errorMessageOnReadFailure = TRUE;
/*
* ReadFromRFBServer is called whenever we want to read some data from the RFB
* server. It is non-trivial for two reasons:
*
* 1. For efficiency it performs some intelligent buffering, avoiding invoking
* the read() system call too often. For small chunks of data, it simply
* copies the data out of an internal buffer. For large amounts of data it
* reads directly into the buffer provided by the caller.
*
* 2. Whenever read() would block, it invokes the Xt event dispatching
* mechanism to process X events. In fact, this is the only place these
* events are processed, as there is no XtAppMainLoop in the program.
*/
rfbBool
ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)
{
const int USECS_WAIT_PER_RETRY = 100000;
int retries = 0;
#undef DEBUG_READ_EXACT
#ifdef DEBUG_READ_EXACT
char* oout=out;
unsigned int nn=n;
rfbClientLog("ReadFromRFBServer %d bytes\n",n);
#endif
/* Handle attempts to write to NULL out buffer that might occur
when an outside malloc() fails. For instance, memcpy() to NULL
results in undefined behaviour and probably memory corruption.*/
if(!out)
return FALSE;
if (client->serverPort==-1) {
/* vncrec playing */
rfbVNCRec* rec = client->vncRec;
struct timeval tv;
if (rec->readTimestamp) {
rec->readTimestamp = FALSE;
if (!fread(&tv,sizeof(struct timeval),1,rec->file))
return FALSE;
tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);
tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);
if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {
struct timeval diff;
diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;
diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;
if(diff.tv_usec<0) {
diff.tv_sec--;
diff.tv_usec+=1000000;
}
#ifndef WIN32
sleep (diff.tv_sec);
usleep (diff.tv_usec);
#else
Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000);
#endif
}
rec->tv=tv;
}
return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);
}
if (n <= client->buffered) {
memcpy(out, client->bufoutptr, n);
client->bufoutptr += n;
client->buffered -= n;
#ifdef DEBUG_READ_EXACT
goto hexdump;
#endif
return TRUE;
}
memcpy(out, client->bufoutptr, client->buffered);
out += client->buffered;
n -= client->buffered;
client->bufoutptr = client->buf;
client->buffered = 0;
if (n <= RFB_BUF_SIZE) {
while (client->buffered < n) {
int i;
if (client->tlsSession)
i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
else
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn)
i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
else {
#endif /* LIBVNCSERVER_HAVE_SASL */
i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
#ifdef WIN32
if (i < 0) errno=WSAGetLastError();
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
}
#endif
if (i <= 0) {
if (i < 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
if (client->readTimeout > 0 &&
++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))
{
rfbClientLog("Connection timed out\n");
return FALSE;
}
/* TODO:
ProcessXtEvents();
*/
WaitForMessage(client, USECS_WAIT_PER_RETRY);
i = 0;
} else {
rfbClientErr("read (%d: %s)\n",errno,strerror(errno));
return FALSE;
}
} else {
if (errorMessageOnReadFailure) {
rfbClientLog("VNC server closed connection\n");
}
return FALSE;
}
}
client->buffered += i;
}
memcpy(out, client->bufoutptr, n);
client->bufoutptr += n;
client->buffered -= n;
} else {
while (n > 0) {
int i;
if (client->tlsSession)
i = ReadFromTLS(client, out, n);
else
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn)
i = ReadFromSASL(client, out, n);
else
#endif
i = read(client->sock, out, n);
if (i <= 0) {
if (i < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (errno == EWOULDBLOCK || errno == EAGAIN) {
if (client->readTimeout > 0 &&
++retries > (client->readTimeout * 1000 * 1000 / USECS_WAIT_PER_RETRY))
{
rfbClientLog("Connection timed out\n");
return FALSE;
}
/* TODO:
ProcessXtEvents();
*/
WaitForMessage(client, USECS_WAIT_PER_RETRY);
i = 0;
} else {
rfbClientErr("read (%s)\n",strerror(errno));
return FALSE;
}
} else {
if (errorMessageOnReadFailure) {
rfbClientLog("VNC server closed connection\n");
}
return FALSE;
}
}
out += i;
n -= i;
}
}
#ifdef DEBUG_READ_EXACT
hexdump:
{ unsigned int ii;
for(ii=0;ii<nn;ii++)
fprintf(stderr,"%02x ",(unsigned char)oout[ii]);
fprintf(stderr,"\n");
}
#endif
return TRUE;
}
/*
* Write an exact number of bytes, and don't return until you've sent them.
*/
rfbBool
WriteToRFBServer(rfbClient* client, const char *buf, unsigned int n)
{
fd_set fds;
int i = 0;
int j;
const char *obuf = buf;
#ifdef LIBVNCSERVER_HAVE_SASL
const char *output;
unsigned int outputlen;
int err;
#endif /* LIBVNCSERVER_HAVE_SASL */
if (client->serverPort==-1)
return TRUE; /* vncrec playing */
if (client->tlsSession) {
/* WriteToTLS() will guarantee either everything is written, or error/eof returns */
i = WriteToTLS(client, buf, n);
if (i <= 0) return FALSE;
return TRUE;
}
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn) {
err = sasl_encode(client->saslconn,
buf, n,
&output, &outputlen);
if (err != SASL_OK) {
rfbClientLog("Failed to encode SASL data %s",
sasl_errstring(err, NULL, NULL));
return FALSE;
}
obuf = output;
n = outputlen;
}
#endif /* LIBVNCSERVER_HAVE_SASL */
while (i < n) {
j = write(client->sock, obuf + i, (n - i));
if (j <= 0) {
if (j < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (errno == EWOULDBLOCK ||
#ifdef LIBVNCSERVER_ENOENT_WORKAROUND
errno == ENOENT ||
#endif
errno == EAGAIN) {
FD_ZERO(&fds);
FD_SET(client->sock,&fds);
if (select(client->sock+1, NULL, &fds, NULL, NULL) <= 0) {
rfbClientErr("select\n");
return FALSE;
}
j = 0;
} else {
rfbClientErr("write\n");
return FALSE;
}
} else {
rfbClientLog("write failed\n");
return FALSE;
}
}
i += j;
}
return TRUE;
}
static rfbBool WaitForConnected(int socket, unsigned int secs)
{
fd_set writefds;
fd_set exceptfds;
struct timeval timeout;
timeout.tv_sec=secs;
timeout.tv_usec=0;
FD_ZERO(&writefds);
FD_SET(socket, &writefds);
FD_ZERO(&exceptfds);
FD_SET(socket, &exceptfds);
if (select(socket+1, NULL, &writefds, &exceptfds, &timeout)==1) {
#ifdef WIN32
if (FD_ISSET(socket, &exceptfds))
return FALSE;
#else
int so_error;
socklen_t len = sizeof so_error;
getsockopt(socket, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error!=0)
return FALSE;
#endif
return TRUE;
}
return FALSE;
}
rfbSocket
ConnectClientToTcpAddr(unsigned int host, int port)
{
rfbSocket sock = ConnectClientToTcpAddrWithTimeout(host, port, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToTcpAddrWithTimeout(unsigned int host, int port, unsigned int timeout)
{
rfbSocket sock;
struct sockaddr_in addr;
int one = 1;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = host;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbClientErr("ConnectToTcpAddr: socket (%s)\n",strerror(errno));
return RFB_INVALID_SOCKET;
}
if (!SetNonBlocking(sock))
return FALSE;
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (!((errno == EWOULDBLOCK || errno == EINPROGRESS) && WaitForConnected(sock, timeout))) {
rfbClientErr("ConnectToTcpAddr: connect\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("ConnectToTcpAddr: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
rfbSocket
ConnectClientToTcpAddr6(const char *hostname, int port)
{
rfbSocket sock = ConnectClientToTcpAddr6WithTimeout(hostname, port, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToTcpAddr6WithTimeout(const char *hostname, int port, unsigned int timeout)
{
#ifdef LIBVNCSERVER_IPv6
rfbSocket sock;
int n;
struct addrinfo hints, *res, *ressave;
char port_s[10];
int one = 1;
snprintf(port_s, 10, "%d", port);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((n = getaddrinfo(strcmp(hostname,"") == 0 ? "localhost": hostname, port_s, &hints, &res)))
{
rfbClientErr("ConnectClientToTcpAddr6: getaddrinfo (%s)\n", gai_strerror(n));
return RFB_INVALID_SOCKET;
}
ressave = res;
sock = RFB_INVALID_SOCKET;
while (res)
{
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock != RFB_INVALID_SOCKET)
{
if (SetNonBlocking(sock)) {
if (connect(sock, res->ai_addr, res->ai_addrlen) == 0) {
break;
} else {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if ((errno == EWOULDBLOCK || errno == EINPROGRESS) && WaitForConnected(sock, timeout))
break;
rfbCloseSocket(sock);
sock = RFB_INVALID_SOCKET;
}
} else {
rfbCloseSocket(sock);
sock = RFB_INVALID_SOCKET;
}
}
res = res->ai_next;
}
freeaddrinfo(ressave);
if (sock == RFB_INVALID_SOCKET)
{
rfbClientErr("ConnectClientToTcpAddr6: connect\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("ConnectToTcpAddr: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
#else
rfbClientErr("ConnectClientToTcpAddr6: IPv6 disabled\n");
return RFB_INVALID_SOCKET;
#endif
}
rfbSocket
ConnectClientToUnixSock(const char *sockFile)
{
rfbSocket sock = ConnectClientToUnixSockWithTimeout(sockFile, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToUnixSockWithTimeout(const char *sockFile, unsigned int timeout)
{
#ifdef WIN32
rfbClientErr("Windows doesn't support UNIX sockets\n");
return RFB_INVALID_SOCKET;
#else
rfbSocket sock;
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
if(strlen(sockFile) + 1 > sizeof(addr.sun_path)) {
rfbClientErr("ConnectToUnixSock: socket file name too long\n");
return RFB_INVALID_SOCKET;
}
strcpy(addr.sun_path, sockFile);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("ConnectToUnixSock: socket (%s)\n",strerror(errno));
return RFB_INVALID_SOCKET;
}
if (!SetNonBlocking(sock))
return RFB_INVALID_SOCKET;
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr.sun_family) + strlen(addr.sun_path)) < 0 &&
!(errno == EINPROGRESS && WaitForConnected(sock, timeout))) {
rfbClientErr("ConnectToUnixSock: connect\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
#endif
}
/*
* FindFreeTcpPort tries to find unused TCP port in the range
* (TUNNEL_PORT_OFFSET, TUNNEL_PORT_OFFSET + 99]. Returns 0 on failure.
*/
int
FindFreeTcpPort(void)
{
rfbSocket sock;
int port;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr(": FindFreeTcpPort: socket\n");
return 0;
}
for (port = TUNNEL_PORT_OFFSET + 99; port > TUNNEL_PORT_OFFSET; port--) {
addr.sin_port = htons((unsigned short)port);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
rfbCloseSocket(sock);
return port;
}
}
rfbCloseSocket(sock);
return 0;
}
/*
* ListenAtTcpPort starts listening at the given TCP port.
*/
rfbSocket
ListenAtTcpPort(int port)
{
return ListenAtTcpPortAndAddress(port, NULL);
}
/*
* ListenAtTcpPortAndAddress starts listening at the given TCP port on
* the given IP address
*/
rfbSocket
ListenAtTcpPortAndAddress(int port, const char *address)
{
rfbSocket sock = RFB_INVALID_SOCKET;
int one = 1;
#ifndef LIBVNCSERVER_IPv6
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (address) {
addr.sin_addr.s_addr = inet_addr(address);
} else {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("ListenAtTcpPort: socket\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(const char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPort: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
rfbClientErr("ListenAtTcpPort: bind\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
#else
int rv;
struct addrinfo hints, *servinfo, *p;
char port_str[8];
snprintf(port_str, 8, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; /* fill in wildcard address if address == NULL */
if ((rv = getaddrinfo(address, port_str, &hints, &servinfo)) != 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in getaddrinfo: %s\n", gai_strerror(rv));
return RFB_INVALID_SOCKET;
}
/* loop through all the results and bind to the first we can */
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == RFB_INVALID_SOCKET) {
continue;
}
#ifdef IPV6_V6ONLY
/* we have separate IPv4 and IPv6 sockets since some OS's do not support dual binding */
if (p->ai_family == AF_INET6 && setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in setsockopt IPV6_V6ONLY: %s\n", strerror(errno));
rfbCloseSocket(sock);
freeaddrinfo(servinfo);
return RFB_INVALID_SOCKET;
}
#endif
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in setsockopt SO_REUSEADDR: %s\n", strerror(errno));
rfbCloseSocket(sock);
freeaddrinfo(servinfo);
return RFB_INVALID_SOCKET;
}
if (bind(sock, p->ai_addr, p->ai_addrlen) < 0) {
rfbCloseSocket(sock);
continue;
}
break;
}
if (p == NULL) {
rfbClientErr("ListenAtTcpPortAndAddress: error in bind: %s\n", strerror(errno));
return RFB_INVALID_SOCKET;
}
/* all done with this structure now */
freeaddrinfo(servinfo);
#endif
if (listen(sock, 5) < 0) {
rfbClientErr("ListenAtTcpPort: listen\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
/*
* AcceptTcpConnection accepts a TCP connection.
*/
rfbSocket
AcceptTcpConnection(rfbSocket listenSock)
{
rfbSocket sock;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int one = 1;
sock = accept(listenSock, (struct sockaddr *) &addr, &addrlen);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("AcceptTcpConnection: accept\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("AcceptTcpConnection: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
/*
* SetNonBlocking sets a socket into non-blocking mode.
*/
rfbBool
SetNonBlocking(rfbSocket sock)
{
#ifdef WIN32
unsigned long block=1;
if(ioctlsocket(sock, FIONBIO, &block) == SOCKET_ERROR) {
errno=WSAGetLastError();
#else
int flags = fcntl(sock, F_GETFL);
if(flags < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
#endif
rfbClientErr("Setting socket to non-blocking failed: %s\n",strerror(errno));
return FALSE;
}
return TRUE;
}
rfbBool SetBlocking(rfbSocket sock)
{
#ifdef WIN32
unsigned long block=0;
if(ioctlsocket(sock, FIONBIO, &block) == SOCKET_ERROR) {
errno=WSAGetLastError();
#else
int flags = fcntl(sock, F_GETFL);
if(flags < 0 || fcntl(sock, F_SETFL, flags & ~O_NONBLOCK) < 0) {
#endif
rfbClientErr("Setting socket to blocking failed: %s\n",strerror(errno));
return FALSE;
}
return TRUE;
}
/*
* SetDSCP sets a socket's IP QoS parameters aka Differentiated Services Code Point field
*/
rfbBool
SetDSCP(rfbSocket sock, int dscp)
{
#ifdef WIN32
rfbClientErr("Setting of QoS IP DSCP not implemented for Windows\n");
return TRUE;
#else
int level, cmd;
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
if(getsockname(sock, &addr, &addrlen) != 0) {
rfbClientErr("Setting socket QoS failed while getting socket address: %s\n",strerror(errno));
return FALSE;
}
switch(addr.sa_family)
{
#if defined LIBVNCSERVER_IPv6 && defined IPV6_TCLASS
case AF_INET6:
level = IPPROTO_IPV6;
cmd = IPV6_TCLASS;
break;
#endif
case AF_INET:
level = IPPROTO_IP;
cmd = IP_TOS;
break;
default:
rfbClientErr("Setting socket QoS failed: Not bound to IP address");
return FALSE;
}
if(setsockopt(sock, level, cmd, (void*)&dscp, sizeof(dscp)) != 0) {
rfbClientErr("Setting socket QoS failed: %s\n", strerror(errno));
return FALSE;
}
return TRUE;
#endif
}
/*
* StringToIPAddr - convert a host string to an IP address.
*/
rfbBool
StringToIPAddr(const char *str, unsigned int *addr)
{
struct hostent *hp;
if (strcmp(str,"") == 0) {
*addr = htonl(INADDR_LOOPBACK); /* local */
return TRUE;
}
*addr = inet_addr(str);
if (*addr != -1)
return TRUE;
hp = gethostbyname(str);
if (hp) {
*addr = *(unsigned int *)hp->h_addr;
return TRUE;
}
return FALSE;
}
/*
* Test if the other end of a socket is on the same machine.
*/
rfbBool
SameMachine(rfbSocket sock)
{
struct sockaddr_in peeraddr, myaddr;
socklen_t addrlen = sizeof(struct sockaddr_in);
getpeername(sock, (struct sockaddr *)&peeraddr, &addrlen);
getsockname(sock, (struct sockaddr *)&myaddr, &addrlen);
return (peeraddr.sin_addr.s_addr == myaddr.sin_addr.s_addr);
}
/*
* Print out the contents of a packet for debugging.
*/
void
PrintInHex(char *buf, int len)
{
int i, j;
char c, str[17];
str[16] = 0;
rfbClientLog("ReadExact: ");
for (i = 0; i < len; i++)
{
if ((i % 16 == 0) && (i != 0)) {
rfbClientLog(" ");
}
c = buf[i];
str[i % 16] = (((c > 31) && (c < 127)) ? c : '.');
rfbClientLog("%02x ",(unsigned char)c);
if ((i % 4) == 3)
rfbClientLog(" ");
if ((i % 16) == 15)
{
rfbClientLog("%s\n",str);
}
}
if ((i % 16) != 0)
{
for (j = i % 16; j < 16; j++)
{
rfbClientLog(" ");
if ((j % 4) == 3) rfbClientLog(" ");
}
str[i % 16] = 0;
rfbClientLog("%s\n",str);
}
fflush(stderr);
}
int WaitForMessage(rfbClient* client,unsigned int usecs)
{
fd_set fds;
struct timeval timeout;
int num;
if (client->serverPort==-1)
/* playing back vncrec file */
return 1;
timeout.tv_sec=(usecs/1000000);
timeout.tv_usec=(usecs%1000000);
FD_ZERO(&fds);
FD_SET(client->sock,&fds);
num=select(client->sock+1, &fds, NULL, NULL, &timeout);
if(num<0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbClientLog("Waiting for message failed: %d (%s)\n",errno,strerror(errno));
}
return num;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_4059_0 |
crossvul-cpp_data_bad_505_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colormap-private.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/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/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__)
#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
/*
Enumerated declaractions.
*/
typedef enum
{
UndefinedSubtype,
RGB555,
RGB565,
ARGB4444,
ARGB1555
} BMPSubtype;
/*
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;
long
colorspace;
PrimaryInfo
red_primary,
green_primary,
blue_primary,
gamma_scale;
} BMPInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteBMPImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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,const size_t number_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.
%
% o number_pixels: The number of pixels.
%
*/
static MagickBooleanType DecodeImage(Image *image,const size_t compression,
unsigned char *pixels,const size_t number_pixels)
{
int
byte,
count;
register ssize_t
i,
x;
register unsigned char
*p,
*q;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
(void) memset(pixels,0,number_pixels*sizeof(*pixels));
byte=0;
x=0;
p=pixels;
q=pixels+number_pixels;
for (y=0; y < (ssize_t) image->rows; )
{
MagickBooleanType
status;
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=ReadBlobByte(image);
if (byte == EOF)
break;
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 == EOF)
break;
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++)
{
byte=ReadBlobByte(image);
if (byte == EOF)
break;
*p++=(unsigned char) byte;
}
else
for (i=0; i < (ssize_t) count; i++)
{
if ((i & 0x01) == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
break;
}
*p++=(unsigned char)
((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
}
x+=count;
/*
Read pad byte.
*/
if (compression == BI_RLE8)
{
if ((count & 0x01) != 0)
if (ReadBlobByte(image) == EOF)
break;
}
else
if (((count & 0x03) == 1) || ((count & 0x03) == 2))
if (ReadBlobByte(image) == EOF)
break;
break;
}
}
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) ReadBlobByte(image); /* end of line */
(void) ReadBlobByte(image);
return(y < (ssize_t) image->rows ? MagickFalse : 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 == MagickCoreSignature);
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;
MagickBooleanType
status;
MagickOffsetType
offset,
start_position;
MemoryInfo
*pixel_info;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
bytes_per_line,
length;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
unsigned int
blue,
green,
offset_bits,
red;
/*
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);
}
/*
Determine if this a BMP file.
*/
(void) memset(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
offset_bits=0;
count=ReadBlob(image,2,magick);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
PixelInfo
quantum_bits;
PixelPacket
shift;
/*
Verify BMP identifier.
*/
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 != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
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",MagickPathExtent);
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) ReadBlobLSBSignedLong(image);
bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(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);
if (bmp_info.number_colors > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
bmp_info.colors_important=ReadBlobLSBLong(image);
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 (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
gamma;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=ReadBlobLSBSignedLong(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;
gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.red_primary.x*=gamma;
bmp_info.red_primary.y*=gamma;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.green_primary.x*=gamma;
bmp_info.green_primary.y*=gamma;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.blue_primary.x*=gamma;
bmp_info.blue_primary.y*=gamma;
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",MagickPathExtent);
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;
}
}
(void) ReadBlobLSBLong(image); /* Profile data */
(void) ReadBlobLSBLong(image); /* 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:
image->compression=NoCompression;
break;
case BI_RLE8:
case BI_RLE4:
image->compression=RLECompression;
break;
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->alpha_trait=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :
UndefinedPixelTrait;
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;
}
image->resolution.x=(double) bmp_info.x_pixels/100.0;
image->resolution.y=(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;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
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,exception) == 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)
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
/*
Read image data.
*/
if (bmp_info.offset_bits == offset_bits)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset_bits=bmp_info.offset_bits;
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;
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
if ((MagickSizeType) length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
pixel_info=AcquireVirtualMemory(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 (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.
*/
pixel_info=AcquireVirtualMemory(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);
status=DecodeImage(image,bmp_info.compression,pixels,
image->columns*image->rows);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
/*
We should ignore the alpha value in BMP3 files but there have been
reports about 32 bit files with alpha. We do a quick check to see if
the alpha channel contains a value that is not zero (default value).
If we find a non zero value we asume the program that wrote the file
wants to use the alpha channel.
*/
if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&
(bmp_info.bits_per_pixel == 32))
{
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (*(p+3) != 0)
{
image->alpha_trait=BlendPixelTrait;
y=-1;
break;
}
p+=4;
}
}
}
bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?
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;
}
}
(void) memset(&shift,0,sizeof(shift));
(void) memset(&quantum_bits,0,sizeof(quantum_bits));
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register unsigned int
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
{
shift.red++;
if (shift.red >= 32U)
break;
}
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
{
shift.green++;
if (shift.green >= 32U)
break;
}
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
{
shift.blue++;
if (shift.blue >= 32U)
break;
}
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
{
shift.alpha++;
if (shift.alpha >= 32U)
break;
}
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.red=(MagickRealType) (sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.green=(MagickRealType) (sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.blue=(MagickRealType) (sample-shift.blue);
sample=shift.alpha;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
}
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 == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
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,exception);
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 == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
x++;
}
if (x < (ssize_t) image->columns)
break;
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,exception);
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 == (Quantum *) NULL)
break;
for (x=(ssize_t) image->columns; x != 0; --x)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
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,exception);
break;
}
case 16:
{
unsigned int
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 == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*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);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
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 == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
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--)
{
unsigned int
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=((unsigned int) *p++ << 8);
pixel|=((unsigned int) *p++ << 16);
pixel|=((unsigned int) *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);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha == 8)
alpha|=(alpha >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
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 (y > 0)
break;
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);
ReplaceImageInList(&image, flipped_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,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
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);
if (status == MagickFalse)
return(DestroyImageList(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=AcquireMagickInfo("BMP","BMP","Microsoft Windows bitmap image");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("BMP","BMP2","Microsoft Windows bitmap image (V2)");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("BMP","BMP3","Microsoft Windows bitmap image (V3)");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(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,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 WriteBMPImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
BMPInfo
bmp_info;
BMPSubtype
bmp_subtype;
const char
*option;
const StringInfo
*profile;
MagickBooleanType
have_color_info,
status;
MagickOffsetType
scene;
MemoryInfo
*pixel_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
bytes_per_line,
imageListLength,
type;
ssize_t
y;
unsigned char
*bmp_data,
*pixels;
/*
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);
type=4;
if (LocaleCompare(image_info->magick,"BMP2") == 0)
type=2;
else
if (LocaleCompare(image_info->magick,"BMP3") == 0)
type=3;
option=GetImageOption(image_info,"bmp:format");
if (option != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",option);
if (LocaleCompare(option,"bmp2") == 0)
type=2;
if (LocaleCompare(option,"bmp3") == 0)
type=3;
if (LocaleCompare(option,"bmp4") == 0)
type=4;
}
scene=0;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize BMP raster file header.
*/
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) memset(&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;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
bmp_info.alpha_mask=0xff000000U;
bmp_subtype=UndefinedSubtype;
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass,exception);
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->alpha_trait != UndefinedPixelTrait)
(void) SetImageStorageClass(image,DirectClass,exception);
else
if ((size_t) bmp_info.number_colors < image->colors)
(void) SetImageStorageClass(image,DirectClass,exception);
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;
option=GetImageOption(image_info,"bmp:subtype");
if (option != (const char *) NULL)
{
if (image->alpha_trait != UndefinedPixelTrait)
{
if (LocaleNCompare(option,"ARGB4444",8) == 0)
{
bmp_subtype=ARGB4444;
bmp_info.red_mask=0x00000f00U;
bmp_info.green_mask=0x000000f0U;
bmp_info.blue_mask=0x0000000fU;
bmp_info.alpha_mask=0x0000f000U;
}
else if (LocaleNCompare(option,"ARGB1555",8) == 0)
{
bmp_subtype=ARGB1555;
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0x00008000U;
}
}
else
{
if (LocaleNCompare(option,"RGB555",6) == 0)
{
bmp_subtype=RGB555;
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0U;
}
else if (LocaleNCompare(option,"RGB565",6) == 0)
{
bmp_subtype=RGB565;
bmp_info.red_mask=0x0000f800U;
bmp_info.green_mask=0x000007e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0U;
}
}
}
if (bmp_subtype != UndefinedSubtype)
{
bmp_info.bits_per_pixel=16;
bmp_info.compression=BI_BITFIELDS;
}
else
{
bmp_info.bits_per_pixel=(unsigned short) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? 32 : 24);
bmp_info.compression=(unsigned int) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB);
if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait))
{
option=GetImageOption(image_info,"bmp3:alpha");
if (IsStringTrue(option))
bmp_info.bits_per_pixel=32;
}
}
}
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->alpha_trait == UndefinedPixelTrait) &&
(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;
}
if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) ||
((ssize_t) image->rows != (ssize_t) ((signed int) image->rows)))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
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->resolution.x/2.54);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
break;
}
case PixelsPerCentimeterResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
break;
}
}
bmp_info.colors_important=bmp_info.number_colors;
/*
Convert MIFF to BMP raster pixels.
*/
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(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++)
{
ssize_t
offset;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
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(image,p) != 0 ? 0x01 : 0x00;
bit++;
if (bit == 8)
{
*q++=(unsigned char) byte;
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
*q++=(unsigned char) (byte << (8-bit));
x++;
}
offset=(ssize_t) (image->columns+7)/8;
for (x=offset; 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:
{
unsigned int
byte,
nibble;
ssize_t
offset;
/*
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,exception);
if (p == (const Quantum *) NULL)
break;
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|=((unsigned int) GetPixelIndex(image,p) & 0x0f);
nibble++;
if (nibble == 2)
{
*q++=(unsigned char) byte;
nibble=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (nibble != 0)
{
*q++=(unsigned char) (byte << 4);
x++;
}
offset=(ssize_t) (image->columns+1)/2;
for (x=offset; 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,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
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 16:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
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+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
unsigned short
pixel;
pixel=0;
if (bmp_subtype == ARGB4444)
{
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelAlpha(image,p),15) << 12);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),15) << 8);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),15) << 4);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),15));
}
else if (bmp_subtype == RGB565)
{
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),31) << 11);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),63) << 5);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),31));
}
else
{
if (bmp_subtype == ARGB1555)
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelAlpha(image,p),1) << 15);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),31) << 10);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),31) << 5);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),31));
}
*((unsigned short *) q)=pixel;
q+=2;
p+=GetPixelChannels(image);
}
for (x=2L*(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 24:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
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+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
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,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
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->alpha_trait != UndefinedPixelTrait)
(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) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);
(void) WriteBlobLSBSignedShort(image,(signed 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) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width);
(void) WriteBlobLSBSignedLong(image,(signed 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->alpha_trait != UndefinedPixelTrait) ||
(have_color_info != MagickFalse)))
{
/*
Write the rest of the 108-byte BMP Version 4 header.
*/
(void) WriteBlobLSBLong(image,bmp_info.red_mask);
(void) WriteBlobLSBLong(image,bmp_info.green_mask);
(void) WriteBlobLSBLong(image,bmp_info.blue_mask);
(void) WriteBlobLSBLong(image,bmp_info.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(ClampToQuantum(image->colormap[i].blue));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
*q++=ScaleQuantumToChar(ClampToQuantum(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++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_505_0 |
crossvul-cpp_data_good_2782_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.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/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/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MaxTextExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p,
text[MaxTextExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
if ((max_value == 0) || (max_value > 4294967295))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("SPARSE-COLOR");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Sparse Color");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TEXT");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Text");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TXT");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->description=ConstantString("Text");
entry->magick=(IsImageFormatHandler *) IsTXT;
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
colorspace[MaxTextExtent],
tuple[MaxTextExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
/*
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,WriteBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MaxTextExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->matte != MagickFalse)
(void) ConcatenateMagickString(colorspace,"a",MaxTextExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MaxTextExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetMagickPixelPacket(image,&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);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelOpacity(p) == (Quantum) OpaqueOpacity)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g,",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p++;
continue;
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g: ",(double)
x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MaxTextExtent);
ConcatenateColorComponent(&pixel,RedChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,GreenChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,BlueChannel,compliance,tuple);
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,IndexChannel,compliance,tuple);
}
if (pixel.matte != MagickFalse)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,AlphaChannel,compliance,tuple);
}
(void) ConcatenateMagickString(tuple,")",MaxTextExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MaxTextExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p++;
}
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-835/c/good_2782_0 |
crossvul-cpp_data_good_2765_1 | /*
* Apple HTTP Live Streaming demuxer
* Copyright (c) 2010 Martin Storsjo
* Copyright (c) 2013 Anssi Hannula
*
* 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
* Apple HTTP Live Streaming demuxer
* http://tools.ietf.org/html/draft-pantos-http-live-streaming
*/
#include "libavutil/avstring.h"
#include "libavutil/avassert.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/time.h"
#include "avformat.h"
#include "internal.h"
#include "avio_internal.h"
#include "id3v2.h"
#define INITIAL_BUFFER_SIZE 32768
#define MAX_FIELD_LEN 64
#define MAX_CHARACTERISTICS_LEN 512
#define MPEG_TIME_BASE 90000
#define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
/*
* An apple http stream consists of a playlist with media segment files,
* played sequentially. There may be several playlists with the same
* video content, in different bandwidth variants, that are played in
* parallel (preferably only one bandwidth variant at a time). In this case,
* the user supplied the url to a main playlist that only lists the variant
* playlists.
*
* If the main playlist doesn't point at any variants, we still create
* one anonymous toplevel variant for this, to maintain the structure.
*/
enum KeyType {
KEY_NONE,
KEY_AES_128,
KEY_SAMPLE_AES
};
struct segment {
int64_t duration;
int64_t url_offset;
int64_t size;
char *url;
char *key;
enum KeyType key_type;
uint8_t iv[16];
/* associated Media Initialization Section, treated as a segment */
struct segment *init_section;
};
struct rendition;
enum PlaylistType {
PLS_TYPE_UNSPECIFIED,
PLS_TYPE_EVENT,
PLS_TYPE_VOD
};
/*
* Each playlist has its own demuxer. If it currently is active,
* it has an open AVIOContext too, and potentially an AVPacket
* containing the next packet from this stream.
*/
struct playlist {
char url[MAX_URL_SIZE];
AVIOContext pb;
uint8_t* read_buffer;
AVIOContext *input;
AVFormatContext *parent;
int index;
AVFormatContext *ctx;
AVPacket pkt;
int has_noheader_flag;
/* main demuxer streams associated with this playlist
* indexed by the subdemuxer stream indexes */
AVStream **main_streams;
int n_main_streams;
int finished;
enum PlaylistType type;
int64_t target_duration;
int start_seq_no;
int n_segments;
struct segment **segments;
int needed, cur_needed;
int cur_seq_no;
int64_t cur_seg_offset;
int64_t last_load_time;
/* Currently active Media Initialization Section */
struct segment *cur_init_section;
uint8_t *init_sec_buf;
unsigned int init_sec_buf_size;
unsigned int init_sec_data_len;
unsigned int init_sec_buf_read_offset;
char key_url[MAX_URL_SIZE];
uint8_t key[16];
/* ID3 timestamp handling (elementary audio streams have ID3 timestamps
* (and possibly other ID3 tags) in the beginning of each segment) */
int is_id3_timestamped; /* -1: not yet known */
int64_t id3_mpegts_timestamp; /* in mpegts tb */
int64_t id3_offset; /* in stream original tb */
uint8_t* id3_buf; /* temp buffer for id3 parsing */
unsigned int id3_buf_size;
AVDictionary *id3_initial; /* data from first id3 tag */
int id3_found; /* ID3 tag found at some point */
int id3_changed; /* ID3 tag data has changed at some point */
ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
int64_t seek_timestamp;
int seek_flags;
int seek_stream_index; /* into subdemuxer stream array */
/* Renditions associated with this playlist, if any.
* Alternative rendition playlists have a single rendition associated
* with them, and variant main Media Playlists may have
* multiple (playlist-less) renditions associated with them. */
int n_renditions;
struct rendition **renditions;
/* Media Initialization Sections (EXT-X-MAP) associated with this
* playlist, if any. */
int n_init_sections;
struct segment **init_sections;
};
/*
* Renditions are e.g. alternative subtitle or audio streams.
* The rendition may either be an external playlist or it may be
* contained in the main Media Playlist of the variant (in which case
* playlist is NULL).
*/
struct rendition {
enum AVMediaType type;
struct playlist *playlist;
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
int disposition;
};
struct variant {
int bandwidth;
/* every variant contains at least the main Media Playlist in index 0 */
int n_playlists;
struct playlist **playlists;
char audio_group[MAX_FIELD_LEN];
char video_group[MAX_FIELD_LEN];
char subtitles_group[MAX_FIELD_LEN];
};
typedef struct HLSContext {
AVClass *class;
AVFormatContext *ctx;
int n_variants;
struct variant **variants;
int n_playlists;
struct playlist **playlists;
int n_renditions;
struct rendition **renditions;
int cur_seq_no;
int live_start_index;
int first_packet;
int64_t first_timestamp;
int64_t cur_timestamp;
AVIOInterruptCB *interrupt_callback;
char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
char *http_proxy; ///< holds the address of the HTTP proxy server
AVDictionary *avio_opts;
int strict_std_compliance;
char *allowed_extensions;
int max_reload;
} HLSContext;
static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
{
int len = ff_get_line(s, buf, maxlen);
while (len > 0 && av_isspace(buf[len - 1]))
buf[--len] = '\0';
return len;
}
static void free_segment_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_segments; i++) {
av_freep(&pls->segments[i]->key);
av_freep(&pls->segments[i]->url);
av_freep(&pls->segments[i]);
}
av_freep(&pls->segments);
pls->n_segments = 0;
}
static void free_init_section_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_init_sections; i++) {
av_freep(&pls->init_sections[i]->url);
av_freep(&pls->init_sections[i]);
}
av_freep(&pls->init_sections);
pls->n_init_sections = 0;
}
static void free_playlist_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
free_segment_list(pls);
free_init_section_list(pls);
av_freep(&pls->main_streams);
av_freep(&pls->renditions);
av_freep(&pls->id3_buf);
av_dict_free(&pls->id3_initial);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
av_freep(&pls->init_sec_buf);
av_packet_unref(&pls->pkt);
av_freep(&pls->pb.buffer);
if (pls->input)
ff_format_io_close(c->ctx, &pls->input);
if (pls->ctx) {
pls->ctx->pb = NULL;
avformat_close_input(&pls->ctx);
}
av_free(pls);
}
av_freep(&c->playlists);
av_freep(&c->cookies);
av_freep(&c->user_agent);
av_freep(&c->headers);
av_freep(&c->http_proxy);
c->n_playlists = 0;
}
static void free_variant_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
av_freep(&var->playlists);
av_free(var);
}
av_freep(&c->variants);
c->n_variants = 0;
}
static void free_rendition_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_renditions; i++)
av_freep(&c->renditions[i]);
av_freep(&c->renditions);
c->n_renditions = 0;
}
/*
* Used to reset a statically allocated AVPacket to a clean slate,
* containing no data.
*/
static void reset_packet(AVPacket *pkt)
{
av_init_packet(pkt);
pkt->data = NULL;
}
static struct playlist *new_playlist(HLSContext *c, const char *url,
const char *base)
{
struct playlist *pls = av_mallocz(sizeof(struct playlist));
if (!pls)
return NULL;
reset_packet(&pls->pkt);
ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
pls->seek_timestamp = AV_NOPTS_VALUE;
pls->is_id3_timestamped = -1;
pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
dynarray_add(&c->playlists, &c->n_playlists, pls);
return pls;
}
struct variant_info {
char bandwidth[20];
/* variant group ids: */
char audio[MAX_FIELD_LEN];
char video[MAX_FIELD_LEN];
char subtitles[MAX_FIELD_LEN];
};
static struct variant *new_variant(HLSContext *c, struct variant_info *info,
const char *url, const char *base)
{
struct variant *var;
struct playlist *pls;
pls = new_playlist(c, url, base);
if (!pls)
return NULL;
var = av_mallocz(sizeof(struct variant));
if (!var)
return NULL;
if (info) {
var->bandwidth = atoi(info->bandwidth);
strcpy(var->audio_group, info->audio);
strcpy(var->video_group, info->video);
strcpy(var->subtitles_group, info->subtitles);
}
dynarray_add(&c->variants, &c->n_variants, var);
dynarray_add(&var->playlists, &var->n_playlists, pls);
return var;
}
static void handle_variant_args(struct variant_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "BANDWIDTH=", key_len)) {
*dest = info->bandwidth;
*dest_len = sizeof(info->bandwidth);
} else if (!strncmp(key, "AUDIO=", key_len)) {
*dest = info->audio;
*dest_len = sizeof(info->audio);
} else if (!strncmp(key, "VIDEO=", key_len)) {
*dest = info->video;
*dest_len = sizeof(info->video);
} else if (!strncmp(key, "SUBTITLES=", key_len)) {
*dest = info->subtitles;
*dest_len = sizeof(info->subtitles);
}
}
struct key_info {
char uri[MAX_URL_SIZE];
char method[11];
char iv[35];
};
static void handle_key_args(struct key_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "METHOD=", key_len)) {
*dest = info->method;
*dest_len = sizeof(info->method);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "IV=", key_len)) {
*dest = info->iv;
*dest_len = sizeof(info->iv);
}
}
struct init_section_info {
char uri[MAX_URL_SIZE];
char byterange[32];
};
static struct segment *new_init_section(struct playlist *pls,
struct init_section_info *info,
const char *url_base)
{
struct segment *sec;
char *ptr;
char tmp_str[MAX_URL_SIZE];
if (!info->uri[0])
return NULL;
sec = av_mallocz(sizeof(*sec));
if (!sec)
return NULL;
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
sec->url = av_strdup(tmp_str);
if (!sec->url) {
av_free(sec);
return NULL;
}
if (info->byterange[0]) {
sec->size = strtoll(info->byterange, NULL, 10);
ptr = strchr(info->byterange, '@');
if (ptr)
sec->url_offset = strtoll(ptr+1, NULL, 10);
} else {
/* the entire file is the init section */
sec->size = -1;
}
dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
return sec;
}
static void handle_init_section_args(struct init_section_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "BYTERANGE=", key_len)) {
*dest = info->byterange;
*dest_len = sizeof(info->byterange);
}
}
struct rendition_info {
char type[16];
char uri[MAX_URL_SIZE];
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char assoc_language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
char defaultr[4];
char forced[4];
char characteristics[MAX_CHARACTERISTICS_LEN];
};
static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
const char *url_base)
{
struct rendition *rend;
enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
char *characteristic;
char *chr_ptr;
char *saveptr;
if (!strcmp(info->type, "AUDIO"))
type = AVMEDIA_TYPE_AUDIO;
else if (!strcmp(info->type, "VIDEO"))
type = AVMEDIA_TYPE_VIDEO;
else if (!strcmp(info->type, "SUBTITLES"))
type = AVMEDIA_TYPE_SUBTITLE;
else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
/* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
* AVC SEI RBSP anyway */
return NULL;
if (type == AVMEDIA_TYPE_UNKNOWN)
return NULL;
/* URI is mandatory for subtitles as per spec */
if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
return NULL;
/* TODO: handle subtitles (each segment has to parsed separately) */
if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
if (type == AVMEDIA_TYPE_SUBTITLE)
return NULL;
rend = av_mallocz(sizeof(struct rendition));
if (!rend)
return NULL;
dynarray_add(&c->renditions, &c->n_renditions, rend);
rend->type = type;
strcpy(rend->group_id, info->group_id);
strcpy(rend->language, info->language);
strcpy(rend->name, info->name);
/* add the playlist if this is an external rendition */
if (info->uri[0]) {
rend->playlist = new_playlist(c, info->uri, url_base);
if (rend->playlist)
dynarray_add(&rend->playlist->renditions,
&rend->playlist->n_renditions, rend);
}
if (info->assoc_language[0]) {
int langlen = strlen(rend->language);
if (langlen < sizeof(rend->language) - 3) {
rend->language[langlen] = ',';
strncpy(rend->language + langlen + 1, info->assoc_language,
sizeof(rend->language) - langlen - 2);
}
}
if (!strcmp(info->defaultr, "YES"))
rend->disposition |= AV_DISPOSITION_DEFAULT;
if (!strcmp(info->forced, "YES"))
rend->disposition |= AV_DISPOSITION_FORCED;
chr_ptr = info->characteristics;
while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
else if (!strcmp(characteristic, "public.accessibility.describes-video"))
rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
chr_ptr = NULL;
}
return rend;
}
static void handle_rendition_args(struct rendition_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "TYPE=", key_len)) {
*dest = info->type;
*dest_len = sizeof(info->type);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "GROUP-ID=", key_len)) {
*dest = info->group_id;
*dest_len = sizeof(info->group_id);
} else if (!strncmp(key, "LANGUAGE=", key_len)) {
*dest = info->language;
*dest_len = sizeof(info->language);
} else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
*dest = info->assoc_language;
*dest_len = sizeof(info->assoc_language);
} else if (!strncmp(key, "NAME=", key_len)) {
*dest = info->name;
*dest_len = sizeof(info->name);
} else if (!strncmp(key, "DEFAULT=", key_len)) {
*dest = info->defaultr;
*dest_len = sizeof(info->defaultr);
} else if (!strncmp(key, "FORCED=", key_len)) {
*dest = info->forced;
*dest_len = sizeof(info->forced);
} else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
*dest = info->characteristics;
*dest_len = sizeof(info->characteristics);
}
/*
* ignored:
* - AUTOSELECT: client may autoselect based on e.g. system language
* - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
*/
}
/* used by parse_playlist to allocate a new variant+playlist when the
* playlist is detected to be a Media Playlist (not Master Playlist)
* and we have no parent Master Playlist (parsing of which would have
* allocated the variant and playlist already)
* *pls == NULL => Master Playlist or parentless Media Playlist
* *pls != NULL => parented Media Playlist, playlist+variant allocated */
static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
{
if (*pls)
return 0;
if (!new_variant(c, NULL, url, NULL))
return AVERROR(ENOMEM);
*pls = c->playlists[c->n_playlists - 1];
return 0;
}
static void update_options(char **dest, const char *name, void *src)
{
av_freep(dest);
av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
if (*dest && !strlen(*dest))
av_freep(dest);
}
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
AVDictionary *opts, AVDictionary *opts2, int *is_http)
{
HLSContext *c = s->priv_data;
AVDictionary *tmp = NULL;
const char *proto_name = NULL;
int ret;
av_dict_copy(&tmp, opts, 0);
av_dict_copy(&tmp, opts2, 0);
if (av_strstart(url, "crypto", NULL)) {
if (url[6] == '+' || url[6] == ':')
proto_name = avio_find_protocol_name(url + 7);
}
if (!proto_name)
proto_name = avio_find_protocol_name(url);
if (!proto_name)
return AVERROR_INVALIDDATA;
// only http(s) & file are allowed
if (av_strstart(proto_name, "file", NULL)) {
if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
av_log(s, AV_LOG_ERROR,
"Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
"If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
url);
return AVERROR_INVALIDDATA;
}
} else if (av_strstart(proto_name, "http", NULL)) {
;
} else
return AVERROR_INVALIDDATA;
if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
;
else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
;
else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
return AVERROR_INVALIDDATA;
ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
if (ret >= 0) {
// update cookies on http response with setcookies.
char *new_cookies = NULL;
if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
if (new_cookies) {
av_free(c->cookies);
c->cookies = new_cookies;
}
av_dict_set(&opts, "cookies", c->cookies, 0);
}
av_dict_free(&tmp);
if (is_http)
*is_http = av_strstart(proto_name, "http", NULL);
return ret;
}
static int parse_playlist(HLSContext *c, const char *url,
struct playlist *pls, AVIOContext *in)
{
int ret = 0, is_segment = 0, is_variant = 0;
int64_t duration = 0;
enum KeyType key_type = KEY_NONE;
uint8_t iv[16] = "";
int has_iv = 0;
char key[MAX_URL_SIZE] = "";
char line[MAX_URL_SIZE];
const char *ptr;
int close_in = 0;
int64_t seg_offset = 0;
int64_t seg_size = -1;
uint8_t *new_url = NULL;
struct variant_info variant_info;
char tmp_str[MAX_URL_SIZE];
struct segment *cur_init_section = NULL;
if (!in) {
#if 1
AVDictionary *opts = NULL;
close_in = 1;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&opts, "seekable", "0", 0);
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
av_dict_free(&opts);
if (ret < 0)
return ret;
#else
ret = open_in(c, &in, url);
if (ret < 0)
return ret;
close_in = 1;
#endif
}
if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
url = new_url;
read_chomp_line(in, line, sizeof(line));
if (strcmp(line, "#EXTM3U")) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (pls) {
free_segment_list(pls);
pls->finished = 0;
pls->type = PLS_TYPE_UNSPECIFIED;
}
while (!avio_feof(in)) {
read_chomp_line(in, line, sizeof(line));
if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
is_variant = 1;
memset(&variant_info, 0, sizeof(variant_info));
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
&variant_info);
} else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
struct key_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
&info);
key_type = KEY_NONE;
has_iv = 0;
if (!strcmp(info.method, "AES-128"))
key_type = KEY_AES_128;
if (!strcmp(info.method, "SAMPLE-AES"))
key_type = KEY_SAMPLE_AES;
if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
ff_hex_to_data(iv, info.iv + 2);
has_iv = 1;
}
av_strlcpy(key, info.uri, sizeof(key));
} else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
struct rendition_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
&info);
new_rendition(c, &info, url);
} else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->start_seq_no = atoi(ptr);
} else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
if (!strcmp(ptr, "EVENT"))
pls->type = PLS_TYPE_EVENT;
else if (!strcmp(ptr, "VOD"))
pls->type = PLS_TYPE_VOD;
} else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
struct init_section_info info = {{0}};
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
&info);
cur_init_section = new_init_section(pls, &info, url);
} else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
if (pls)
pls->finished = 1;
} else if (av_strstart(line, "#EXTINF:", &ptr)) {
is_segment = 1;
duration = atof(ptr) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
seg_size = strtoll(ptr, NULL, 10);
ptr = strchr(ptr, '@');
if (ptr)
seg_offset = strtoll(ptr+1, NULL, 10);
} else if (av_strstart(line, "#", NULL)) {
continue;
} else if (line[0]) {
if (is_variant) {
if (!new_variant(c, &variant_info, line, url)) {
ret = AVERROR(ENOMEM);
goto fail;
}
is_variant = 0;
}
if (is_segment) {
struct segment *seg;
if (!pls) {
if (!new_variant(c, 0, url, NULL)) {
ret = AVERROR(ENOMEM);
goto fail;
}
pls = c->playlists[c->n_playlists - 1];
}
seg = av_malloc(sizeof(struct segment));
if (!seg) {
ret = AVERROR(ENOMEM);
goto fail;
}
seg->duration = duration;
seg->key_type = key_type;
if (has_iv) {
memcpy(seg->iv, iv, sizeof(iv));
} else {
int seq = pls->start_seq_no + pls->n_segments;
memset(seg->iv, 0, sizeof(seg->iv));
AV_WB32(seg->iv + 12, seq);
}
if (key_type != KEY_NONE) {
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
seg->key = av_strdup(tmp_str);
if (!seg->key) {
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
} else {
seg->key = NULL;
}
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
seg->url = av_strdup(tmp_str);
if (!seg->url) {
av_free(seg->key);
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
dynarray_add(&pls->segments, &pls->n_segments, seg);
is_segment = 0;
seg->size = seg_size;
if (seg_size >= 0) {
seg->url_offset = seg_offset;
seg_offset += seg_size;
seg_size = -1;
} else {
seg->url_offset = 0;
seg_offset = 0;
}
seg->init_section = cur_init_section;
}
}
}
if (pls)
pls->last_load_time = av_gettime_relative();
fail:
av_free(new_url);
if (close_in)
ff_format_io_close(c->ctx, &in);
return ret;
}
static struct segment *current_segment(struct playlist *pls)
{
return pls->segments[pls->cur_seq_no - pls->start_seq_no];
}
enum ReadFromURLMode {
READ_NORMAL,
READ_COMPLETE,
};
static int read_from_url(struct playlist *pls, struct segment *seg,
uint8_t *buf, int buf_size,
enum ReadFromURLMode mode)
{
int ret;
/* limit read if the segment was only a part of a file */
if (seg->size >= 0)
buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
if (mode == READ_COMPLETE) {
ret = avio_read(pls->input, buf, buf_size);
if (ret != buf_size)
av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
} else
ret = avio_read(pls->input, buf, buf_size);
if (ret > 0)
pls->cur_seg_offset += ret;
return ret;
}
/* Parse the raw ID3 data and pass contents to caller */
static void parse_id3(AVFormatContext *s, AVIOContext *pb,
AVDictionary **metadata, int64_t *dts,
ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
{
static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
ID3v2ExtraMeta *meta;
ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
for (meta = *extra_meta; meta; meta = meta->next) {
if (!strcmp(meta->tag, "PRIV")) {
ID3v2ExtraMetaPRIV *priv = meta->data;
if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
/* 33-bit MPEG timestamp */
int64_t ts = AV_RB64(priv->data);
av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
if ((ts & ~((1ULL << 33) - 1)) == 0)
*dts = ts;
else
av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
}
} else if (!strcmp(meta->tag, "APIC") && apic)
*apic = meta->data;
}
}
/* Check if the ID3 metadata contents have changed */
static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
ID3v2ExtraMetaAPIC *apic)
{
AVDictionaryEntry *entry = NULL;
AVDictionaryEntry *oldentry;
/* check that no keys have changed values */
while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
return 1;
}
/* check if apic appeared */
if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
return 1;
if (apic) {
int size = pls->ctx->streams[1]->attached_pic.size;
if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
return 1;
if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
return 1;
}
return 0;
}
/* Parse ID3 data and handle the found data */
static void handle_id3(AVIOContext *pb, struct playlist *pls)
{
AVDictionary *metadata = NULL;
ID3v2ExtraMetaAPIC *apic = NULL;
ID3v2ExtraMeta *extra_meta = NULL;
int64_t timestamp = AV_NOPTS_VALUE;
parse_id3(pls->ctx, pb, &metadata, ×tamp, &apic, &extra_meta);
if (timestamp != AV_NOPTS_VALUE) {
pls->id3_mpegts_timestamp = timestamp;
pls->id3_offset = 0;
}
if (!pls->id3_found) {
/* initial ID3 tags */
av_assert0(!pls->id3_deferred_extra);
pls->id3_found = 1;
/* get picture attachment and set text metadata */
if (pls->ctx->nb_streams)
ff_id3v2_parse_apic(pls->ctx, &extra_meta);
else
/* demuxer not yet opened, defer picture attachment */
pls->id3_deferred_extra = extra_meta;
av_dict_copy(&pls->ctx->metadata, metadata, 0);
pls->id3_initial = metadata;
} else {
if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
pls->id3_changed = 1;
}
av_dict_free(&metadata);
}
if (!pls->id3_deferred_extra)
ff_id3v2_free_extra_meta(&extra_meta);
}
static void intercept_id3(struct playlist *pls, uint8_t *buf,
int buf_size, int *len)
{
/* intercept id3 tags, we do not want to pass them to the raw
* demuxer on all segment switches */
int bytes;
int id3_buf_pos = 0;
int fill_buf = 0;
struct segment *seg = current_segment(pls);
/* gather all the id3 tags */
while (1) {
/* see if we can retrieve enough data for ID3 header */
if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
if (bytes > 0) {
if (bytes == ID3v2_HEADER_SIZE - *len)
/* no EOF yet, so fill the caller buffer again after
* we have stripped the ID3 tags */
fill_buf = 1;
*len += bytes;
} else if (*len <= 0) {
/* error/EOF */
*len = bytes;
fill_buf = 0;
}
}
if (*len < ID3v2_HEADER_SIZE)
break;
if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
int taglen = ff_id3v2_tag_len(buf);
int tag_got_bytes = FFMIN(taglen, *len);
int remaining = taglen - tag_got_bytes;
if (taglen > maxsize) {
av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
taglen, maxsize);
break;
}
/*
* Copy the id3 tag to our temporary id3 buffer.
* We could read a small id3 tag directly without memcpy, but
* we would still need to copy the large tags, and handling
* both of those cases together with the possibility for multiple
* tags would make the handling a bit complex.
*/
pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
if (!pls->id3_buf)
break;
memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
id3_buf_pos += tag_got_bytes;
/* strip the intercepted bytes */
*len -= tag_got_bytes;
memmove(buf, buf + tag_got_bytes, *len);
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
if (remaining > 0) {
/* read the rest of the tag in */
if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
break;
id3_buf_pos += remaining;
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
}
} else {
/* no more ID3 tags */
break;
}
}
/* re-fill buffer for the caller unless EOF */
if (*len >= 0 && (fill_buf || *len == 0)) {
bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
/* ignore error if we already had some data */
if (bytes >= 0)
*len += bytes;
else if (*len == 0)
*len = bytes;
}
if (pls->id3_buf) {
/* Now parse all the ID3 tags */
AVIOContext id3ioctx;
ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
handle_id3(&id3ioctx, pls);
}
if (pls->is_id3_timestamped == -1)
pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
}
static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
{
AVDictionary *opts = NULL;
int ret;
int is_http = 0;
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
av_dict_set(&opts, "seekable", "0", 0);
if (seg->size >= 0) {
/* try to restrict the HTTP request to the part we want
* (if this is in fact a HTTP request) */
av_dict_set_int(&opts, "offset", seg->url_offset, 0);
av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
}
av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
seg->url, seg->url_offset, pls->index);
if (seg->key_type == KEY_NONE) {
ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts, &is_http);
} else if (seg->key_type == KEY_AES_128) {
AVDictionary *opts2 = NULL;
char iv[33], key[33], url[MAX_URL_SIZE];
if (strcmp(seg->key, pls->key_url)) {
AVIOContext *pb;
if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
ret = avio_read(pb, pls->key, sizeof(pls->key));
if (ret != sizeof(pls->key)) {
av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
seg->key);
}
ff_format_io_close(pls->parent, &pb);
} else {
av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
seg->key);
}
av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
}
ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
iv[32] = key[32] = '\0';
if (strstr(seg->url, "://"))
snprintf(url, sizeof(url), "crypto+%s", seg->url);
else
snprintf(url, sizeof(url), "crypto:%s", seg->url);
av_dict_copy(&opts2, c->avio_opts, 0);
av_dict_set(&opts2, "key", key, 0);
av_dict_set(&opts2, "iv", iv, 0);
ret = open_url(pls->parent, &pls->input, url, opts2, opts, &is_http);
av_dict_free(&opts2);
if (ret < 0) {
goto cleanup;
}
ret = 0;
} else if (seg->key_type == KEY_SAMPLE_AES) {
av_log(pls->parent, AV_LOG_ERROR,
"SAMPLE-AES encryption is not supported yet\n");
ret = AVERROR_PATCHWELCOME;
}
else
ret = AVERROR(ENOSYS);
/* Seek to the requested position. If this was a HTTP request, the offset
* should already be where want it to, but this allows e.g. local testing
* without a HTTP server.
*
* This is not done for HTTP at all as avio_seek() does internal bookkeeping
* of file offset which is out-of-sync with the actual offset when "offset"
* AVOption is used with http protocol, causing the seek to not be a no-op
* as would be expected. Wrong offset received from the server will not be
* noticed without the call, though.
*/
if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
if (seekret < 0) {
av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
ret = seekret;
ff_format_io_close(pls->parent, &pls->input);
}
}
cleanup:
av_dict_free(&opts);
pls->cur_seg_offset = 0;
return ret;
}
static int update_init_section(struct playlist *pls, struct segment *seg)
{
static const int max_init_section_size = 1024*1024;
HLSContext *c = pls->parent->priv_data;
int64_t sec_size;
int64_t urlsize;
int ret;
if (seg->init_section == pls->cur_init_section)
return 0;
pls->cur_init_section = NULL;
if (!seg->init_section)
return 0;
ret = open_input(c, pls, seg->init_section);
if (ret < 0) {
av_log(pls->parent, AV_LOG_WARNING,
"Failed to open an initialization section in playlist %d\n",
pls->index);
return ret;
}
if (seg->init_section->size >= 0)
sec_size = seg->init_section->size;
else if ((urlsize = avio_size(pls->input)) >= 0)
sec_size = urlsize;
else
sec_size = max_init_section_size;
av_log(pls->parent, AV_LOG_DEBUG,
"Downloading an initialization section of size %"PRId64"\n",
sec_size);
sec_size = FFMIN(sec_size, max_init_section_size);
av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
pls->init_sec_buf_size, READ_COMPLETE);
ff_format_io_close(pls->parent, &pls->input);
if (ret < 0)
return ret;
pls->cur_init_section = seg->init_section;
pls->init_sec_data_len = ret;
pls->init_sec_buf_read_offset = 0;
/* spec says audio elementary streams do not have media initialization
* sections, so there should be no ID3 timestamps */
pls->is_id3_timestamped = 0;
return 0;
}
static int64_t default_reload_interval(struct playlist *pls)
{
return pls->n_segments > 0 ?
pls->segments[pls->n_segments - 1]->duration :
pls->target_duration;
}
static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
int reload_count = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
reload_count++;
if (reload_count > c->max_reload)
return AVERROR_EOF;
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
static void add_renditions_to_variant(HLSContext *c, struct variant *var,
enum AVMediaType type, const char *group_id)
{
int i;
for (i = 0; i < c->n_renditions; i++) {
struct rendition *rend = c->renditions[i];
if (rend->type == type && !strcmp(rend->group_id, group_id)) {
if (rend->playlist)
/* rendition is an external playlist
* => add the playlist to the variant */
dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
else
/* rendition is part of the variant main Media Playlist
* => add the rendition to the main Media Playlist */
dynarray_add(&var->playlists[0]->renditions,
&var->playlists[0]->n_renditions,
rend);
}
}
}
static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
enum AVMediaType type)
{
int rend_idx = 0;
int i;
for (i = 0; i < pls->n_main_streams; i++) {
AVStream *st = pls->main_streams[i];
if (st->codecpar->codec_type != type)
continue;
for (; rend_idx < pls->n_renditions; rend_idx++) {
struct rendition *rend = pls->renditions[rend_idx];
if (rend->type != type)
continue;
if (rend->language[0])
av_dict_set(&st->metadata, "language", rend->language, 0);
if (rend->name[0])
av_dict_set(&st->metadata, "comment", rend->name, 0);
st->disposition |= rend->disposition;
}
if (rend_idx >=pls->n_renditions)
break;
}
}
/* if timestamp was in valid range: returns 1 and sets seq_no
* if not: returns 0 and sets seq_no to closest segment */
static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
int64_t timestamp, int *seq_no)
{
int i;
int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
if (timestamp < pos) {
*seq_no = pls->start_seq_no;
return 0;
}
for (i = 0; i < pls->n_segments; i++) {
int64_t diff = pos + pls->segments[i]->duration - timestamp;
if (diff > 0) {
*seq_no = pls->start_seq_no + i;
return 1;
}
pos += pls->segments[i]->duration;
}
*seq_no = pls->start_seq_no + pls->n_segments - 1;
return 0;
}
static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
{
int seq_no;
if (!pls->finished && !c->first_packet &&
av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
/* reload the playlist since it was suspended */
parse_playlist(c, pls->url, pls, NULL);
/* If playback is already in progress (we are just selecting a new
* playlist) and this is a complete file, find the matching segment
* by counting durations. */
if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
return seq_no;
}
if (!pls->finished) {
if (!c->first_packet && /* we are doing a segment selection during playback */
c->cur_seq_no >= pls->start_seq_no &&
c->cur_seq_no < pls->start_seq_no + pls->n_segments)
/* While spec 3.4.3 says that we cannot assume anything about the
* content at the same sequence number on different playlists,
* in practice this seems to work and doing it otherwise would
* require us to download a segment to inspect its timestamps. */
return c->cur_seq_no;
/* If this is a live stream, start live_start_index segments from the
* start or end */
if (c->live_start_index < 0)
return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
else
return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
}
/* Otherwise just start on the first segment. */
return pls->start_seq_no;
}
static int save_avio_options(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
static const char *opts[] = {
"headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
const char **opt = opts;
uint8_t *buf;
int ret = 0;
while (*opt) {
if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
ret = av_dict_set(&c->avio_opts, *opt, buf,
AV_DICT_DONT_STRDUP_VAL);
if (ret < 0)
return ret;
}
opt++;
}
return ret;
}
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
int flags, AVDictionary **opts)
{
av_log(s, AV_LOG_ERROR,
"A HLS playlist item '%s' referred to an external file '%s'. "
"Opening this file was forbidden for security reasons\n",
s->filename, url);
return AVERROR(EPERM);
}
static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
{
HLSContext *c = s->priv_data;
int i, j;
int bandwidth = -1;
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
for (j = 0; j < v->n_playlists; j++) {
if (v->playlists[j] != pls)
continue;
av_program_add_stream_index(s, i, stream->index);
if (bandwidth < 0)
bandwidth = v->bandwidth;
else if (bandwidth != v->bandwidth)
bandwidth = -1; /* stream in multiple variants with different bandwidths */
}
}
if (bandwidth >= 0)
av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
}
static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
{
int err;
err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
if (err < 0)
return err;
if (pls->is_id3_timestamped) /* custom timestamps via id3 */
avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
else
avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
st->internal->need_context_update = 1;
return 0;
}
/* add new subdemuxer streams to our context, if any */
static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
{
int err;
while (pls->n_main_streams < pls->ctx->nb_streams) {
int ist_idx = pls->n_main_streams;
AVStream *st = avformat_new_stream(s, NULL);
AVStream *ist = pls->ctx->streams[ist_idx];
if (!st)
return AVERROR(ENOMEM);
st->id = pls->index;
dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
add_stream_to_programs(s, pls, st);
err = set_stream_info_from_input_stream(st, pls, ist);
if (err < 0)
return err;
}
return 0;
}
static void update_noheader_flag(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
int flag_needed = 0;
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->has_noheader_flag) {
flag_needed = 1;
break;
}
}
if (flag_needed)
s->ctx_flags |= AVFMTCTX_NOHEADER;
else
s->ctx_flags &= ~AVFMTCTX_NOHEADER;
}
static int hls_close(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
free_playlist_list(c);
free_variant_list(c);
free_rendition_list(c);
av_dict_free(&c->avio_opts);
return 0;
}
static int hls_read_header(AVFormatContext *s)
{
void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
HLSContext *c = s->priv_data;
int ret = 0, i;
int highest_cur_seq_no = 0;
c->ctx = s;
c->interrupt_callback = &s->interrupt_callback;
c->strict_std_compliance = s->strict_std_compliance;
c->first_packet = 1;
c->first_timestamp = AV_NOPTS_VALUE;
c->cur_timestamp = AV_NOPTS_VALUE;
if (u) {
// get the previous user agent & set back to null if string size is zero
update_options(&c->user_agent, "user_agent", u);
// get the previous cookies & set back to null if string size is zero
update_options(&c->cookies, "cookies", u);
// get the previous headers & set back to null if string size is zero
update_options(&c->headers, "headers", u);
// get the previous http proxt & set back to null if string size is zero
update_options(&c->http_proxy, "http_proxy", u);
}
if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
goto fail;
if ((ret = save_avio_options(s)) < 0)
goto fail;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&c->avio_opts, "seekable", "0", 0);
if (c->n_variants == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If the playlist only contained playlists (Master Playlist),
* parse each individual playlist. */
if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
goto fail;
}
}
if (c->variants[0]->playlists[0]->n_segments == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If this isn't a live stream, calculate the total duration of the
* stream. */
if (c->variants[0]->playlists[0]->finished) {
int64_t duration = 0;
for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
duration += c->variants[0]->playlists[0]->segments[i]->duration;
s->duration = duration;
}
/* Associate renditions with variants */
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
if (var->audio_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
if (var->video_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
if (var->subtitles_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
}
/* Create a program for each variant */
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
AVProgram *program;
program = av_new_program(s, i);
if (!program)
goto fail;
av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
}
/* Select the starting segments */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->n_segments == 0)
continue;
pls->cur_seq_no = select_cur_seq_no(c, pls);
highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
}
/* Open the demuxer for each playlist */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
AVInputFormat *in_fmt = NULL;
if (!(pls->ctx = avformat_alloc_context())) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (pls->n_segments == 0)
continue;
pls->index = i;
pls->needed = 1;
pls->parent = s;
/*
* If this is a live stream and this playlist looks like it is one segment
* behind, try to sync it up so that every substream starts at the same
* time position (so e.g. avformat_find_stream_info() will see packets from
* all active streams within the first few seconds). This is not very generic,
* though, as the sequence numbers are technically independent.
*/
if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
pls->cur_seq_no = highest_cur_seq_no;
}
pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
if (!pls->read_buffer){
ret = AVERROR(ENOMEM);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
read_data, NULL, NULL);
pls->pb.seekable = 0;
ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
NULL, 0, 0);
if (ret < 0) {
/* Free the ctx - it isn't initialized properly at this point,
* so avformat_close_input shouldn't be called. If
* avformat_open_input fails below, it frees and zeros the
* context, so it doesn't need any special treatment like this. */
av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
pls->ctx->pb = &pls->pb;
pls->ctx->io_open = nested_io_open;
pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
goto fail;
ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
if (ret < 0)
goto fail;
if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
avformat_queue_attached_pictures(pls->ctx);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
pls->id3_deferred_extra = NULL;
}
if (pls->is_id3_timestamped == -1)
av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
/*
* For ID3 timestamped raw audio streams we need to detect the packet
* durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
* but for other streams we can rely on our user calling avformat_find_stream_info()
* on us if they want to.
*/
if (pls->is_id3_timestamped) {
ret = avformat_find_stream_info(pls->ctx, NULL);
if (ret < 0)
goto fail;
}
pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
/* Create new AVStreams for each stream in this playlist */
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0)
goto fail;
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
}
update_noheader_flag(s);
return 0;
fail:
hls_close(s);
return ret;
}
static int recheck_discard_flags(AVFormatContext *s, int first)
{
HLSContext *c = s->priv_data;
int i, changed = 0;
/* Check if any new streams are needed */
for (i = 0; i < c->n_playlists; i++)
c->playlists[i]->cur_needed = 0;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
struct playlist *pls = c->playlists[s->streams[i]->id];
if (st->discard < AVDISCARD_ALL)
pls->cur_needed = 1;
}
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->cur_needed && !pls->needed) {
pls->needed = 1;
changed = 1;
pls->cur_seq_no = select_cur_seq_no(c, pls);
pls->pb.eof_reached = 0;
if (c->cur_timestamp != AV_NOPTS_VALUE) {
/* catch up */
pls->seek_timestamp = c->cur_timestamp;
pls->seek_flags = AVSEEK_FLAG_ANY;
pls->seek_stream_index = -1;
}
av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
} else if (first && !pls->cur_needed && pls->needed) {
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
pls->needed = 0;
changed = 1;
av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
}
}
return changed;
}
static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
{
if (pls->id3_offset >= 0) {
pls->pkt.dts = pls->id3_mpegts_timestamp +
av_rescale_q(pls->id3_offset,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
if (pls->pkt.duration)
pls->id3_offset += pls->pkt.duration;
else
pls->id3_offset = -1;
} else {
/* there have been packets with unknown duration
* since the last id3 tag, should not normally happen */
pls->pkt.dts = AV_NOPTS_VALUE;
}
if (pls->pkt.duration)
pls->pkt.duration = av_rescale_q(pls->pkt.duration,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
pls->pkt.pts = AV_NOPTS_VALUE;
}
static AVRational get_timebase(struct playlist *pls)
{
if (pls->is_id3_timestamped)
return MPEG_TIME_BASE_Q;
return pls->ctx->streams[pls->pkt.stream_index]->time_base;
}
static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
int64_t ts_b, struct playlist *pls_b)
{
int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
}
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
{
HLSContext *c = s->priv_data;
int ret, i, minplaylist = -1;
recheck_discard_flags(s, c->first_packet);
c->first_packet = 0;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
/* Make sure we've got one buffered packet from each open playlist
* stream */
if (pls->needed && !pls->pkt.data) {
while (1) {
int64_t ts_diff;
AVRational tb;
ret = av_read_frame(pls->ctx, &pls->pkt);
if (ret < 0) {
if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
return ret;
reset_packet(&pls->pkt);
break;
} else {
/* stream_index check prevents matching picture attachments etc. */
if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
/* audio elementary streams are id3 timestamped */
fill_timing_for_id3_timestamped_stream(pls);
}
if (c->first_timestamp == AV_NOPTS_VALUE &&
pls->pkt.dts != AV_NOPTS_VALUE)
c->first_timestamp = av_rescale_q(pls->pkt.dts,
get_timebase(pls), AV_TIME_BASE_Q);
}
if (pls->seek_timestamp == AV_NOPTS_VALUE)
break;
if (pls->seek_stream_index < 0 ||
pls->seek_stream_index == pls->pkt.stream_index) {
if (pls->pkt.dts == AV_NOPTS_VALUE) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
tb = get_timebase(pls);
ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
tb.den, AV_ROUND_DOWN) -
pls->seek_timestamp;
if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
pls->pkt.flags & AV_PKT_FLAG_KEY)) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
}
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
}
}
/* Check if this stream has the packet with the lowest dts */
if (pls->pkt.data) {
struct playlist *minpls = minplaylist < 0 ?
NULL : c->playlists[minplaylist];
if (minplaylist < 0) {
minplaylist = i;
} else {
int64_t dts = pls->pkt.dts;
int64_t mindts = minpls->pkt.dts;
if (dts == AV_NOPTS_VALUE ||
(mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
minplaylist = i;
}
}
}
/* If we got a packet, return it */
if (minplaylist >= 0) {
struct playlist *pls = c->playlists[minplaylist];
AVStream *ist;
AVStream *st;
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0) {
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return ret;
}
/* check if noheader flag has been cleared by the subdemuxer */
if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
pls->has_noheader_flag = 0;
update_noheader_flag(s);
}
if (pls->pkt.stream_index >= pls->n_main_streams) {
av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return AVERROR_BUG;
}
ist = pls->ctx->streams[pls->pkt.stream_index];
st = pls->main_streams[pls->pkt.stream_index];
*pkt = pls->pkt;
pkt->stream_index = st->index;
reset_packet(&c->playlists[minplaylist]->pkt);
if (pkt->dts != AV_NOPTS_VALUE)
c->cur_timestamp = av_rescale_q(pkt->dts,
ist->time_base,
AV_TIME_BASE_Q);
/* There may be more situations where this would be useful, but this at least
* handles newly probed codecs properly (i.e. request_probe by mpegts). */
if (ist->codecpar->codec_id != st->codecpar->codec_id) {
ret = set_stream_info_from_input_stream(st, pls, ist);
if (ret < 0) {
av_packet_unref(pkt);
return ret;
}
}
return 0;
}
return AVERROR_EOF;
}
static int hls_read_seek(AVFormatContext *s, int stream_index,
int64_t timestamp, int flags)
{
HLSContext *c = s->priv_data;
struct playlist *seek_pls = NULL;
int i, seq_no;
int j;
int stream_subdemuxer_index;
int64_t first_timestamp, seek_timestamp, duration;
if ((flags & AVSEEK_FLAG_BYTE) ||
!(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
return AVERROR(ENOSYS);
first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
s->streams[stream_index]->time_base.den,
flags & AVSEEK_FLAG_BACKWARD ?
AV_ROUND_DOWN : AV_ROUND_UP);
duration = s->duration == AV_NOPTS_VALUE ?
0 : s->duration;
if (0 < duration && duration < seek_timestamp - first_timestamp)
return AVERROR(EIO);
/* find the playlist with the specified stream */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
for (j = 0; j < pls->n_main_streams; j++) {
if (pls->main_streams[j] == s->streams[stream_index]) {
seek_pls = pls;
stream_subdemuxer_index = j;
break;
}
}
}
/* check if the timestamp is valid for the playlist with the
* specified stream index */
if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
return AVERROR(EIO);
/* set segment now so we do not need to search again below */
seek_pls->cur_seq_no = seq_no;
seek_pls->seek_stream_index = stream_subdemuxer_index;
for (i = 0; i < c->n_playlists; i++) {
/* Reset reading */
struct playlist *pls = c->playlists[i];
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
pls->pb.eof_reached = 0;
/* Clear any buffered data */
pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
/* Reset the pos, to let the mpegts demuxer know we've seeked. */
pls->pb.pos = 0;
/* Flush the packet queue of the subdemuxer. */
ff_read_frame_flush(pls->ctx);
pls->seek_timestamp = seek_timestamp;
pls->seek_flags = flags;
if (pls != seek_pls) {
/* set closest segment seq_no for playlists not handled above */
find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
/* seek the playlist to the given position without taking
* keyframes into account since this playlist does not have the
* specified stream where we should look for the keyframes */
pls->seek_stream_index = -1;
pls->seek_flags |= AVSEEK_FLAG_ANY;
}
}
c->cur_timestamp = seek_timestamp;
return 0;
}
static int hls_probe(AVProbeData *p)
{
/* Require #EXTM3U at the start, and either one of the ones below
* somewhere for a proper match. */
if (strncmp(p->buf, "#EXTM3U", 7))
return 0;
if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
return AVPROBE_SCORE_MAX;
return 0;
}
#define OFFSET(x) offsetof(HLSContext, x)
#define FLAGS AV_OPT_FLAG_DECODING_PARAM
static const AVOption hls_options[] = {
{"live_start_index", "segment index to start live streams at (negative values are from the end)",
OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
{"allowed_extensions", "List of file extensions that hls is allowed to access",
OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
{.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"},
INT_MIN, INT_MAX, FLAGS},
{"max_reload", "Maximum number of times a insufficient list is attempted to be reloaded",
OFFSET(max_reload), AV_OPT_TYPE_INT, {.i64 = 1000}, 0, INT_MAX, FLAGS},
{NULL}
};
static const AVClass hls_class = {
.class_name = "hls,applehttp",
.item_name = av_default_item_name,
.option = hls_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVInputFormat ff_hls_demuxer = {
.name = "hls,applehttp",
.long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
.priv_class = &hls_class,
.priv_data_size = sizeof(HLSContext),
.read_probe = hls_probe,
.read_header = hls_read_header,
.read_packet = hls_read_packet,
.read_close = hls_close,
.read_seek = hls_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2765_1 |
crossvul-cpp_data_good_2662_0 | /*
* Copyright (c) 2015 The TCPDUMP 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.
*
* 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.
*
* Initial contribution by Andrew Darqui (andrew.darqui@gmail.com).
*/
/* \summary: REdis Serialization Protocol (RESP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "extract.h"
static const char tstr[] = " [|RESP]";
/*
* For information regarding RESP, see: http://redis.io/topics/protocol
*/
#define RESP_SIMPLE_STRING '+'
#define RESP_ERROR '-'
#define RESP_INTEGER ':'
#define RESP_BULK_STRING '$'
#define RESP_ARRAY '*'
#define resp_print_empty(ndo) ND_PRINT((ndo, " empty"))
#define resp_print_null(ndo) ND_PRINT((ndo, " null"))
#define resp_print_length_too_large(ndo) ND_PRINT((ndo, " length too large"))
#define resp_print_length_negative(ndo) ND_PRINT((ndo, " length negative and not -1"))
#define resp_print_invalid(ndo) ND_PRINT((ndo, " invalid"))
void resp_print(netdissect_options *, const u_char *, u_int);
static int resp_parse(netdissect_options *, register const u_char *, int);
static int resp_print_string_error_integer(netdissect_options *, register const u_char *, int);
static int resp_print_simple_string(netdissect_options *, register const u_char *, int);
static int resp_print_integer(netdissect_options *, register const u_char *, int);
static int resp_print_error(netdissect_options *, register const u_char *, int);
static int resp_print_bulk_string(netdissect_options *, register const u_char *, int);
static int resp_print_bulk_array(netdissect_options *, register const u_char *, int);
static int resp_print_inline(netdissect_options *, register const u_char *, int);
static int resp_get_length(netdissect_options *, register const u_char *, int, const u_char **);
#define LCHECK2(_tot_len, _len) \
{ \
if (_tot_len < _len) \
goto trunc; \
}
#define LCHECK(_tot_len) LCHECK2(_tot_len, 1)
/*
* FIND_CRLF:
* Attempts to move our 'ptr' forward until a \r\n is found,
* while also making sure we don't exceed the buffer '_len'
* or go past the end of the captured data.
* If we exceed or go past the end of the captured data,
* jump to trunc.
*/
#define FIND_CRLF(_ptr, _len) \
for (;;) { \
LCHECK2(_len, 2); \
ND_TCHECK2(*_ptr, 2); \
if (*_ptr == '\r' && *(_ptr+1) == '\n') \
break; \
_ptr++; \
_len--; \
}
/*
* CONSUME_CRLF
* Consume a CRLF that we've just found.
*/
#define CONSUME_CRLF(_ptr, _len) \
_ptr += 2; \
_len -= 2;
/*
* FIND_CR_OR_LF
* Attempts to move our '_ptr' forward until a \r or \n is found,
* while also making sure we don't exceed the buffer '_len'
* or go past the end of the captured data.
* If we exceed or go past the end of the captured data,
* jump to trunc.
*/
#define FIND_CR_OR_LF(_ptr, _len) \
for (;;) { \
LCHECK(_len); \
ND_TCHECK(*_ptr); \
if (*_ptr == '\r' || *_ptr == '\n') \
break; \
_ptr++; \
_len--; \
}
/*
* CONSUME_CR_OR_LF
* Consume all consecutive \r and \n bytes.
* If we exceed '_len' or go past the end of the captured data,
* jump to trunc.
*/
#define CONSUME_CR_OR_LF(_ptr, _len) \
{ \
int _found_cr_or_lf = 0; \
for (;;) { \
/* \
* Have we hit the end of data? \
*/ \
if (_len == 0 || !ND_TTEST(*_ptr)) { \
/* \
* Yes. Have we seen a \r \
* or \n? \
*/ \
if (_found_cr_or_lf) { \
/* \
* Yes. Just stop. \
*/ \
break; \
} \
/* \
* No. We ran out of packet. \
*/ \
goto trunc; \
} \
if (*_ptr != '\r' && *_ptr != '\n') \
break; \
_found_cr_or_lf = 1; \
_ptr++; \
_len--; \
} \
}
/*
* SKIP_OPCODE
* Skip over the opcode character.
* The opcode has already been fetched, so we know it's there, and don't
* need to do any checks.
*/
#define SKIP_OPCODE(_ptr, _tot_len) \
_ptr++; \
_tot_len--;
/*
* GET_LENGTH
* Get a bulk string or array length.
*/
#define GET_LENGTH(_ndo, _tot_len, _ptr, _len) \
{ \
const u_char *_endp; \
_len = resp_get_length(_ndo, _ptr, _tot_len, &_endp); \
_tot_len -= (_endp - _ptr); \
_ptr = _endp; \
}
/*
* TEST_RET_LEN
* If ret_len is < 0, jump to the trunc tag which returns (-1)
* and 'bubbles up' to printing tstr. Otherwise, return ret_len.
*/
#define TEST_RET_LEN(rl) \
if (rl < 0) { goto trunc; } else { return rl; }
/*
* TEST_RET_LEN_NORETURN
* If ret_len is < 0, jump to the trunc tag which returns (-1)
* and 'bubbles up' to printing tstr. Otherwise, continue onward.
*/
#define TEST_RET_LEN_NORETURN(rl) \
if (rl < 0) { goto trunc; }
/*
* RESP_PRINT_SEGMENT
* Prints a segment in the form of: ' "<stuff>"\n"
* Assumes the data has already been verified as present.
*/
#define RESP_PRINT_SEGMENT(_ndo, _bp, _len) \
ND_PRINT((_ndo, " \"")); \
if (fn_printn(_ndo, _bp, _len, _ndo->ndo_snapend)) \
goto trunc; \
fn_print_char(_ndo, '"');
void
resp_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
int ret_len = 0, length_cur = length;
if(!bp || length <= 0)
return;
ND_PRINT((ndo, ": RESP"));
while (length_cur > 0) {
/*
* This block supports redis pipelining.
* For example, multiple operations can be pipelined within the same string:
* "*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n"
* or
* "PING\r\nPING\r\nPING\r\n"
* In order to handle this case, we must try and parse 'bp' until
* 'length' bytes have been processed or we reach a trunc condition.
*/
ret_len = resp_parse(ndo, bp, length_cur);
TEST_RET_LEN_NORETURN(ret_len);
bp += ret_len;
length_cur -= ret_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
resp_parse(netdissect_options *ndo, register const u_char *bp, int length)
{
u_char op;
int ret_len;
LCHECK2(length, 1);
ND_TCHECK(*bp);
op = *bp;
/* bp now points to the op, so these routines must skip it */
switch(op) {
case RESP_SIMPLE_STRING: ret_len = resp_print_simple_string(ndo, bp, length); break;
case RESP_INTEGER: ret_len = resp_print_integer(ndo, bp, length); break;
case RESP_ERROR: ret_len = resp_print_error(ndo, bp, length); break;
case RESP_BULK_STRING: ret_len = resp_print_bulk_string(ndo, bp, length); break;
case RESP_ARRAY: ret_len = resp_print_bulk_array(ndo, bp, length); break;
default: ret_len = resp_print_inline(ndo, bp, length); break;
}
/*
* This gives up with a "truncated" indicator for all errors,
* including invalid packet errors; that's what we want, as
* we have to give up on further parsing in that case.
*/
TEST_RET_LEN(ret_len);
trunc:
return (-1);
}
static int
resp_print_simple_string(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_integer(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_error(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_string_error_integer(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length, len, ret_len;
const u_char *bp_ptr;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
bp_ptr = bp;
/*
* bp now prints past the (+-;) opcode, so it's pointing to the first
* character of the string (which could be numeric).
* +OK\r\n
* -ERR ...\r\n
* :02912309\r\n
*
* Find the \r\n with FIND_CRLF().
*/
FIND_CRLF(bp_ptr, length_cur);
/*
* bp_ptr points to the \r\n, so bp_ptr - bp is the length of text
* preceding the \r\n. That includes the opcode, so don't print
* that.
*/
len = (bp_ptr - bp);
RESP_PRINT_SEGMENT(ndo, bp, len);
ret_len = 1 /*<opcode>*/ + len /*<string>*/ + 2 /*<CRLF>*/;
TEST_RET_LEN(ret_len);
trunc:
return (-1);
}
static int
resp_print_bulk_string(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length, string_len;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
/* <length>\r\n */
GET_LENGTH(ndo, length_cur, bp, string_len);
if (string_len >= 0) {
/* Byte string of length string_len, starting at bp */
if (string_len == 0)
resp_print_empty(ndo);
else {
LCHECK2(length_cur, string_len);
ND_TCHECK2(*bp, string_len);
RESP_PRINT_SEGMENT(ndo, bp, string_len);
bp += string_len;
length_cur -= string_len;
}
/*
* Find the \r\n at the end of the string and skip past it.
* XXX - report an error if the \r\n isn't immediately after
* the item?
*/
FIND_CRLF(bp, length_cur);
CONSUME_CRLF(bp, length_cur);
} else {
/* null, truncated, or invalid for some reason */
switch(string_len) {
case (-1): resp_print_null(ndo); break;
case (-2): goto trunc;
case (-3): resp_print_length_too_large(ndo); break;
case (-4): resp_print_length_negative(ndo); break;
default: resp_print_invalid(ndo); break;
}
}
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_print_bulk_array(netdissect_options *ndo, register const u_char *bp, int length) {
u_int length_cur = length;
int array_len, i, ret_len;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
/* <array_length>\r\n */
GET_LENGTH(ndo, length_cur, bp, array_len);
if (array_len > 0) {
/* non empty array */
for (i = 0; i < array_len; i++) {
ret_len = resp_parse(ndo, bp, length_cur);
TEST_RET_LEN_NORETURN(ret_len);
bp += ret_len;
length_cur -= ret_len;
}
} else {
/* empty, null, truncated, or invalid */
switch(array_len) {
case 0: resp_print_empty(ndo); break;
case (-1): resp_print_null(ndo); break;
case (-2): goto trunc;
case (-3): resp_print_length_too_large(ndo); break;
case (-4): resp_print_length_negative(ndo); break;
default: resp_print_invalid(ndo); break;
}
}
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_print_inline(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length;
int len;
const u_char *bp_ptr;
/*
* Inline commands are simply 'strings' followed by \r or \n or both.
* Redis will do its best to split/parse these strings.
* This feature of redis is implemented to support the ability of
* command parsing from telnet/nc sessions etc.
*
* <string><\r||\n||\r\n...>
*/
/*
* Skip forward past any leading \r, \n, or \r\n.
*/
CONSUME_CR_OR_LF(bp, length_cur);
bp_ptr = bp;
/*
* Scan forward looking for \r or \n.
*/
FIND_CR_OR_LF(bp_ptr, length_cur);
/*
* Found it; bp_ptr points to the \r or \n, so bp_ptr - bp is the
* Length of the line text that preceeds it. Print it.
*/
len = (bp_ptr - bp);
RESP_PRINT_SEGMENT(ndo, bp, len);
/*
* Skip forward past the \r, \n, or \r\n.
*/
CONSUME_CR_OR_LF(bp_ptr, length_cur);
/*
* Return the number of bytes we processed.
*/
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)
{
int result;
u_char c;
int saw_digit;
int neg;
int too_large;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
too_large = 0;
neg = 0;
if (*bp == '-') {
neg = 1;
bp++;
len--;
}
result = 0;
saw_digit = 0;
for (;;) {
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
c = *bp;
if (!(c >= '0' && c <= '9')) {
if (!saw_digit) {
bp++;
goto invalid;
}
break;
}
c -= '0';
if (result > (INT_MAX / 10)) {
/* This will overflow an int when we multiply it by 10. */
too_large = 1;
} else {
result *= 10;
if (result == INT_MAX && c > (INT_MAX % 10)) {
/* This will overflow an int when we add c */
too_large = 1;
} else
result += c;
}
bp++;
len--;
saw_digit = 1;
}
if (!saw_digit)
goto invalid;
/*
* OK, the next thing should be \r\n.
*/
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\r') {
bp++;
goto invalid;
}
bp++;
len--;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\n') {
bp++;
goto invalid;
}
bp++;
len--;
*endp = bp;
if (neg) {
/* -1 means "null", anything else is invalid */
if (too_large || result != 1)
return (-4);
result = -1;
}
return (too_large ? -3 : result);
trunc:
*endp = bp;
return (-2);
invalid:
*endp = bp;
return (-5);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2662_0 |
crossvul-cpp_data_good_3016_0 | // SPDX-License-Identifier: GPL-2.0
/*
* linux/mm/madvise.c
*
* Copyright (C) 1999 Linus Torvalds
* Copyright (C) 2002 Christoph Hellwig
*/
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/syscalls.h>
#include <linux/mempolicy.h>
#include <linux/page-isolation.h>
#include <linux/userfaultfd_k.h>
#include <linux/hugetlb.h>
#include <linux/falloc.h>
#include <linux/sched.h>
#include <linux/ksm.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/shmem_fs.h>
#include <linux/mmu_notifier.h>
#include <asm/tlb.h>
#include "internal.h"
/*
* Any behaviour which results in changes to the vma->vm_flags needs to
* take mmap_sem for writing. Others, which simply traverse vmas, need
* to only take it for reading.
*/
static int madvise_need_mmap_write(int behavior)
{
switch (behavior) {
case MADV_REMOVE:
case MADV_WILLNEED:
case MADV_DONTNEED:
case MADV_FREE:
return 0;
default:
/* be safe, default to 1. list exceptions explicitly */
return 1;
}
}
/*
* We can potentially split a vm area into separate
* areas, each area with its own behavior.
*/
static long madvise_behavior(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end, int behavior)
{
struct mm_struct *mm = vma->vm_mm;
int error = 0;
pgoff_t pgoff;
unsigned long new_flags = vma->vm_flags;
switch (behavior) {
case MADV_NORMAL:
new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
break;
case MADV_SEQUENTIAL:
new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
break;
case MADV_RANDOM:
new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
break;
case MADV_DONTFORK:
new_flags |= VM_DONTCOPY;
break;
case MADV_DOFORK:
if (vma->vm_flags & VM_IO) {
error = -EINVAL;
goto out;
}
new_flags &= ~VM_DONTCOPY;
break;
case MADV_WIPEONFORK:
/* MADV_WIPEONFORK is only supported on anonymous memory. */
if (vma->vm_file || vma->vm_flags & VM_SHARED) {
error = -EINVAL;
goto out;
}
new_flags |= VM_WIPEONFORK;
break;
case MADV_KEEPONFORK:
new_flags &= ~VM_WIPEONFORK;
break;
case MADV_DONTDUMP:
new_flags |= VM_DONTDUMP;
break;
case MADV_DODUMP:
if (new_flags & VM_SPECIAL) {
error = -EINVAL;
goto out;
}
new_flags &= ~VM_DONTDUMP;
break;
case MADV_MERGEABLE:
case MADV_UNMERGEABLE:
error = ksm_madvise(vma, start, end, behavior, &new_flags);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
break;
case MADV_HUGEPAGE:
case MADV_NOHUGEPAGE:
error = hugepage_madvise(vma, &new_flags, behavior);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
break;
}
if (new_flags == vma->vm_flags) {
*prev = vma;
goto out;
}
pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
*prev = vma_merge(mm, *prev, start, end, new_flags, vma->anon_vma,
vma->vm_file, pgoff, vma_policy(vma),
vma->vm_userfaultfd_ctx);
if (*prev) {
vma = *prev;
goto success;
}
*prev = vma;
if (start != vma->vm_start) {
if (unlikely(mm->map_count >= sysctl_max_map_count)) {
error = -ENOMEM;
goto out;
}
error = __split_vma(mm, vma, start, 1);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
}
if (end != vma->vm_end) {
if (unlikely(mm->map_count >= sysctl_max_map_count)) {
error = -ENOMEM;
goto out;
}
error = __split_vma(mm, vma, end, 0);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
}
success:
/*
* vm_flags is protected by the mmap_sem held in write mode.
*/
vma->vm_flags = new_flags;
out:
return error;
}
#ifdef CONFIG_SWAP
static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
unsigned long end, struct mm_walk *walk)
{
pte_t *orig_pte;
struct vm_area_struct *vma = walk->private;
unsigned long index;
if (pmd_none_or_trans_huge_or_clear_bad(pmd))
return 0;
for (index = start; index != end; index += PAGE_SIZE) {
pte_t pte;
swp_entry_t entry;
struct page *page;
spinlock_t *ptl;
orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
pte = *(orig_pte + ((index - start) / PAGE_SIZE));
pte_unmap_unlock(orig_pte, ptl);
if (pte_present(pte) || pte_none(pte))
continue;
entry = pte_to_swp_entry(pte);
if (unlikely(non_swap_entry(entry)))
continue;
page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
vma, index, false);
if (page)
put_page(page);
}
return 0;
}
static void force_swapin_readahead(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
struct mm_walk walk = {
.mm = vma->vm_mm,
.pmd_entry = swapin_walk_pmd_entry,
.private = vma,
};
walk_page_range(start, end, &walk);
lru_add_drain(); /* Push any new pages onto the LRU now */
}
static void force_shm_swapin_readahead(struct vm_area_struct *vma,
unsigned long start, unsigned long end,
struct address_space *mapping)
{
pgoff_t index;
struct page *page;
swp_entry_t swap;
for (; start < end; start += PAGE_SIZE) {
index = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
page = find_get_entry(mapping, index);
if (!radix_tree_exceptional_entry(page)) {
if (page)
put_page(page);
continue;
}
swap = radix_to_swp_entry(page);
page = read_swap_cache_async(swap, GFP_HIGHUSER_MOVABLE,
NULL, 0, false);
if (page)
put_page(page);
}
lru_add_drain(); /* Push any new pages onto the LRU now */
}
#endif /* CONFIG_SWAP */
/*
* Schedule all required I/O operations. Do not wait for completion.
*/
static long madvise_willneed(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
struct file *file = vma->vm_file;
*prev = vma;
#ifdef CONFIG_SWAP
if (!file) {
force_swapin_readahead(vma, start, end);
return 0;
}
if (shmem_mapping(file->f_mapping)) {
force_shm_swapin_readahead(vma, start, end,
file->f_mapping);
return 0;
}
#else
if (!file)
return -EBADF;
#endif
if (IS_DAX(file_inode(file))) {
/* no bad return value, but ignore advice */
return 0;
}
start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
if (end > vma->vm_end)
end = vma->vm_end;
end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
force_page_cache_readahead(file->f_mapping, file, start, end - start);
return 0;
}
static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct mmu_gather *tlb = walk->private;
struct mm_struct *mm = tlb->mm;
struct vm_area_struct *vma = walk->vma;
spinlock_t *ptl;
pte_t *orig_pte, *pte, ptent;
struct page *page;
int nr_swap = 0;
unsigned long next;
next = pmd_addr_end(addr, end);
if (pmd_trans_huge(*pmd))
if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
goto next;
if (pmd_trans_unstable(pmd))
return 0;
tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
flush_tlb_batched_pending(mm);
arch_enter_lazy_mmu_mode();
for (; addr != end; pte++, addr += PAGE_SIZE) {
ptent = *pte;
if (pte_none(ptent))
continue;
/*
* If the pte has swp_entry, just clear page table to
* prevent swap-in which is more expensive rather than
* (page allocation + zeroing).
*/
if (!pte_present(ptent)) {
swp_entry_t entry;
entry = pte_to_swp_entry(ptent);
if (non_swap_entry(entry))
continue;
nr_swap--;
free_swap_and_cache(entry);
pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
continue;
}
page = _vm_normal_page(vma, addr, ptent, true);
if (!page)
continue;
/*
* If pmd isn't transhuge but the page is THP and
* is owned by only this process, split it and
* deactivate all pages.
*/
if (PageTransCompound(page)) {
if (page_mapcount(page) != 1)
goto out;
get_page(page);
if (!trylock_page(page)) {
put_page(page);
goto out;
}
pte_unmap_unlock(orig_pte, ptl);
if (split_huge_page(page)) {
unlock_page(page);
put_page(page);
pte_offset_map_lock(mm, pmd, addr, &ptl);
goto out;
}
unlock_page(page);
put_page(page);
pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
pte--;
addr -= PAGE_SIZE;
continue;
}
VM_BUG_ON_PAGE(PageTransCompound(page), page);
if (PageSwapCache(page) || PageDirty(page)) {
if (!trylock_page(page))
continue;
/*
* If page is shared with others, we couldn't clear
* PG_dirty of the page.
*/
if (page_mapcount(page) != 1) {
unlock_page(page);
continue;
}
if (PageSwapCache(page) && !try_to_free_swap(page)) {
unlock_page(page);
continue;
}
ClearPageDirty(page);
unlock_page(page);
}
if (pte_young(ptent) || pte_dirty(ptent)) {
/*
* Some of architecture(ex, PPC) don't update TLB
* with set_pte_at and tlb_remove_tlb_entry so for
* the portability, remap the pte with old|clean
* after pte clearing.
*/
ptent = ptep_get_and_clear_full(mm, addr, pte,
tlb->fullmm);
ptent = pte_mkold(ptent);
ptent = pte_mkclean(ptent);
set_pte_at(mm, addr, pte, ptent);
tlb_remove_tlb_entry(tlb, pte, addr);
}
mark_page_lazyfree(page);
}
out:
if (nr_swap) {
if (current->mm == mm)
sync_mm_rss(mm);
add_mm_counter(mm, MM_SWAPENTS, nr_swap);
}
arch_leave_lazy_mmu_mode();
pte_unmap_unlock(orig_pte, ptl);
cond_resched();
next:
return 0;
}
static void madvise_free_page_range(struct mmu_gather *tlb,
struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
struct mm_walk free_walk = {
.pmd_entry = madvise_free_pte_range,
.mm = vma->vm_mm,
.private = tlb,
};
tlb_start_vma(tlb, vma);
walk_page_range(addr, end, &free_walk);
tlb_end_vma(tlb, vma);
}
static int madvise_free_single_vma(struct vm_area_struct *vma,
unsigned long start_addr, unsigned long end_addr)
{
unsigned long start, end;
struct mm_struct *mm = vma->vm_mm;
struct mmu_gather tlb;
/* MADV_FREE works for only anon vma at the moment */
if (!vma_is_anonymous(vma))
return -EINVAL;
start = max(vma->vm_start, start_addr);
if (start >= vma->vm_end)
return -EINVAL;
end = min(vma->vm_end, end_addr);
if (end <= vma->vm_start)
return -EINVAL;
lru_add_drain();
tlb_gather_mmu(&tlb, mm, start, end);
update_hiwater_rss(mm);
mmu_notifier_invalidate_range_start(mm, start, end);
madvise_free_page_range(&tlb, vma, start, end);
mmu_notifier_invalidate_range_end(mm, start, end);
tlb_finish_mmu(&tlb, start, end);
return 0;
}
/*
* Application no longer needs these pages. If the pages are dirty,
* it's OK to just throw them away. The app will be more careful about
* data it wants to keep. Be sure to free swap resources too. The
* zap_page_range call sets things up for shrink_active_list to actually free
* these pages later if no one else has touched them in the meantime,
* although we could add these pages to a global reuse list for
* shrink_active_list to pick up before reclaiming other pages.
*
* NB: This interface discards data rather than pushes it out to swap,
* as some implementations do. This has performance implications for
* applications like large transactional databases which want to discard
* pages in anonymous maps after committing to backing store the data
* that was kept in them. There is no reason to write this data out to
* the swap area if the application is discarding it.
*
* An interface that causes the system to free clean pages and flush
* dirty pages is already available as msync(MS_INVALIDATE).
*/
static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
zap_page_range(vma, start, end - start);
return 0;
}
static long madvise_dontneed_free(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end,
int behavior)
{
*prev = vma;
if (!can_madv_dontneed_vma(vma))
return -EINVAL;
if (!userfaultfd_remove(vma, start, end)) {
*prev = NULL; /* mmap_sem has been dropped, prev is stale */
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, start);
if (!vma)
return -ENOMEM;
if (start < vma->vm_start) {
/*
* This "vma" under revalidation is the one
* with the lowest vma->vm_start where start
* is also < vma->vm_end. If start <
* vma->vm_start it means an hole materialized
* in the user address space within the
* virtual range passed to MADV_DONTNEED
* or MADV_FREE.
*/
return -ENOMEM;
}
if (!can_madv_dontneed_vma(vma))
return -EINVAL;
if (end > vma->vm_end) {
/*
* Don't fail if end > vma->vm_end. If the old
* vma was splitted while the mmap_sem was
* released the effect of the concurrent
* operation may not cause madvise() to
* have an undefined result. There may be an
* adjacent next vma that we'll walk
* next. userfaultfd_remove() will generate an
* UFFD_EVENT_REMOVE repetition on the
* end-vma->vm_end range, but the manager can
* handle a repetition fine.
*/
end = vma->vm_end;
}
VM_WARN_ON(start >= end);
}
if (behavior == MADV_DONTNEED)
return madvise_dontneed_single_vma(vma, start, end);
else if (behavior == MADV_FREE)
return madvise_free_single_vma(vma, start, end);
else
return -EINVAL;
}
/*
* Application wants to free up the pages and associated backing store.
* This is effectively punching a hole into the middle of a file.
*/
static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
struct file *f;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & VM_LOCKED)
return -EINVAL;
f = vma->vm_file;
if (!f || !f->f_mapping || !f->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/*
* Filesystem's fallocate may need to take i_mutex. We need to
* explicitly grab a reference because the vma (and hence the
* vma's reference to the file) can go away as soon as we drop
* mmap_sem.
*/
get_file(f);
if (userfaultfd_remove(vma, start, end)) {
/* mmap_sem was not released by userfaultfd_remove() */
up_read(¤t->mm->mmap_sem);
}
error = vfs_fallocate(f,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
fput(f);
down_read(¤t->mm->mmap_sem);
return error;
}
#ifdef CONFIG_MEMORY_FAILURE
/*
* Error injection support for memory error handling.
*/
static int madvise_inject_error(int behavior,
unsigned long start, unsigned long end)
{
struct page *page;
struct zone *zone;
unsigned int order;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
for (; start < end; start += PAGE_SIZE << order) {
int ret;
ret = get_user_pages_fast(start, 1, 0, &page);
if (ret != 1)
return ret;
/*
* When soft offlining hugepages, after migrating the page
* we dissolve it, therefore in the second loop "page" will
* no longer be a compound page, and order will be 0.
*/
order = compound_order(compound_head(page));
if (PageHWPoison(page)) {
put_page(page);
continue;
}
if (behavior == MADV_SOFT_OFFLINE) {
pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
page_to_pfn(page), start);
ret = soft_offline_page(page, MF_COUNT_INCREASED);
if (ret)
return ret;
continue;
}
pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
page_to_pfn(page), start);
ret = memory_failure(page_to_pfn(page), 0, MF_COUNT_INCREASED);
if (ret)
return ret;
}
/* Ensure that all poisoned pages are removed from per-cpu lists */
for_each_populated_zone(zone)
drain_all_pages(zone);
return 0;
}
#endif
static long
madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, int behavior)
{
switch (behavior) {
case MADV_REMOVE:
return madvise_remove(vma, prev, start, end);
case MADV_WILLNEED:
return madvise_willneed(vma, prev, start, end);
case MADV_FREE:
case MADV_DONTNEED:
return madvise_dontneed_free(vma, prev, start, end, behavior);
default:
return madvise_behavior(vma, prev, start, end, behavior);
}
}
static bool
madvise_behavior_valid(int behavior)
{
switch (behavior) {
case MADV_DOFORK:
case MADV_DONTFORK:
case MADV_NORMAL:
case MADV_SEQUENTIAL:
case MADV_RANDOM:
case MADV_REMOVE:
case MADV_WILLNEED:
case MADV_DONTNEED:
case MADV_FREE:
#ifdef CONFIG_KSM
case MADV_MERGEABLE:
case MADV_UNMERGEABLE:
#endif
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
case MADV_HUGEPAGE:
case MADV_NOHUGEPAGE:
#endif
case MADV_DONTDUMP:
case MADV_DODUMP:
case MADV_WIPEONFORK:
case MADV_KEEPONFORK:
#ifdef CONFIG_MEMORY_FAILURE
case MADV_SOFT_OFFLINE:
case MADV_HWPOISON:
#endif
return true;
default:
return false;
}
}
/*
* The madvise(2) system call.
*
* Applications can use madvise() to advise the kernel how it should
* handle paging I/O in this VM area. The idea is to help the kernel
* use appropriate read-ahead and caching techniques. The information
* provided is advisory only, and can be safely disregarded by the
* kernel without affecting the correct operation of the application.
*
* behavior values:
* MADV_NORMAL - the default behavior is to read clusters. This
* results in some read-ahead and read-behind.
* MADV_RANDOM - the system should read the minimum amount of data
* on any access, since it is unlikely that the appli-
* cation will need more than what it asks for.
* MADV_SEQUENTIAL - pages in the given range will probably be accessed
* once, so they can be aggressively read ahead, and
* can be freed soon after they are accessed.
* MADV_WILLNEED - the application is notifying the system to read
* some pages ahead.
* MADV_DONTNEED - the application is finished with the given range,
* so the kernel can free resources associated with it.
* MADV_FREE - the application marks pages in the given range as lazy free,
* where actual purges are postponed until memory pressure happens.
* MADV_REMOVE - the application wants to free up the given range of
* pages and associated backing store.
* MADV_DONTFORK - omit this area from child's address space when forking:
* typically, to avoid COWing pages pinned by get_user_pages().
* MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
* MADV_WIPEONFORK - present the child process with zero-filled memory in this
* range after a fork.
* MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
* MADV_HWPOISON - trigger memory error handler as if the given memory range
* were corrupted by unrecoverable hardware memory failure.
* MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
* MADV_MERGEABLE - the application recommends that KSM try to merge pages in
* this area with pages of identical content from other such areas.
* MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
* MADV_HUGEPAGE - the application wants to back the given range by transparent
* huge pages in the future. Existing pages might be coalesced and
* new pages might be allocated as THP.
* MADV_NOHUGEPAGE - mark the given range as not worth being backed by
* transparent huge pages so the existing pages will not be
* coalesced into THP and new pages will not be allocated as THP.
* MADV_DONTDUMP - the application wants to prevent pages in the given range
* from being included in its core dump.
* MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
*
* return values:
* zero - success
* -EINVAL - start + len < 0, start is not page-aligned,
* "behavior" is not a valid value, or application
* is attempting to release locked or shared pages,
* or the specified address range includes file, Huge TLB,
* MAP_SHARED or VMPFNMAP range.
* -ENOMEM - addresses in the specified range are not currently
* mapped, or are outside the AS of the process.
* -EIO - an I/O error occurred while paging in data.
* -EBADF - map exists, but area maps something that isn't a file.
* -EAGAIN - a kernel resource was temporarily unavailable.
*/
SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
{
unsigned long end, tmp;
struct vm_area_struct *vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
int write;
size_t len;
struct blk_plug plug;
if (!madvise_behavior_valid(behavior))
return error;
if (start & ~PAGE_MASK)
return error;
len = (len_in + ~PAGE_MASK) & PAGE_MASK;
/* Check to see whether len was rounded up from small -ve to zero */
if (len_in && !len)
return error;
end = start + len;
if (end < start)
return error;
error = 0;
if (end == start)
return error;
#ifdef CONFIG_MEMORY_FAILURE
if (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)
return madvise_inject_error(behavior, start, start + len_in);
#endif
write = madvise_need_mmap_write(behavior);
if (write) {
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
} else {
down_read(¤t->mm->mmap_sem);
}
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - different from the way of handling in mlock etc.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
blk_start_plug(&plug);
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
goto out;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
goto out;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = madvise_vma(vma, &prev, start, tmp, behavior);
if (error)
goto out;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
goto out;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
out:
blk_finish_plug(&plug);
if (write)
up_write(¤t->mm->mmap_sem);
else
up_read(¤t->mm->mmap_sem);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_3016_0 |
crossvul-cpp_data_good_3169_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.
*
* Implementation of the Transmission Control Protocol(TCP).
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
* Corey Minyard <wf-rch!minyard@relay.EU.net>
* Florian La Roche, <flla@stud.uni-sb.de>
* Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
* Linus Torvalds, <torvalds@cs.helsinki.fi>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
* Matthew Dillon, <dillon@apollo.west.oic.com>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Jorge Cwik, <jorge@laser.satlink.net>
*
* Fixes:
* Alan Cox : Numerous verify_area() calls
* Alan Cox : Set the ACK bit on a reset
* Alan Cox : Stopped it crashing if it closed while
* sk->inuse=1 and was trying to connect
* (tcp_err()).
* Alan Cox : All icmp error handling was broken
* pointers passed where wrong and the
* socket was looked up backwards. Nobody
* tested any icmp error code obviously.
* Alan Cox : tcp_err() now handled properly. It
* wakes people on errors. poll
* behaves and the icmp error race
* has gone by moving it into sock.c
* Alan Cox : tcp_send_reset() fixed to work for
* everything not just packets for
* unknown sockets.
* Alan Cox : tcp option processing.
* Alan Cox : Reset tweaked (still not 100%) [Had
* syn rule wrong]
* Herp Rosmanith : More reset fixes
* Alan Cox : No longer acks invalid rst frames.
* Acking any kind of RST is right out.
* Alan Cox : Sets an ignore me flag on an rst
* receive otherwise odd bits of prattle
* escape still
* Alan Cox : Fixed another acking RST frame bug.
* Should stop LAN workplace lockups.
* Alan Cox : Some tidyups using the new skb list
* facilities
* Alan Cox : sk->keepopen now seems to work
* Alan Cox : Pulls options out correctly on accepts
* Alan Cox : Fixed assorted sk->rqueue->next errors
* Alan Cox : PSH doesn't end a TCP read. Switched a
* bit to skb ops.
* Alan Cox : Tidied tcp_data to avoid a potential
* nasty.
* Alan Cox : Added some better commenting, as the
* tcp is hard to follow
* Alan Cox : Removed incorrect check for 20 * psh
* Michael O'Reilly : ack < copied bug fix.
* Johannes Stille : Misc tcp fixes (not all in yet).
* Alan Cox : FIN with no memory -> CRASH
* Alan Cox : Added socket option proto entries.
* Also added awareness of them to accept.
* Alan Cox : Added TCP options (SOL_TCP)
* Alan Cox : Switched wakeup calls to callbacks,
* so the kernel can layer network
* sockets.
* Alan Cox : Use ip_tos/ip_ttl settings.
* Alan Cox : Handle FIN (more) properly (we hope).
* Alan Cox : RST frames sent on unsynchronised
* state ack error.
* Alan Cox : Put in missing check for SYN bit.
* Alan Cox : Added tcp_select_window() aka NET2E
* window non shrink trick.
* Alan Cox : Added a couple of small NET2E timer
* fixes
* Charles Hedrick : TCP fixes
* Toomas Tamm : TCP window fixes
* Alan Cox : Small URG fix to rlogin ^C ack fight
* Charles Hedrick : Rewrote most of it to actually work
* Linus : Rewrote tcp_read() and URG handling
* completely
* Gerhard Koerting: Fixed some missing timer handling
* Matthew Dillon : Reworked TCP machine states as per RFC
* Gerhard Koerting: PC/TCP workarounds
* Adam Caldwell : Assorted timer/timing errors
* Matthew Dillon : Fixed another RST bug
* Alan Cox : Move to kernel side addressing changes.
* Alan Cox : Beginning work on TCP fastpathing
* (not yet usable)
* Arnt Gulbrandsen: Turbocharged tcp_check() routine.
* Alan Cox : TCP fast path debugging
* Alan Cox : Window clamping
* Michael Riepe : Bug in tcp_check()
* Matt Dillon : More TCP improvements and RST bug fixes
* Matt Dillon : Yet more small nasties remove from the
* TCP code (Be very nice to this man if
* tcp finally works 100%) 8)
* Alan Cox : BSD accept semantics.
* Alan Cox : Reset on closedown bug.
* Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
* Michael Pall : Handle poll() after URG properly in
* all cases.
* Michael Pall : Undo the last fix in tcp_read_urg()
* (multi URG PUSH broke rlogin).
* Michael Pall : Fix the multi URG PUSH problem in
* tcp_readable(), poll() after URG
* works now.
* Michael Pall : recv(...,MSG_OOB) never blocks in the
* BSD api.
* Alan Cox : Changed the semantics of sk->socket to
* fix a race and a signal problem with
* accept() and async I/O.
* Alan Cox : Relaxed the rules on tcp_sendto().
* Yury Shevchuk : Really fixed accept() blocking problem.
* Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
* clients/servers which listen in on
* fixed ports.
* Alan Cox : Cleaned the above up and shrank it to
* a sensible code size.
* Alan Cox : Self connect lockup fix.
* Alan Cox : No connect to multicast.
* Ross Biro : Close unaccepted children on master
* socket close.
* Alan Cox : Reset tracing code.
* Alan Cox : Spurious resets on shutdown.
* Alan Cox : Giant 15 minute/60 second timer error
* Alan Cox : Small whoops in polling before an
* accept.
* Alan Cox : Kept the state trace facility since
* it's handy for debugging.
* Alan Cox : More reset handler fixes.
* Alan Cox : Started rewriting the code based on
* the RFC's for other useful protocol
* references see: Comer, KA9Q NOS, and
* for a reference on the difference
* between specifications and how BSD
* works see the 4.4lite source.
* A.N.Kuznetsov : Don't time wait on completion of tidy
* close.
* Linus Torvalds : Fin/Shutdown & copied_seq changes.
* Linus Torvalds : Fixed BSD port reuse to work first syn
* Alan Cox : Reimplemented timers as per the RFC
* and using multiple timers for sanity.
* Alan Cox : Small bug fixes, and a lot of new
* comments.
* Alan Cox : Fixed dual reader crash by locking
* the buffers (much like datagram.c)
* Alan Cox : Fixed stuck sockets in probe. A probe
* now gets fed up of retrying without
* (even a no space) answer.
* Alan Cox : Extracted closing code better
* Alan Cox : Fixed the closing state machine to
* resemble the RFC.
* Alan Cox : More 'per spec' fixes.
* Jorge Cwik : Even faster checksumming.
* Alan Cox : tcp_data() doesn't ack illegal PSH
* only frames. At least one pc tcp stack
* generates them.
* Alan Cox : Cache last socket.
* Alan Cox : Per route irtt.
* Matt Day : poll()->select() match BSD precisely on error
* Alan Cox : New buffers
* Marc Tamsky : Various sk->prot->retransmits and
* sk->retransmits misupdating fixed.
* Fixed tcp_write_timeout: stuck close,
* and TCP syn retries gets used now.
* Mark Yarvis : In tcp_read_wakeup(), don't send an
* ack if state is TCP_CLOSED.
* Alan Cox : Look up device on a retransmit - routes may
* change. Doesn't yet cope with MSS shrink right
* but it's a start!
* Marc Tamsky : Closing in closing fixes.
* Mike Shaver : RFC1122 verifications.
* Alan Cox : rcv_saddr errors.
* Alan Cox : Block double connect().
* Alan Cox : Small hooks for enSKIP.
* Alexey Kuznetsov: Path MTU discovery.
* Alan Cox : Support soft errors.
* Alan Cox : Fix MTU discovery pathological case
* when the remote claims no mtu!
* Marc Tamsky : TCP_CLOSE fix.
* Colin (G3TNE) : Send a reset on syn ack replies in
* window but wrong (fixes NT lpd problems)
* Pedro Roque : Better TCP window handling, delayed ack.
* Joerg Reuter : No modification of locked buffers in
* tcp_do_retransmit()
* Eric Schenk : Changed receiver side silly window
* avoidance algorithm to BSD style
* algorithm. This doubles throughput
* against machines running Solaris,
* and seems to result in general
* improvement.
* Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
* Willy Konynenberg : Transparent proxying support.
* Mike McLagan : Routing by source
* Keith Owens : Do proper merging with partial SKB's in
* tcp_do_sendmsg to avoid burstiness.
* Eric Schenk : Fix fast close down bug with
* shutdown() followed by close().
* Andi Kleen : Make poll agree with SIGIO
* Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
* lingertime == 0 (RFC 793 ABORT Call)
* Hirokazu Takahashi : Use copy_from_user() instead of
* csum_and_copy_from_user() if possible.
*
* 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.
*
* Description of States:
*
* TCP_SYN_SENT sent a connection request, waiting for ack
*
* TCP_SYN_RECV received a connection request, sent ack,
* waiting for final ack in three-way handshake.
*
* TCP_ESTABLISHED connection established
*
* TCP_FIN_WAIT1 our side has shutdown, waiting to complete
* transmission of remaining buffered data
*
* TCP_FIN_WAIT2 all buffered data sent, waiting for remote
* to shutdown
*
* TCP_CLOSING both sides have shutdown but we still have
* data we have to finish sending
*
* TCP_TIME_WAIT timeout to catch resent junk before entering
* closed, can only be entered from FIN_WAIT2
* or CLOSING. Required because the other end
* may not have gotten our last ACK causing it
* to retransmit the data packet (which we ignore)
*
* TCP_CLOSE_WAIT remote side has shutdown and is waiting for
* us to finish writing our data and to shutdown
* (we have to close() to move on to LAST_ACK)
*
* TCP_LAST_ACK out side has shutdown after remote has
* shutdown. There may still be data in our
* buffer that we have to finish sending
*
* TCP_CLOSE socket is finished
*/
#define pr_fmt(fmt) "TCP: " fmt
#include <crypto/hash.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/inet_diag.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/skbuff.h>
#include <linux/scatterlist.h>
#include <linux/splice.h>
#include <linux/net.h>
#include <linux/socket.h>
#include <linux/random.h>
#include <linux/bootmem.h>
#include <linux/highmem.h>
#include <linux/swap.h>
#include <linux/cache.h>
#include <linux/err.h>
#include <linux/time.h>
#include <linux/slab.h>
#include <net/icmp.h>
#include <net/inet_common.h>
#include <net/tcp.h>
#include <net/xfrm.h>
#include <net/ip.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <net/busy_poll.h>
int sysctl_tcp_min_tso_segs __read_mostly = 2;
int sysctl_tcp_autocorking __read_mostly = 1;
struct percpu_counter tcp_orphan_count;
EXPORT_SYMBOL_GPL(tcp_orphan_count);
long sysctl_tcp_mem[3] __read_mostly;
int sysctl_tcp_wmem[3] __read_mostly;
int sysctl_tcp_rmem[3] __read_mostly;
EXPORT_SYMBOL(sysctl_tcp_mem);
EXPORT_SYMBOL(sysctl_tcp_rmem);
EXPORT_SYMBOL(sysctl_tcp_wmem);
atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
EXPORT_SYMBOL(tcp_memory_allocated);
/*
* Current number of TCP sockets.
*/
struct percpu_counter tcp_sockets_allocated;
EXPORT_SYMBOL(tcp_sockets_allocated);
/*
* TCP splice context
*/
struct tcp_splice_state {
struct pipe_inode_info *pipe;
size_t len;
unsigned int flags;
};
/*
* Pressure flag: try to collapse.
* Technical note: it is used by multiple contexts non atomically.
* All the __sk_mem_schedule() is of this nature: accounting
* is strict, actions are advisory and have some latency.
*/
int tcp_memory_pressure __read_mostly;
EXPORT_SYMBOL(tcp_memory_pressure);
void tcp_enter_memory_pressure(struct sock *sk)
{
if (!tcp_memory_pressure) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
tcp_memory_pressure = 1;
}
}
EXPORT_SYMBOL(tcp_enter_memory_pressure);
/* Convert seconds to retransmits based on initial and max timeout */
static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
{
u8 res = 0;
if (seconds > 0) {
int period = timeout;
res = 1;
while (seconds > period && res < 255) {
res++;
timeout <<= 1;
if (timeout > rto_max)
timeout = rto_max;
period += timeout;
}
}
return res;
}
/* Convert retransmits to seconds based on initial and max timeout */
static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
{
int period = 0;
if (retrans > 0) {
period = timeout;
while (--retrans) {
timeout <<= 1;
if (timeout > rto_max)
timeout = rto_max;
period += timeout;
}
}
return period;
}
/* Address-family independent initialization for a tcp_sock.
*
* NOTE: A lot of things set to zero explicitly by call to
* sk_alloc() so need not be done here.
*/
void tcp_init_sock(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
tp->out_of_order_queue = RB_ROOT;
tcp_init_xmit_timers(sk);
tcp_prequeue_init(tp);
INIT_LIST_HEAD(&tp->tsq_node);
icsk->icsk_rto = TCP_TIMEOUT_INIT;
tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
minmax_reset(&tp->rtt_min, tcp_time_stamp, ~0U);
/* So many TCP implementations out there (incorrectly) count the
* initial SYN frame in their delayed-ACK and congestion control
* algorithms that we must have the following bandaid to talk
* efficiently to them. -DaveM
*/
tp->snd_cwnd = TCP_INIT_CWND;
/* There's a bubble in the pipe until at least the first ACK. */
tp->app_limited = ~0U;
/* See draft-stevens-tcpca-spec-01 for discussion of the
* initialization of these values.
*/
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_clamp = ~0;
tp->mss_cache = TCP_MSS_DEFAULT;
tp->reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering;
tcp_enable_early_retrans(tp);
tcp_assign_congestion_control(sk);
tp->tsoffset = 0;
sk->sk_state = TCP_CLOSE;
sk->sk_write_space = sk_stream_write_space;
sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
icsk->icsk_sync_mss = tcp_sync_mss;
sk->sk_sndbuf = sysctl_tcp_wmem[1];
sk->sk_rcvbuf = sysctl_tcp_rmem[1];
local_bh_disable();
sk_sockets_allocated_inc(sk);
local_bh_enable();
}
EXPORT_SYMBOL(tcp_init_sock);
static void tcp_tx_timestamp(struct sock *sk, u16 tsflags, struct sk_buff *skb)
{
if (tsflags) {
struct skb_shared_info *shinfo = skb_shinfo(skb);
struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
if (tsflags & SOF_TIMESTAMPING_TX_ACK)
tcb->txstamp_ack = 1;
if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
}
}
/*
* Wait for a TCP event.
*
* Note that we don't need to lock the socket, as the upper poll layers
* take care of normal races (between the test and the event) and we don't
* go look at any of the socket buffers directly.
*/
unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
unsigned int mask;
struct sock *sk = sock->sk;
const struct tcp_sock *tp = tcp_sk(sk);
int state;
sock_rps_record_flow(sk);
sock_poll_wait(file, sk_sleep(sk), wait);
state = sk_state_load(sk);
if (state == TCP_LISTEN)
return inet_csk_listen_poll(sk);
/* Socket is not locked. We are protected from async events
* by poll logic and correct handling of state changes
* made by other threads is impossible in any case.
*/
mask = 0;
/*
* POLLHUP is certainly not done right. But poll() doesn't
* have a notion of HUP in just one direction, and for a
* socket the read side is more interesting.
*
* Some poll() documentation says that POLLHUP is incompatible
* with the POLLOUT/POLLWR flags, so somebody should check this
* all. But careful, it tends to be safer to return too many
* bits than too few, and you can easily break real applications
* if you don't tell them that something has hung up!
*
* Check-me.
*
* Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
* our fs/select.c). It means that after we received EOF,
* poll always returns immediately, making impossible poll() on write()
* in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
* if and only if shutdown has been made in both directions.
* Actually, it is interesting to look how Solaris and DUX
* solve this dilemma. I would prefer, if POLLHUP were maskable,
* then we could set it on SND_SHUTDOWN. BTW examples given
* in Stevens' books assume exactly this behaviour, it explains
* why POLLHUP is incompatible with POLLOUT. --ANK
*
* NOTE. Check for TCP_CLOSE is added. The goal is to prevent
* blocking on fresh not-connected or disconnected socket. --ANK
*/
if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLIN | POLLRDNORM | POLLRDHUP;
/* Connected or passive Fast Open socket? */
if (state != TCP_SYN_SENT &&
(state != TCP_SYN_RECV || tp->fastopen_rsk)) {
int target = sock_rcvlowat(sk, 0, INT_MAX);
if (tp->urg_seq == tp->copied_seq &&
!sock_flag(sk, SOCK_URGINLINE) &&
tp->urg_data)
target++;
if (tp->rcv_nxt - tp->copied_seq >= target)
mask |= POLLIN | POLLRDNORM;
if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
if (sk_stream_is_writeable(sk)) {
mask |= POLLOUT | POLLWRNORM;
} else { /* send SIGIO later */
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
/* Race breaker. If space is freed after
* wspace test but before the flags are set,
* IO signal will be lost. Memory barrier
* pairs with the input side.
*/
smp_mb__after_atomic();
if (sk_stream_is_writeable(sk))
mask |= POLLOUT | POLLWRNORM;
}
} else
mask |= POLLOUT | POLLWRNORM;
if (tp->urg_data & TCP_URG_VALID)
mask |= POLLPRI;
}
/* This barrier is coupled with smp_wmb() in tcp_reset() */
smp_rmb();
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR;
return mask;
}
EXPORT_SYMBOL(tcp_poll);
int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
struct tcp_sock *tp = tcp_sk(sk);
int answ;
bool slow;
switch (cmd) {
case SIOCINQ:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
slow = lock_sock_fast(sk);
answ = tcp_inq(sk);
unlock_sock_fast(sk, slow);
break;
case SIOCATMARK:
answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
break;
case SIOCOUTQ:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
answ = 0;
else
answ = tp->write_seq - tp->snd_una;
break;
case SIOCOUTQNSD:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
answ = 0;
else
answ = tp->write_seq - tp->snd_nxt;
break;
default:
return -ENOIOCTLCMD;
}
return put_user(answ, (int __user *)arg);
}
EXPORT_SYMBOL(tcp_ioctl);
static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
{
TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
tp->pushed_seq = tp->write_seq;
}
static inline bool forced_push(const struct tcp_sock *tp)
{
return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
}
static void skb_entail(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
skb->csum = 0;
tcb->seq = tcb->end_seq = tp->write_seq;
tcb->tcp_flags = TCPHDR_ACK;
tcb->sacked = 0;
__skb_header_release(skb);
tcp_add_write_queue_tail(sk, skb);
sk->sk_wmem_queued += skb->truesize;
sk_mem_charge(sk, skb->truesize);
if (tp->nonagle & TCP_NAGLE_PUSH)
tp->nonagle &= ~TCP_NAGLE_PUSH;
tcp_slow_start_after_idle_check(sk);
}
static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
{
if (flags & MSG_OOB)
tp->snd_up = tp->write_seq;
}
/* If a not yet filled skb is pushed, do not send it if
* we have data packets in Qdisc or NIC queues :
* Because TX completion will happen shortly, it gives a chance
* to coalesce future sendmsg() payload into this skb, without
* need for a timer, and with no latency trade off.
* As packets containing data payload have a bigger truesize
* than pure acks (dataless) packets, the last checks prevent
* autocorking if we only have an ACK in Qdisc/NIC queues,
* or if TX completion was delayed after we processed ACK packet.
*/
static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
int size_goal)
{
return skb->len < size_goal &&
sysctl_tcp_autocorking &&
skb != tcp_write_queue_head(sk) &&
atomic_read(&sk->sk_wmem_alloc) > skb->truesize;
}
static void tcp_push(struct sock *sk, int flags, int mss_now,
int nonagle, int size_goal)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
if (!tcp_send_head(sk))
return;
skb = tcp_write_queue_tail(sk);
if (!(flags & MSG_MORE) || forced_push(tp))
tcp_mark_push(tp, skb);
tcp_mark_urg(tp, flags);
if (tcp_should_autocork(sk, skb, size_goal)) {
/* avoid atomic op if TSQ_THROTTLED bit is already set */
if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
}
/* It is possible TX completion already happened
* before we set TSQ_THROTTLED.
*/
if (atomic_read(&sk->sk_wmem_alloc) > skb->truesize)
return;
}
if (flags & MSG_MORE)
nonagle = TCP_NAGLE_CORK;
__tcp_push_pending_frames(sk, mss_now, nonagle);
}
static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
unsigned int offset, size_t len)
{
struct tcp_splice_state *tss = rd_desc->arg.data;
int ret;
ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
min(rd_desc->count, len), tss->flags);
if (ret > 0)
rd_desc->count -= ret;
return ret;
}
static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
{
/* Store TCP splice context information in read_descriptor_t. */
read_descriptor_t rd_desc = {
.arg.data = tss,
.count = tss->len,
};
return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
}
/**
* tcp_splice_read - splice data from TCP socket to a pipe
* @sock: socket to splice from
* @ppos: position (not valid)
* @pipe: pipe to splice to
* @len: number of bytes to splice
* @flags: splice modifier flags
*
* Description:
* Will read pages from given socket and fill them into a pipe.
*
**/
ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
/* if __tcp_splice_read() got nothing while we have
* an skb in receive queue, we do not want to loop.
* This might happen with URG data.
*/
if (!skb_queue_empty(&sk->sk_receive_queue))
break;
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
EXPORT_SYMBOL(tcp_splice_read);
struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
bool force_schedule)
{
struct sk_buff *skb;
/* The TCP header must be at least 32-bit aligned. */
size = ALIGN(size, 4);
if (unlikely(tcp_under_memory_pressure(sk)))
sk_mem_reclaim_partial(sk);
skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
if (likely(skb)) {
bool mem_scheduled;
if (force_schedule) {
mem_scheduled = true;
sk_forced_mem_schedule(sk, skb->truesize);
} else {
mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
}
if (likely(mem_scheduled)) {
skb_reserve(skb, sk->sk_prot->max_header);
/*
* Make sure that we have exactly size bytes
* available to the caller, no more, no less.
*/
skb->reserved_tailroom = skb->end - skb->tail - size;
return skb;
}
__kfree_skb(skb);
} else {
sk->sk_prot->enter_memory_pressure(sk);
sk_stream_moderate_sndbuf(sk);
}
return NULL;
}
static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
int large_allowed)
{
struct tcp_sock *tp = tcp_sk(sk);
u32 new_size_goal, size_goal;
if (!large_allowed || !sk_can_gso(sk))
return mss_now;
/* Note : tcp_tso_autosize() will eventually split this later */
new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER;
new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal);
/* We try hard to avoid divides here */
size_goal = tp->gso_segs * mss_now;
if (unlikely(new_size_goal < size_goal ||
new_size_goal >= size_goal + mss_now)) {
tp->gso_segs = min_t(u16, new_size_goal / mss_now,
sk->sk_gso_max_segs);
size_goal = tp->gso_segs * mss_now;
}
return max(size_goal, mss_now);
}
static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
{
int mss_now;
mss_now = tcp_current_mss(sk);
*size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
return mss_now;
}
static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
size_t size, int flags)
{
struct tcp_sock *tp = tcp_sk(sk);
int mss_now, size_goal;
int err;
ssize_t copied;
long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
/* Wait for a connection to finish. One exception is TCP Fast Open
* (passive side) where data is allowed to be sent before a connection
* is fully established.
*/
if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
!tcp_passive_fastopen(sk)) {
err = sk_stream_wait_connect(sk, &timeo);
if (err != 0)
goto out_err;
}
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
mss_now = tcp_send_mss(sk, &size_goal, flags);
copied = 0;
err = -EPIPE;
if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
goto out_err;
while (size > 0) {
struct sk_buff *skb = tcp_write_queue_tail(sk);
int copy, i;
bool can_coalesce;
if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 ||
!tcp_skb_can_collapse_to(skb)) {
new_segment:
if (!sk_stream_memory_free(sk))
goto wait_for_sndbuf;
skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation,
skb_queue_empty(&sk->sk_write_queue));
if (!skb)
goto wait_for_memory;
skb_entail(sk, skb);
copy = size_goal;
}
if (copy > size)
copy = size;
i = skb_shinfo(skb)->nr_frags;
can_coalesce = skb_can_coalesce(skb, i, page, offset);
if (!can_coalesce && i >= sysctl_max_skb_frags) {
tcp_mark_push(tp, skb);
goto new_segment;
}
if (!sk_wmem_schedule(sk, copy))
goto wait_for_memory;
if (can_coalesce) {
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
} else {
get_page(page);
skb_fill_page_desc(skb, i, page, offset, copy);
}
skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
sk->sk_wmem_queued += copy;
sk_mem_charge(sk, copy);
skb->ip_summed = CHECKSUM_PARTIAL;
tp->write_seq += copy;
TCP_SKB_CB(skb)->end_seq += copy;
tcp_skb_pcount_set(skb, 0);
if (!copied)
TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
copied += copy;
offset += copy;
size -= copy;
if (!size) {
tcp_tx_timestamp(sk, sk->sk_tsflags, skb);
goto out;
}
if (skb->len < size_goal || (flags & MSG_OOB))
continue;
if (forced_push(tp)) {
tcp_mark_push(tp, skb);
__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
} else if (skb == tcp_send_head(sk))
tcp_push_one(sk, mss_now);
continue;
wait_for_sndbuf:
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
tcp_push(sk, flags & ~MSG_MORE, mss_now,
TCP_NAGLE_PUSH, size_goal);
err = sk_stream_wait_memory(sk, &timeo);
if (err != 0)
goto do_error;
mss_now = tcp_send_mss(sk, &size_goal, flags);
}
out:
if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
return copied;
do_error:
if (copied)
goto out;
out_err:
/* make sure we wake any epoll edge trigger waiter */
if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
err == -EAGAIN)) {
sk->sk_write_space(sk);
tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
}
return sk_stream_error(sk, flags, err);
}
int tcp_sendpage(struct sock *sk, struct page *page, int offset,
size_t size, int flags)
{
ssize_t res;
if (!(sk->sk_route_caps & NETIF_F_SG) ||
!sk_check_csum_caps(sk))
return sock_no_sendpage(sk->sk_socket, page, offset, size,
flags);
lock_sock(sk);
tcp_rate_check_app_limited(sk); /* is sending application-limited? */
res = do_tcp_sendpages(sk, page, offset, size, flags);
release_sock(sk);
return res;
}
EXPORT_SYMBOL(tcp_sendpage);
/* Do not bother using a page frag for very small frames.
* But use this heuristic only for the first skb in write queue.
*
* Having no payload in skb->head allows better SACK shifting
* in tcp_shift_skb_data(), reducing sack/rack overhead, because
* write queue has less skbs.
* Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB.
* This also speeds up tso_fragment(), since it wont fallback
* to tcp_fragment().
*/
static int linear_payload_sz(bool first_skb)
{
if (first_skb)
return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
return 0;
}
static int select_size(const struct sock *sk, bool sg, bool first_skb)
{
const struct tcp_sock *tp = tcp_sk(sk);
int tmp = tp->mss_cache;
if (sg) {
if (sk_can_gso(sk)) {
tmp = linear_payload_sz(first_skb);
} else {
int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
if (tmp >= pgbreak &&
tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
tmp = pgbreak;
}
}
return tmp;
}
void tcp_free_fastopen_req(struct tcp_sock *tp)
{
if (tp->fastopen_req) {
kfree(tp->fastopen_req);
tp->fastopen_req = NULL;
}
}
static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg,
int *copied, size_t size)
{
struct tcp_sock *tp = tcp_sk(sk);
int err, flags;
if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE))
return -EOPNOTSUPP;
if (tp->fastopen_req)
return -EALREADY; /* Another Fast Open is in progress */
tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
sk->sk_allocation);
if (unlikely(!tp->fastopen_req))
return -ENOBUFS;
tp->fastopen_req->data = msg;
tp->fastopen_req->size = size;
flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
err = __inet_stream_connect(sk->sk_socket, msg->msg_name,
msg->msg_namelen, flags);
*copied = tp->fastopen_req->copied;
tcp_free_fastopen_req(tp);
return err;
}
int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
struct sockcm_cookie sockc;
int flags, err, copied = 0;
int mss_now = 0, size_goal, copied_syn = 0;
bool process_backlog = false;
bool sg;
long timeo;
lock_sock(sk);
flags = msg->msg_flags;
if (flags & MSG_FASTOPEN) {
err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size);
if (err == -EINPROGRESS && copied_syn > 0)
goto out;
else if (err)
goto out_err;
}
timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
tcp_rate_check_app_limited(sk); /* is sending application-limited? */
/* Wait for a connection to finish. One exception is TCP Fast Open
* (passive side) where data is allowed to be sent before a connection
* is fully established.
*/
if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
!tcp_passive_fastopen(sk)) {
err = sk_stream_wait_connect(sk, &timeo);
if (err != 0)
goto do_error;
}
if (unlikely(tp->repair)) {
if (tp->repair_queue == TCP_RECV_QUEUE) {
copied = tcp_send_rcvq(sk, msg, size);
goto out_nopush;
}
err = -EINVAL;
if (tp->repair_queue == TCP_NO_QUEUE)
goto out_err;
/* 'common' sending to sendq */
}
sockc.tsflags = sk->sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err)) {
err = -EINVAL;
goto out_err;
}
}
/* This should be in poll */
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
/* Ok commence sending. */
copied = 0;
restart:
mss_now = tcp_send_mss(sk, &size_goal, flags);
err = -EPIPE;
if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
goto do_error;
sg = !!(sk->sk_route_caps & NETIF_F_SG);
while (msg_data_left(msg)) {
int copy = 0;
int max = size_goal;
skb = tcp_write_queue_tail(sk);
if (tcp_send_head(sk)) {
if (skb->ip_summed == CHECKSUM_NONE)
max = mss_now;
copy = max - skb->len;
}
if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
bool first_skb;
new_segment:
/* Allocate new segment. If the interface is SG,
* allocate skb fitting to single page.
*/
if (!sk_stream_memory_free(sk))
goto wait_for_sndbuf;
if (process_backlog && sk_flush_backlog(sk)) {
process_backlog = false;
goto restart;
}
first_skb = skb_queue_empty(&sk->sk_write_queue);
skb = sk_stream_alloc_skb(sk,
select_size(sk, sg, first_skb),
sk->sk_allocation,
first_skb);
if (!skb)
goto wait_for_memory;
process_backlog = true;
/*
* Check whether we can use HW checksum.
*/
if (sk_check_csum_caps(sk))
skb->ip_summed = CHECKSUM_PARTIAL;
skb_entail(sk, skb);
copy = size_goal;
max = size_goal;
/* All packets are restored as if they have
* already been sent. skb_mstamp isn't set to
* avoid wrong rtt estimation.
*/
if (tp->repair)
TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
}
/* Try to append data to the end of skb. */
if (copy > msg_data_left(msg))
copy = msg_data_left(msg);
/* Where to copy to? */
if (skb_availroom(skb) > 0) {
/* We have some space in skb head. Superb! */
copy = min_t(int, copy, skb_availroom(skb));
err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy);
if (err)
goto do_fault;
} else {
bool merge = true;
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
if (!sk_page_frag_refill(sk, pfrag))
goto wait_for_memory;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
if (i >= sysctl_max_skb_frags || !sg) {
tcp_mark_push(tp, skb);
goto new_segment;
}
merge = false;
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (!sk_wmem_schedule(sk, copy))
goto wait_for_memory;
err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
pfrag->page,
pfrag->offset,
copy);
if (err)
goto do_error;
/* Update the skb. */
if (merge) {
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
} else {
skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, copy);
get_page(pfrag->page);
}
pfrag->offset += copy;
}
if (!copied)
TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
tp->write_seq += copy;
TCP_SKB_CB(skb)->end_seq += copy;
tcp_skb_pcount_set(skb, 0);
copied += copy;
if (!msg_data_left(msg)) {
tcp_tx_timestamp(sk, sockc.tsflags, skb);
if (unlikely(flags & MSG_EOR))
TCP_SKB_CB(skb)->eor = 1;
goto out;
}
if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair))
continue;
if (forced_push(tp)) {
tcp_mark_push(tp, skb);
__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
} else if (skb == tcp_send_head(sk))
tcp_push_one(sk, mss_now);
continue;
wait_for_sndbuf:
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
if (copied)
tcp_push(sk, flags & ~MSG_MORE, mss_now,
TCP_NAGLE_PUSH, size_goal);
err = sk_stream_wait_memory(sk, &timeo);
if (err != 0)
goto do_error;
mss_now = tcp_send_mss(sk, &size_goal, flags);
}
out:
if (copied)
tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
out_nopush:
release_sock(sk);
return copied + copied_syn;
do_fault:
if (!skb->len) {
tcp_unlink_write_queue(skb, sk);
/* It is the one place in all of TCP, except connection
* reset, where we can be unlinking the send_head.
*/
tcp_check_send_head(sk, skb);
sk_wmem_free_skb(sk, skb);
}
do_error:
if (copied + copied_syn)
goto out;
out_err:
err = sk_stream_error(sk, flags, err);
/* make sure we wake any epoll edge trigger waiter */
if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
err == -EAGAIN)) {
sk->sk_write_space(sk);
tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
}
release_sock(sk);
return err;
}
EXPORT_SYMBOL(tcp_sendmsg);
/*
* Handle reading urgent data. BSD has very simple semantics for
* this, no blocking and very strange errors 8)
*/
static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
{
struct tcp_sock *tp = tcp_sk(sk);
/* No URG data to read. */
if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
tp->urg_data == TCP_URG_READ)
return -EINVAL; /* Yes this is right ! */
if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
return -ENOTCONN;
if (tp->urg_data & TCP_URG_VALID) {
int err = 0;
char c = tp->urg_data;
if (!(flags & MSG_PEEK))
tp->urg_data = TCP_URG_READ;
/* Read urgent data. */
msg->msg_flags |= MSG_OOB;
if (len > 0) {
if (!(flags & MSG_TRUNC))
err = memcpy_to_msg(msg, &c, 1);
len = 1;
} else
msg->msg_flags |= MSG_TRUNC;
return err ? -EFAULT : len;
}
if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
return 0;
/* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
* the available implementations agree in this case:
* this call should never block, independent of the
* blocking state of the socket.
* Mike <pall@rz.uni-karlsruhe.de>
*/
return -EAGAIN;
}
static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
{
struct sk_buff *skb;
int copied = 0, err = 0;
/* XXX -- need to support SO_PEEK_OFF */
skb_queue_walk(&sk->sk_write_queue, skb) {
err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
if (err)
break;
copied += skb->len;
}
return err ?: copied;
}
/* Clean up the receive buffer for full frames taken by the user,
* then send an ACK if necessary. COPIED is the number of bytes
* tcp_recvmsg has given to the user so far, it speeds up the
* calculation of whether or not we must ACK for the sake of
* a window update.
*/
static void tcp_cleanup_rbuf(struct sock *sk, int copied)
{
struct tcp_sock *tp = tcp_sk(sk);
bool time_to_ack = false;
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
"cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
if (inet_csk_ack_scheduled(sk)) {
const struct inet_connection_sock *icsk = inet_csk(sk);
/* Delayed ACKs frequently hit locked sockets during bulk
* receive. */
if (icsk->icsk_ack.blocked ||
/* Once-per-two-segments ACK was not sent by tcp_input.c */
tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
/*
* If this read emptied read buffer, we send ACK, if
* connection is not bidirectional, user drained
* receive buffer and there was a small segment
* in queue.
*/
(copied > 0 &&
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
!icsk->icsk_ack.pingpong)) &&
!atomic_read(&sk->sk_rmem_alloc)))
time_to_ack = true;
}
/* We send an ACK if we can now advertise a non-zero window
* which has been raised "significantly".
*
* Even if window raised up to infinity, do not send window open ACK
* in states, where we will not receive more. It is useless.
*/
if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
__u32 rcv_window_now = tcp_receive_window(tp);
/* Optimize, __tcp_select_window() is not cheap. */
if (2*rcv_window_now <= tp->window_clamp) {
__u32 new_window = __tcp_select_window(sk);
/* Send ACK now, if this read freed lots of space
* in our buffer. Certainly, new_window is new window.
* We can advertise it now, if it is not less than current one.
* "Lots" means "at least twice" here.
*/
if (new_window && new_window >= 2 * rcv_window_now)
time_to_ack = true;
}
}
if (time_to_ack)
tcp_send_ack(sk);
}
static void tcp_prequeue_process(struct sock *sk)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
sk_backlog_rcv(sk, skb);
/* Clear memory counter. */
tp->ucopy.memory = 0;
}
static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
{
struct sk_buff *skb;
u32 offset;
while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
offset = seq - TCP_SKB_CB(skb)->seq;
if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
pr_err_once("%s: found a SYN, please report !\n", __func__);
offset--;
}
if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
*off = offset;
return skb;
}
/* This looks weird, but this can happen if TCP collapsing
* splitted a fat GRO packet, while we released socket lock
* in skb_splice_bits()
*/
sk_eat_skb(sk, skb);
}
return NULL;
}
/*
* This routine provides an alternative to tcp_recvmsg() for routines
* that would like to handle copying from skbuffs directly in 'sendfile'
* fashion.
* Note:
* - It is assumed that the socket was locked by the caller.
* - The routine does not block.
* - At present, there is no support for reading OOB data
* or for 'peeking' the socket using this routine
* (although both would be easy to implement).
*/
int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used <= 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq - 1, &offset);
if (!skb)
break;
/* TCP coalescing might have appended data to the skb.
* Try to splice more frags
*/
if (offset + 1 != skb->len)
continue;
}
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
sk_eat_skb(sk, skb);
++seq;
break;
}
sk_eat_skb(sk, skb);
if (!desc->count)
break;
tp->copied_seq = seq;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0) {
tcp_recv_skb(sk, seq, &offset);
tcp_cleanup_rbuf(sk, copied);
}
return copied;
}
EXPORT_SYMBOL(tcp_read_sock);
int tcp_peek_len(struct socket *sock)
{
return tcp_inq(sock->sk);
}
EXPORT_SYMBOL(tcp_peek_len);
/*
* This routine copies from a sock struct into the user buffer.
*
* Technical note: in 2.3 we work on _locked_ socket, so that
* tricks with *seq access order and skb->users are not required.
* Probably, code can be easily improved even more.
*/
int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock,
int flags, int *addr_len)
{
struct tcp_sock *tp = tcp_sk(sk);
int copied = 0;
u32 peek_seq;
u32 *seq;
unsigned long used;
int err;
int target; /* Read at least this many bytes */
long timeo;
struct task_struct *user_recv = NULL;
struct sk_buff *skb, *last;
u32 urg_hole = 0;
if (unlikely(flags & MSG_ERRQUEUE))
return inet_recv_error(sk, msg, len, addr_len);
if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) &&
(sk->sk_state == TCP_ESTABLISHED))
sk_busy_loop(sk, nonblock);
lock_sock(sk);
err = -ENOTCONN;
if (sk->sk_state == TCP_LISTEN)
goto out;
timeo = sock_rcvtimeo(sk, nonblock);
/* Urgent data needs to be handled specially. */
if (flags & MSG_OOB)
goto recv_urg;
if (unlikely(tp->repair)) {
err = -EPERM;
if (!(flags & MSG_PEEK))
goto out;
if (tp->repair_queue == TCP_SEND_QUEUE)
goto recv_sndq;
err = -EINVAL;
if (tp->repair_queue == TCP_NO_QUEUE)
goto out;
/* 'common' recv queue MSG_PEEK-ing */
}
seq = &tp->copied_seq;
if (flags & MSG_PEEK) {
peek_seq = tp->copied_seq;
seq = &peek_seq;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
do {
u32 offset;
/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
if (tp->urg_data && tp->urg_seq == *seq) {
if (copied)
break;
if (signal_pending(current)) {
copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
break;
}
}
/* Next get a buffer. */
last = skb_peek_tail(&sk->sk_receive_queue);
skb_queue_walk(&sk->sk_receive_queue, skb) {
last = skb;
/* Now that we have two receive queues this
* shouldn't happen.
*/
if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
"recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
*seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
flags))
break;
offset = *seq - TCP_SKB_CB(skb)->seq;
if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
pr_err_once("%s: found a SYN, please report !\n", __func__);
offset--;
}
if (offset < skb->len)
goto found_ok_skb;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
goto found_fin_ok;
WARN(!(flags & MSG_PEEK),
"recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
*seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
}
/* Well, if we have backlog, try to process it now yet. */
if (copied >= target && !sk->sk_backlog.tail)
break;
if (copied) {
if (sk->sk_err ||
sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
!timeo ||
signal_pending(current))
break;
} else {
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
copied = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
if (!sock_flag(sk, SOCK_DONE)) {
/* This occurs when user tries to read
* from never connected socket.
*/
copied = -ENOTCONN;
break;
}
break;
}
if (!timeo) {
copied = -EAGAIN;
break;
}
if (signal_pending(current)) {
copied = sock_intr_errno(timeo);
break;
}
}
tcp_cleanup_rbuf(sk, copied);
if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
/* Install new reader */
if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
user_recv = current;
tp->ucopy.task = user_recv;
tp->ucopy.msg = msg;
}
tp->ucopy.len = len;
WARN_ON(tp->copied_seq != tp->rcv_nxt &&
!(flags & (MSG_PEEK | MSG_TRUNC)));
/* Ugly... If prequeue is not empty, we have to
* process it before releasing socket, otherwise
* order will be broken at second iteration.
* More elegant solution is required!!!
*
* Look: we have the following (pseudo)queues:
*
* 1. packets in flight
* 2. backlog
* 3. prequeue
* 4. receive_queue
*
* Each queue can be processed only if the next ones
* are empty. At this point we have empty receive_queue.
* But prequeue _can_ be not empty after 2nd iteration,
* when we jumped to start of loop because backlog
* processing added something to receive_queue.
* We cannot release_sock(), because backlog contains
* packets arrived _after_ prequeued ones.
*
* Shortly, algorithm is clear --- to process all
* the queues in order. We could make it more directly,
* requeueing packets from backlog to prequeue, if
* is not empty. It is more elegant, but eats cycles,
* unfortunately.
*/
if (!skb_queue_empty(&tp->ucopy.prequeue))
goto do_prequeue;
/* __ Set realtime policy in scheduler __ */
}
if (copied >= target) {
/* Do not sleep, just process backlog. */
release_sock(sk);
lock_sock(sk);
} else {
sk_wait_data(sk, &timeo, last);
}
if (user_recv) {
int chunk;
/* __ Restore normal policy in scheduler __ */
chunk = len - tp->ucopy.len;
if (chunk != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
len -= chunk;
copied += chunk;
}
if (tp->rcv_nxt == tp->copied_seq &&
!skb_queue_empty(&tp->ucopy.prequeue)) {
do_prequeue:
tcp_prequeue_process(sk);
chunk = len - tp->ucopy.len;
if (chunk != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
len -= chunk;
copied += chunk;
}
}
}
if ((flags & MSG_PEEK) &&
(peek_seq - copied - urg_hole != tp->copied_seq)) {
net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
current->comm,
task_pid_nr(current));
peek_seq = tp->copied_seq;
}
continue;
found_ok_skb:
/* Ok so how much can we use? */
used = skb->len - offset;
if (len < used)
used = len;
/* Do we have urgent data here? */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - *seq;
if (urg_offset < used) {
if (!urg_offset) {
if (!sock_flag(sk, SOCK_URGINLINE)) {
++*seq;
urg_hole++;
offset++;
used--;
if (!used)
goto skip_copy;
}
} else
used = urg_offset;
}
}
if (!(flags & MSG_TRUNC)) {
err = skb_copy_datagram_msg(skb, offset, msg, used);
if (err) {
/* Exception. Bailout! */
if (!copied)
copied = -EFAULT;
break;
}
}
*seq += used;
copied += used;
len -= used;
tcp_rcv_space_adjust(sk);
skip_copy:
if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
tp->urg_data = 0;
tcp_fast_path_check(sk);
}
if (used + offset < skb->len)
continue;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
goto found_fin_ok;
if (!(flags & MSG_PEEK))
sk_eat_skb(sk, skb);
continue;
found_fin_ok:
/* Process the FIN. */
++*seq;
if (!(flags & MSG_PEEK))
sk_eat_skb(sk, skb);
break;
} while (len > 0);
if (user_recv) {
if (!skb_queue_empty(&tp->ucopy.prequeue)) {
int chunk;
tp->ucopy.len = copied > 0 ? len : 0;
tcp_prequeue_process(sk);
if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
len -= chunk;
copied += chunk;
}
}
tp->ucopy.task = NULL;
tp->ucopy.len = 0;
}
/* According to UNIX98, msg_name/msg_namelen are ignored
* on connected socket. I was just happy when found this 8) --ANK
*/
/* Clean up data we have read: This will do ACK frames. */
tcp_cleanup_rbuf(sk, copied);
release_sock(sk);
return copied;
out:
release_sock(sk);
return err;
recv_urg:
err = tcp_recv_urg(sk, msg, len, flags);
goto out;
recv_sndq:
err = tcp_peek_sndq(sk, msg, len);
goto out;
}
EXPORT_SYMBOL(tcp_recvmsg);
void tcp_set_state(struct sock *sk, int state)
{
int oldstate = sk->sk_state;
switch (state) {
case TCP_ESTABLISHED:
if (oldstate != TCP_ESTABLISHED)
TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
break;
case TCP_CLOSE:
if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
sk->sk_prot->unhash(sk);
if (inet_csk(sk)->icsk_bind_hash &&
!(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
inet_put_port(sk);
/* fall through */
default:
if (oldstate == TCP_ESTABLISHED)
TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
}
/* Change state AFTER socket is unhashed to avoid closed
* socket sitting in hash tables.
*/
sk_state_store(sk, state);
#ifdef STATE_TRACE
SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
#endif
}
EXPORT_SYMBOL_GPL(tcp_set_state);
/*
* State processing on a close. This implements the state shift for
* sending our FIN frame. Note that we only send a FIN for some
* states. A shutdown() may have already sent the FIN, or we may be
* closed.
*/
static const unsigned char new_state[16] = {
/* current state: new state: action: */
[0 /* (Invalid) */] = TCP_CLOSE,
[TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
[TCP_SYN_SENT] = TCP_CLOSE,
[TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
[TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
[TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
[TCP_TIME_WAIT] = TCP_CLOSE,
[TCP_CLOSE] = TCP_CLOSE,
[TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
[TCP_LAST_ACK] = TCP_LAST_ACK,
[TCP_LISTEN] = TCP_CLOSE,
[TCP_CLOSING] = TCP_CLOSING,
[TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
};
static int tcp_close_state(struct sock *sk)
{
int next = (int)new_state[sk->sk_state];
int ns = next & TCP_STATE_MASK;
tcp_set_state(sk, ns);
return next & TCP_ACTION_FIN;
}
/*
* Shutdown the sending side of a connection. Much like close except
* that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
*/
void tcp_shutdown(struct sock *sk, int how)
{
/* We need to grab some memory, and put together a FIN,
* and then put it into the queue to be sent.
* Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
*/
if (!(how & SEND_SHUTDOWN))
return;
/* If we've already sent a FIN, or it's a closed state, skip this. */
if ((1 << sk->sk_state) &
(TCPF_ESTABLISHED | TCPF_SYN_SENT |
TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
/* Clear out any half completed packets. FIN if needed. */
if (tcp_close_state(sk))
tcp_send_fin(sk);
}
}
EXPORT_SYMBOL(tcp_shutdown);
bool tcp_check_oom(struct sock *sk, int shift)
{
bool too_many_orphans, out_of_socket_memory;
too_many_orphans = tcp_too_many_orphans(sk, shift);
out_of_socket_memory = tcp_out_of_memory(sk);
if (too_many_orphans)
net_info_ratelimited("too many orphaned sockets\n");
if (out_of_socket_memory)
net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
return too_many_orphans || out_of_socket_memory;
}
void tcp_close(struct sock *sk, long timeout)
{
struct sk_buff *skb;
int data_was_unread = 0;
int state;
lock_sock(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
if (sk->sk_state == TCP_LISTEN) {
tcp_set_state(sk, TCP_CLOSE);
/* Special case. */
inet_csk_listen_stop(sk);
goto adjudge_to_death;
}
/* We need to flush the recv. buffs. We do this only on the
* descriptor close, not protocol-sourced closes, because the
* reader process may not have drained the data yet!
*/
while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
len--;
data_was_unread += len;
__kfree_skb(skb);
}
sk_mem_reclaim(sk);
/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
if (sk->sk_state == TCP_CLOSE)
goto adjudge_to_death;
/* As outlined in RFC 2525, section 2.17, we send a RST here because
* data was lost. To witness the awful effects of the old behavior of
* always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
* GET in an FTP client, suspend the process, wait for the client to
* advertise a zero window, then kill -9 the FTP client, wheee...
* Note: timeout is always zero in such a case.
*/
if (unlikely(tcp_sk(sk)->repair)) {
sk->sk_prot->disconnect(sk, 0);
} else if (data_was_unread) {
/* Unread data was tossed, zap the connection. */
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, sk->sk_allocation);
} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
/* Check zero linger _after_ checking for unread data. */
sk->sk_prot->disconnect(sk, 0);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
} else if (tcp_close_state(sk)) {
/* We FIN if the application ate all the data before
* zapping the connection.
*/
/* RED-PEN. Formally speaking, we have broken TCP state
* machine. State transitions:
*
* TCP_ESTABLISHED -> TCP_FIN_WAIT1
* TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
* TCP_CLOSE_WAIT -> TCP_LAST_ACK
*
* are legal only when FIN has been sent (i.e. in window),
* rather than queued out of window. Purists blame.
*
* F.e. "RFC state" is ESTABLISHED,
* if Linux state is FIN-WAIT-1, but FIN is still not sent.
*
* The visible declinations are that sometimes
* we enter time-wait state, when it is not required really
* (harmless), do not send active resets, when they are
* required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
* they look as CLOSING or LAST_ACK for Linux)
* Probably, I missed some more holelets.
* --ANK
* XXX (TFO) - To start off we don't support SYN+ACK+FIN
* in a single packet! (May consider it later but will
* probably need API support or TCP_CORK SYN-ACK until
* data is written and socket is closed.)
*/
tcp_send_fin(sk);
}
sk_stream_wait_close(sk, timeout);
adjudge_to_death:
state = sk->sk_state;
sock_hold(sk);
sock_orphan(sk);
/* It is the last release_sock in its life. It will remove backlog. */
release_sock(sk);
/* Now socket is owned by kernel and we acquire BH lock
to finish close. No need to check for user refs.
*/
local_bh_disable();
bh_lock_sock(sk);
WARN_ON(sock_owned_by_user(sk));
percpu_counter_inc(sk->sk_prot->orphan_count);
/* Have we already been destroyed by a softirq or backlog? */
if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
goto out;
/* This is a (useful) BSD violating of the RFC. There is a
* problem with TCP as specified in that the other end could
* keep a socket open forever with no application left this end.
* We use a 1 minute timeout (about the same as BSD) then kill
* our end. If they send after that then tough - BUT: long enough
* that we won't make the old 4*rto = almost no time - whoops
* reset mistake.
*
* Nope, it was not mistake. It is really desired behaviour
* f.e. on http servers, when such sockets are useless, but
* consume significant resources. Let's do it with special
* linger2 option. --ANK
*/
if (sk->sk_state == TCP_FIN_WAIT2) {
struct tcp_sock *tp = tcp_sk(sk);
if (tp->linger2 < 0) {
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, GFP_ATOMIC);
__NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPABORTONLINGER);
} else {
const int tmo = tcp_fin_time(sk);
if (tmo > TCP_TIMEWAIT_LEN) {
inet_csk_reset_keepalive_timer(sk,
tmo - TCP_TIMEWAIT_LEN);
} else {
tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
goto out;
}
}
}
if (sk->sk_state != TCP_CLOSE) {
sk_mem_reclaim(sk);
if (tcp_check_oom(sk, 0)) {
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, GFP_ATOMIC);
__NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPABORTONMEMORY);
}
}
if (sk->sk_state == TCP_CLOSE) {
struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
/* We could get here with a non-NULL req if the socket is
* aborted (e.g., closed with unread data) before 3WHS
* finishes.
*/
if (req)
reqsk_fastopen_remove(sk, req, false);
inet_csk_destroy_sock(sk);
}
/* Otherwise, socket is reprieved until protocol close. */
out:
bh_unlock_sock(sk);
local_bh_enable();
sock_put(sk);
}
EXPORT_SYMBOL(tcp_close);
/* These states need RST on ABORT according to RFC793 */
static inline bool tcp_need_reset(int state)
{
return (1 << state) &
(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
}
int tcp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int err = 0;
int old_state = sk->sk_state;
if (old_state != TCP_CLOSE)
tcp_set_state(sk, TCP_CLOSE);
/* ABORT function of RFC793 */
if (old_state == TCP_LISTEN) {
inet_csk_listen_stop(sk);
} else if (unlikely(tp->repair)) {
sk->sk_err = ECONNABORTED;
} else if (tcp_need_reset(old_state) ||
(tp->snd_nxt != tp->write_seq &&
(1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
/* The last check adjusts for discrepancy of Linux wrt. RFC
* states
*/
tcp_send_active_reset(sk, gfp_any());
sk->sk_err = ECONNRESET;
} else if (old_state == TCP_SYN_SENT)
sk->sk_err = ECONNRESET;
tcp_clear_xmit_timers(sk);
__skb_queue_purge(&sk->sk_receive_queue);
tcp_write_queue_purge(sk);
skb_rbtree_purge(&tp->out_of_order_queue);
inet->inet_dport = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
sk->sk_shutdown = 0;
sock_reset_flag(sk, SOCK_DONE);
tp->srtt_us = 0;
tp->write_seq += tp->max_window + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
icsk->icsk_backoff = 0;
tp->snd_cwnd = 2;
icsk->icsk_probes_out = 0;
tp->packets_out = 0;
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_cnt = 0;
tp->window_clamp = 0;
tcp_set_ca_state(sk, TCP_CA_Open);
tcp_clear_retrans(tp);
inet_csk_delack_init(sk);
tcp_init_send_head(sk);
memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
__sk_dst_reset(sk);
WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
sk->sk_error_report(sk);
return err;
}
EXPORT_SYMBOL(tcp_disconnect);
static inline bool tcp_can_repair_sock(const struct sock *sk)
{
return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
(sk->sk_state != TCP_LISTEN);
}
static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len)
{
struct tcp_repair_window opt;
if (!tp->repair)
return -EPERM;
if (len != sizeof(opt))
return -EINVAL;
if (copy_from_user(&opt, optbuf, sizeof(opt)))
return -EFAULT;
if (opt.max_window < opt.snd_wnd)
return -EINVAL;
if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
return -EINVAL;
if (after(opt.rcv_wup, tp->rcv_nxt))
return -EINVAL;
tp->snd_wl1 = opt.snd_wl1;
tp->snd_wnd = opt.snd_wnd;
tp->max_window = opt.max_window;
tp->rcv_wnd = opt.rcv_wnd;
tp->rcv_wup = opt.rcv_wup;
return 0;
}
static int tcp_repair_options_est(struct tcp_sock *tp,
struct tcp_repair_opt __user *optbuf, unsigned int len)
{
struct tcp_repair_opt opt;
while (len >= sizeof(opt)) {
if (copy_from_user(&opt, optbuf, sizeof(opt)))
return -EFAULT;
optbuf++;
len -= sizeof(opt);
switch (opt.opt_code) {
case TCPOPT_MSS:
tp->rx_opt.mss_clamp = opt.opt_val;
break;
case TCPOPT_WINDOW:
{
u16 snd_wscale = opt.opt_val & 0xFFFF;
u16 rcv_wscale = opt.opt_val >> 16;
if (snd_wscale > 14 || rcv_wscale > 14)
return -EFBIG;
tp->rx_opt.snd_wscale = snd_wscale;
tp->rx_opt.rcv_wscale = rcv_wscale;
tp->rx_opt.wscale_ok = 1;
}
break;
case TCPOPT_SACK_PERM:
if (opt.opt_val != 0)
return -EINVAL;
tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
if (sysctl_tcp_fack)
tcp_enable_fack(tp);
break;
case TCPOPT_TIMESTAMP:
if (opt.opt_val != 0)
return -EINVAL;
tp->rx_opt.tstamp_ok = 1;
break;
}
}
return 0;
}
/*
* Socket option code for TCP.
*/
static int do_tcp_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct net *net = sock_net(sk);
int val;
int err = 0;
/* These are data/string values, all the others are ints */
switch (optname) {
case TCP_CONGESTION: {
char name[TCP_CA_NAME_MAX];
if (optlen < 1)
return -EINVAL;
val = strncpy_from_user(name, optval,
min_t(long, TCP_CA_NAME_MAX-1, optlen));
if (val < 0)
return -EFAULT;
name[val] = 0;
lock_sock(sk);
err = tcp_set_congestion_control(sk, name);
release_sock(sk);
return err;
}
default:
/* fallthru */
break;
}
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case TCP_MAXSEG:
/* Values greater than interface MTU won't take effect. However
* at the point when this call is done we typically don't yet
* know which interface is going to be used */
if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
err = -EINVAL;
break;
}
tp->rx_opt.user_mss = val;
break;
case TCP_NODELAY:
if (val) {
/* TCP_NODELAY is weaker than TCP_CORK, so that
* this option on corked socket is remembered, but
* it is not activated until cork is cleared.
*
* However, when TCP_NODELAY is set we make
* an explicit push, which overrides even TCP_CORK
* for currently queued segments.
*/
tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
tcp_push_pending_frames(sk);
} else {
tp->nonagle &= ~TCP_NAGLE_OFF;
}
break;
case TCP_THIN_LINEAR_TIMEOUTS:
if (val < 0 || val > 1)
err = -EINVAL;
else
tp->thin_lto = val;
break;
case TCP_THIN_DUPACK:
if (val < 0 || val > 1)
err = -EINVAL;
else {
tp->thin_dupack = val;
if (tp->thin_dupack)
tcp_disable_early_retrans(tp);
}
break;
case TCP_REPAIR:
if (!tcp_can_repair_sock(sk))
err = -EPERM;
else if (val == 1) {
tp->repair = 1;
sk->sk_reuse = SK_FORCE_REUSE;
tp->repair_queue = TCP_NO_QUEUE;
} else if (val == 0) {
tp->repair = 0;
sk->sk_reuse = SK_NO_REUSE;
tcp_send_window_probe(sk);
} else
err = -EINVAL;
break;
case TCP_REPAIR_QUEUE:
if (!tp->repair)
err = -EPERM;
else if (val < TCP_QUEUES_NR)
tp->repair_queue = val;
else
err = -EINVAL;
break;
case TCP_QUEUE_SEQ:
if (sk->sk_state != TCP_CLOSE)
err = -EPERM;
else if (tp->repair_queue == TCP_SEND_QUEUE)
tp->write_seq = val;
else if (tp->repair_queue == TCP_RECV_QUEUE)
tp->rcv_nxt = val;
else
err = -EINVAL;
break;
case TCP_REPAIR_OPTIONS:
if (!tp->repair)
err = -EINVAL;
else if (sk->sk_state == TCP_ESTABLISHED)
err = tcp_repair_options_est(tp,
(struct tcp_repair_opt __user *)optval,
optlen);
else
err = -EPERM;
break;
case TCP_CORK:
/* When set indicates to always queue non-full frames.
* Later the user clears this option and we transmit
* any pending partial frames in the queue. This is
* meant to be used alongside sendfile() to get properly
* filled frames when the user (for example) must write
* out headers with a write() call first and then use
* sendfile to send out the data parts.
*
* TCP_CORK can be set together with TCP_NODELAY and it is
* stronger than TCP_NODELAY.
*/
if (val) {
tp->nonagle |= TCP_NAGLE_CORK;
} else {
tp->nonagle &= ~TCP_NAGLE_CORK;
if (tp->nonagle&TCP_NAGLE_OFF)
tp->nonagle |= TCP_NAGLE_PUSH;
tcp_push_pending_frames(sk);
}
break;
case TCP_KEEPIDLE:
if (val < 1 || val > MAX_TCP_KEEPIDLE)
err = -EINVAL;
else {
tp->keepalive_time = val * HZ;
if (sock_flag(sk, SOCK_KEEPOPEN) &&
!((1 << sk->sk_state) &
(TCPF_CLOSE | TCPF_LISTEN))) {
u32 elapsed = keepalive_time_elapsed(tp);
if (tp->keepalive_time > elapsed)
elapsed = tp->keepalive_time - elapsed;
else
elapsed = 0;
inet_csk_reset_keepalive_timer(sk, elapsed);
}
}
break;
case TCP_KEEPINTVL:
if (val < 1 || val > MAX_TCP_KEEPINTVL)
err = -EINVAL;
else
tp->keepalive_intvl = val * HZ;
break;
case TCP_KEEPCNT:
if (val < 1 || val > MAX_TCP_KEEPCNT)
err = -EINVAL;
else
tp->keepalive_probes = val;
break;
case TCP_SYNCNT:
if (val < 1 || val > MAX_TCP_SYNCNT)
err = -EINVAL;
else
icsk->icsk_syn_retries = val;
break;
case TCP_SAVE_SYN:
if (val < 0 || val > 1)
err = -EINVAL;
else
tp->save_syn = val;
break;
case TCP_LINGER2:
if (val < 0)
tp->linger2 = -1;
else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ)
tp->linger2 = 0;
else
tp->linger2 = val * HZ;
break;
case TCP_DEFER_ACCEPT:
/* Translate value in seconds to number of retransmits */
icsk->icsk_accept_queue.rskq_defer_accept =
secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
TCP_RTO_MAX / HZ);
break;
case TCP_WINDOW_CLAMP:
if (!val) {
if (sk->sk_state != TCP_CLOSE) {
err = -EINVAL;
break;
}
tp->window_clamp = 0;
} else
tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
SOCK_MIN_RCVBUF / 2 : val;
break;
case TCP_QUICKACK:
if (!val) {
icsk->icsk_ack.pingpong = 1;
} else {
icsk->icsk_ack.pingpong = 0;
if ((1 << sk->sk_state) &
(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
inet_csk_ack_scheduled(sk)) {
icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
tcp_cleanup_rbuf(sk, 1);
if (!(val & 1))
icsk->icsk_ack.pingpong = 1;
}
}
break;
#ifdef CONFIG_TCP_MD5SIG
case TCP_MD5SIG:
/* Read the IP->Key mappings from userspace */
err = tp->af_specific->md5_parse(sk, optval, optlen);
break;
#endif
case TCP_USER_TIMEOUT:
/* Cap the max time in ms TCP will retry or probe the window
* before giving up and aborting (ETIMEDOUT) a connection.
*/
if (val < 0)
err = -EINVAL;
else
icsk->icsk_user_timeout = msecs_to_jiffies(val);
break;
case TCP_FASTOPEN:
if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
TCPF_LISTEN))) {
tcp_fastopen_init_key_once(true);
fastopen_queue_tune(sk, val);
} else {
err = -EINVAL;
}
break;
case TCP_TIMESTAMP:
if (!tp->repair)
err = -EPERM;
else
tp->tsoffset = val - tcp_time_stamp;
break;
case TCP_REPAIR_WINDOW:
err = tcp_repair_set_window(tp, optval, optlen);
break;
case TCP_NOTSENT_LOWAT:
tp->notsent_lowat = val;
sk->sk_write_space(sk);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
unsigned int optlen)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (level != SOL_TCP)
return icsk->icsk_af_ops->setsockopt(sk, level, optname,
optval, optlen);
return do_tcp_setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(tcp_setsockopt);
#ifdef CONFIG_COMPAT
int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_TCP)
return inet_csk_compat_setsockopt(sk, level, optname,
optval, optlen);
return do_tcp_setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_tcp_setsockopt);
#endif
static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
struct tcp_info *info)
{
u64 stats[__TCP_CHRONO_MAX], total = 0;
enum tcp_chrono i;
for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
stats[i] = tp->chrono_stat[i - 1];
if (i == tp->chrono_type)
stats[i] += tcp_time_stamp - tp->chrono_start;
stats[i] *= USEC_PER_SEC / HZ;
total += stats[i];
}
info->tcpi_busy_time = total;
info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
}
/* Return information about state of tcp endpoint in API format. */
void tcp_get_info(struct sock *sk, struct tcp_info *info)
{
const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
const struct inet_connection_sock *icsk = inet_csk(sk);
u32 now = tcp_time_stamp, intv;
u64 rate64;
bool slow;
u32 rate;
memset(info, 0, sizeof(*info));
if (sk->sk_type != SOCK_STREAM)
return;
info->tcpi_state = sk_state_load(sk);
/* Report meaningful fields for all TCP states, including listeners */
rate = READ_ONCE(sk->sk_pacing_rate);
rate64 = rate != ~0U ? rate : ~0ULL;
info->tcpi_pacing_rate = rate64;
rate = READ_ONCE(sk->sk_max_pacing_rate);
rate64 = rate != ~0U ? rate : ~0ULL;
info->tcpi_max_pacing_rate = rate64;
info->tcpi_reordering = tp->reordering;
info->tcpi_snd_cwnd = tp->snd_cwnd;
if (info->tcpi_state == TCP_LISTEN) {
/* listeners aliased fields :
* tcpi_unacked -> Number of children ready for accept()
* tcpi_sacked -> max backlog
*/
info->tcpi_unacked = sk->sk_ack_backlog;
info->tcpi_sacked = sk->sk_max_ack_backlog;
return;
}
info->tcpi_ca_state = icsk->icsk_ca_state;
info->tcpi_retransmits = icsk->icsk_retransmits;
info->tcpi_probes = icsk->icsk_probes_out;
info->tcpi_backoff = icsk->icsk_backoff;
if (tp->rx_opt.tstamp_ok)
info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
if (tcp_is_sack(tp))
info->tcpi_options |= TCPI_OPT_SACK;
if (tp->rx_opt.wscale_ok) {
info->tcpi_options |= TCPI_OPT_WSCALE;
info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
}
if (tp->ecn_flags & TCP_ECN_OK)
info->tcpi_options |= TCPI_OPT_ECN;
if (tp->ecn_flags & TCP_ECN_SEEN)
info->tcpi_options |= TCPI_OPT_ECN_SEEN;
if (tp->syn_data_acked)
info->tcpi_options |= TCPI_OPT_SYN_DATA;
info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
info->tcpi_snd_mss = tp->mss_cache;
info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
info->tcpi_unacked = tp->packets_out;
info->tcpi_sacked = tp->sacked_out;
info->tcpi_lost = tp->lost_out;
info->tcpi_retrans = tp->retrans_out;
info->tcpi_fackets = tp->fackets_out;
info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
info->tcpi_rtt = tp->srtt_us >> 3;
info->tcpi_rttvar = tp->mdev_us >> 2;
info->tcpi_snd_ssthresh = tp->snd_ssthresh;
info->tcpi_advmss = tp->advmss;
info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
info->tcpi_rcv_space = tp->rcvq_space.space;
info->tcpi_total_retrans = tp->total_retrans;
slow = lock_sock_fast(sk);
info->tcpi_bytes_acked = tp->bytes_acked;
info->tcpi_bytes_received = tp->bytes_received;
info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
tcp_get_info_chrono_stats(tp, info);
unlock_sock_fast(sk, slow);
info->tcpi_segs_out = tp->segs_out;
info->tcpi_segs_in = tp->segs_in;
info->tcpi_min_rtt = tcp_min_rtt(tp);
info->tcpi_data_segs_in = tp->data_segs_in;
info->tcpi_data_segs_out = tp->data_segs_out;
info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
rate = READ_ONCE(tp->rate_delivered);
intv = READ_ONCE(tp->rate_interval_us);
if (rate && intv) {
rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
do_div(rate64, intv);
info->tcpi_delivery_rate = rate64;
}
}
EXPORT_SYMBOL_GPL(tcp_get_info);
struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *stats;
struct tcp_info info;
stats = alloc_skb(3 * nla_total_size_64bit(sizeof(u64)), GFP_ATOMIC);
if (!stats)
return NULL;
tcp_get_info_chrono_stats(tp, &info);
nla_put_u64_64bit(stats, TCP_NLA_BUSY,
info.tcpi_busy_time, TCP_NLA_PAD);
nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
info.tcpi_rwnd_limited, TCP_NLA_PAD);
nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
info.tcpi_sndbuf_limited, TCP_NLA_PAD);
return stats;
}
static int do_tcp_getsockopt(struct sock *sk, int level,
int optname, char __user *optval, int __user *optlen)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct net *net = sock_net(sk);
int val, len;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
switch (optname) {
case TCP_MAXSEG:
val = tp->mss_cache;
if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
val = tp->rx_opt.user_mss;
if (tp->repair)
val = tp->rx_opt.mss_clamp;
break;
case TCP_NODELAY:
val = !!(tp->nonagle&TCP_NAGLE_OFF);
break;
case TCP_CORK:
val = !!(tp->nonagle&TCP_NAGLE_CORK);
break;
case TCP_KEEPIDLE:
val = keepalive_time_when(tp) / HZ;
break;
case TCP_KEEPINTVL:
val = keepalive_intvl_when(tp) / HZ;
break;
case TCP_KEEPCNT:
val = keepalive_probes(tp);
break;
case TCP_SYNCNT:
val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries;
break;
case TCP_LINGER2:
val = tp->linger2;
if (val >= 0)
val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ;
break;
case TCP_DEFER_ACCEPT:
val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
break;
case TCP_WINDOW_CLAMP:
val = tp->window_clamp;
break;
case TCP_INFO: {
struct tcp_info info;
if (get_user(len, optlen))
return -EFAULT;
tcp_get_info(sk, &info);
len = min_t(unsigned int, len, sizeof(info));
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
case TCP_CC_INFO: {
const struct tcp_congestion_ops *ca_ops;
union tcp_cc_info info;
size_t sz = 0;
int attr;
if (get_user(len, optlen))
return -EFAULT;
ca_ops = icsk->icsk_ca_ops;
if (ca_ops && ca_ops->get_info)
sz = ca_ops->get_info(sk, ~0U, &attr, &info);
len = min_t(unsigned int, len, sz);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
case TCP_QUICKACK:
val = !icsk->icsk_ack.pingpong;
break;
case TCP_CONGESTION:
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
return -EFAULT;
return 0;
case TCP_THIN_LINEAR_TIMEOUTS:
val = tp->thin_lto;
break;
case TCP_THIN_DUPACK:
val = tp->thin_dupack;
break;
case TCP_REPAIR:
val = tp->repair;
break;
case TCP_REPAIR_QUEUE:
if (tp->repair)
val = tp->repair_queue;
else
return -EINVAL;
break;
case TCP_REPAIR_WINDOW: {
struct tcp_repair_window opt;
if (get_user(len, optlen))
return -EFAULT;
if (len != sizeof(opt))
return -EINVAL;
if (!tp->repair)
return -EPERM;
opt.snd_wl1 = tp->snd_wl1;
opt.snd_wnd = tp->snd_wnd;
opt.max_window = tp->max_window;
opt.rcv_wnd = tp->rcv_wnd;
opt.rcv_wup = tp->rcv_wup;
if (copy_to_user(optval, &opt, len))
return -EFAULT;
return 0;
}
case TCP_QUEUE_SEQ:
if (tp->repair_queue == TCP_SEND_QUEUE)
val = tp->write_seq;
else if (tp->repair_queue == TCP_RECV_QUEUE)
val = tp->rcv_nxt;
else
return -EINVAL;
break;
case TCP_USER_TIMEOUT:
val = jiffies_to_msecs(icsk->icsk_user_timeout);
break;
case TCP_FASTOPEN:
val = icsk->icsk_accept_queue.fastopenq.max_qlen;
break;
case TCP_TIMESTAMP:
val = tcp_time_stamp + tp->tsoffset;
break;
case TCP_NOTSENT_LOWAT:
val = tp->notsent_lowat;
break;
case TCP_SAVE_SYN:
val = tp->save_syn;
break;
case TCP_SAVED_SYN: {
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
if (tp->saved_syn) {
if (len < tp->saved_syn[0]) {
if (put_user(tp->saved_syn[0], optlen)) {
release_sock(sk);
return -EFAULT;
}
release_sock(sk);
return -EINVAL;
}
len = tp->saved_syn[0];
if (put_user(len, optlen)) {
release_sock(sk);
return -EFAULT;
}
if (copy_to_user(optval, tp->saved_syn + 1, len)) {
release_sock(sk);
return -EFAULT;
}
tcp_saved_syn_free(tp);
release_sock(sk);
} else {
release_sock(sk);
len = 0;
if (put_user(len, optlen))
return -EFAULT;
}
return 0;
}
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
int __user *optlen)
{
struct inet_connection_sock *icsk = inet_csk(sk);
if (level != SOL_TCP)
return icsk->icsk_af_ops->getsockopt(sk, level, optname,
optval, optlen);
return do_tcp_getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(tcp_getsockopt);
#ifdef CONFIG_COMPAT
int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_TCP)
return inet_csk_compat_getsockopt(sk, level, optname,
optval, optlen);
return do_tcp_getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_tcp_getsockopt);
#endif
#ifdef CONFIG_TCP_MD5SIG
static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
static DEFINE_MUTEX(tcp_md5sig_mutex);
static bool tcp_md5sig_pool_populated = false;
static void __tcp_alloc_md5sig_pool(void)
{
struct crypto_ahash *hash;
int cpu;
hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hash))
return;
for_each_possible_cpu(cpu) {
void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
struct ahash_request *req;
if (!scratch) {
scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
sizeof(struct tcphdr),
GFP_KERNEL,
cpu_to_node(cpu));
if (!scratch)
return;
per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
}
if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
continue;
req = ahash_request_alloc(hash, GFP_KERNEL);
if (!req)
return;
ahash_request_set_callback(req, 0, NULL, NULL);
per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
}
/* before setting tcp_md5sig_pool_populated, we must commit all writes
* to memory. See smp_rmb() in tcp_get_md5sig_pool()
*/
smp_wmb();
tcp_md5sig_pool_populated = true;
}
bool tcp_alloc_md5sig_pool(void)
{
if (unlikely(!tcp_md5sig_pool_populated)) {
mutex_lock(&tcp_md5sig_mutex);
if (!tcp_md5sig_pool_populated)
__tcp_alloc_md5sig_pool();
mutex_unlock(&tcp_md5sig_mutex);
}
return tcp_md5sig_pool_populated;
}
EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
/**
* tcp_get_md5sig_pool - get md5sig_pool for this user
*
* We use percpu structure, so if we succeed, we exit with preemption
* and BH disabled, to make sure another thread or softirq handling
* wont try to get same context.
*/
struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
{
local_bh_disable();
if (tcp_md5sig_pool_populated) {
/* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
smp_rmb();
return this_cpu_ptr(&tcp_md5sig_pool);
}
local_bh_enable();
return NULL;
}
EXPORT_SYMBOL(tcp_get_md5sig_pool);
int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
const struct sk_buff *skb, unsigned int header_len)
{
struct scatterlist sg;
const struct tcphdr *tp = tcp_hdr(skb);
struct ahash_request *req = hp->md5_req;
unsigned int i;
const unsigned int head_data_len = skb_headlen(skb) > header_len ?
skb_headlen(skb) - header_len : 0;
const struct skb_shared_info *shi = skb_shinfo(skb);
struct sk_buff *frag_iter;
sg_init_table(&sg, 1);
sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
ahash_request_set_crypt(req, &sg, NULL, head_data_len);
if (crypto_ahash_update(req))
return 1;
for (i = 0; i < shi->nr_frags; ++i) {
const struct skb_frag_struct *f = &shi->frags[i];
unsigned int offset = f->page_offset;
struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
sg_set_page(&sg, page, skb_frag_size(f),
offset_in_page(offset));
ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
if (crypto_ahash_update(req))
return 1;
}
skb_walk_frags(skb, frag_iter)
if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
return 1;
return 0;
}
EXPORT_SYMBOL(tcp_md5_hash_skb_data);
int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
{
struct scatterlist sg;
sg_init_one(&sg, key->key, key->keylen);
ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen);
return crypto_ahash_update(hp->md5_req);
}
EXPORT_SYMBOL(tcp_md5_hash_key);
#endif
void tcp_done(struct sock *sk)
{
struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
tcp_set_state(sk, TCP_CLOSE);
tcp_clear_xmit_timers(sk);
if (req)
reqsk_fastopen_remove(sk, req, false);
sk->sk_shutdown = SHUTDOWN_MASK;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
else
inet_csk_destroy_sock(sk);
}
EXPORT_SYMBOL_GPL(tcp_done);
int tcp_abort(struct sock *sk, int err)
{
if (!sk_fullsock(sk)) {
if (sk->sk_state == TCP_NEW_SYN_RECV) {
struct request_sock *req = inet_reqsk(sk);
local_bh_disable();
inet_csk_reqsk_queue_drop_and_put(req->rsk_listener,
req);
local_bh_enable();
return 0;
}
return -EOPNOTSUPP;
}
/* Don't race with userspace socket closes such as tcp_close. */
lock_sock(sk);
if (sk->sk_state == TCP_LISTEN) {
tcp_set_state(sk, TCP_CLOSE);
inet_csk_listen_stop(sk);
}
/* Don't race with BH socket closes such as inet_csk_listen_stop. */
local_bh_disable();
bh_lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_err = err;
/* This barrier is coupled with smp_rmb() in tcp_poll() */
smp_wmb();
sk->sk_error_report(sk);
if (tcp_need_reset(sk->sk_state))
tcp_send_active_reset(sk, GFP_ATOMIC);
tcp_done(sk);
}
bh_unlock_sock(sk);
local_bh_enable();
release_sock(sk);
return 0;
}
EXPORT_SYMBOL_GPL(tcp_abort);
extern struct tcp_congestion_ops tcp_reno;
static __initdata unsigned long thash_entries;
static int __init set_thash_entries(char *str)
{
ssize_t ret;
if (!str)
return 0;
ret = kstrtoul(str, 0, &thash_entries);
if (ret)
return 0;
return 1;
}
__setup("thash_entries=", set_thash_entries);
static void __init tcp_init_mem(void)
{
unsigned long limit = nr_free_buffer_pages() / 16;
limit = max(limit, 128UL);
sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */
sysctl_tcp_mem[1] = limit; /* 6.25 % */
sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */
}
void __init tcp_init(void)
{
int max_rshare, max_wshare, cnt;
unsigned long limit;
unsigned int i;
BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
FIELD_SIZEOF(struct sk_buff, cb));
percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL);
tcp_hashinfo.bind_bucket_cachep =
kmem_cache_create("tcp_bind_bucket",
sizeof(struct inet_bind_bucket), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
/* Size and allocate the main established and bind bucket
* hash tables.
*
* The methodology is similar to that of the buffer cache.
*/
tcp_hashinfo.ehash =
alloc_large_system_hash("TCP established",
sizeof(struct inet_ehash_bucket),
thash_entries,
17, /* one slot per 128 KB of memory */
0,
NULL,
&tcp_hashinfo.ehash_mask,
0,
thash_entries ? 0 : 512 * 1024);
for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
if (inet_ehash_locks_alloc(&tcp_hashinfo))
panic("TCP: failed to alloc ehash_locks");
tcp_hashinfo.bhash =
alloc_large_system_hash("TCP bind",
sizeof(struct inet_bind_hashbucket),
tcp_hashinfo.ehash_mask + 1,
17, /* one slot per 128 KB of memory */
0,
&tcp_hashinfo.bhash_size,
NULL,
0,
64 * 1024);
tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
spin_lock_init(&tcp_hashinfo.bhash[i].lock);
INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
}
cnt = tcp_hashinfo.ehash_mask + 1;
tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
sysctl_tcp_max_orphans = cnt / 2;
sysctl_max_syn_backlog = max(128, cnt / 256);
tcp_init_mem();
/* Set per-socket limits to no more than 1/128 the pressure threshold */
limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
max_wshare = min(4UL*1024*1024, limit);
max_rshare = min(6UL*1024*1024, limit);
sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
sysctl_tcp_wmem[1] = 16*1024;
sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
sysctl_tcp_rmem[1] = 87380;
sysctl_tcp_rmem[2] = max(87380, max_rshare);
pr_info("Hash tables configured (established %u bind %u)\n",
tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
tcp_metrics_init();
BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
tcp_tasklet_init();
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_3169_0 |
crossvul-cpp_data_bad_2584_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.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/constitute.h"
#include "MagickCore/draw.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/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MagickPathExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
geometry[MagickPathExtent],
*p,
text[MagickPathExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->resolution.x)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->resolution.y)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MagickPathExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image,exception);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics,exception);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MagickPathExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture,exception);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info,exception);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MagickPathExtent);
(void) SetImageBackgroundColor(image,exception);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture,exception);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info,exception);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MagickPathExtent],
text[MagickPathExtent];
Image
*image;
long
x_offset,
y_offset;
PixelInfo
pixel;
MagickBooleanType
status;
QuantumAny
range;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->alpha_trait=UndefinedPixelTrait;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->alpha_trait=BlendPixelTrait;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,(ColorspaceType) type,exception);
GetPixelInfo(image,&pixel);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
alpha,
black,
blue,
green,
red;
red=0.0;
green=0.0;
blue=0.0;
black=0.0;
alpha=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&alpha);
green=red;
blue=red;
break;
}
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,
&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&black,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&black);
break;
}
default:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
black*=0.01*range;
alpha*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),
range);
pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),
range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
SetPixelViaPixelInfo(image,&pixel,q);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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 (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("TXT","SPARSE-COLOR","Sparse Color");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TXT","TEXT","Text");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->format_type=ImplicitFormatType;
entry->flags|=CoderRawSupportFlag;
entry->flags|=CoderEndianSupportFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("TXT","TXT","Text");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->magick=(IsImageFormatHandler *) IsTXT;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("SPARSE-COLOR");
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(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 WriteTXTImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
buffer[MagickPathExtent],
colorspace[MagickPathExtent],
tuple[MagickPathExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
PixelInfo
pixel;
register const Quantum
*p;
register ssize_t
x;
ssize_t
y;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->alpha_trait != UndefinedPixelTrait)
(void) ConcatenateMagickString(colorspace,"a",MagickPathExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MagickPathExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetPixelInfo(image,&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++)
{
GetPixelInfoPixel(image,p,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,
"%.20g,%.20g,",(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p+=GetPixelChannels(image);
continue;
}
(void) FormatLocaleString(buffer,MagickPathExtent,"%.20g,%.20g: ",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MagickPathExtent);
if (pixel.colorspace == GRAYColorspace)
ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple);
else
{
ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance,
tuple);
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple);
}
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance,
tuple);
}
if (pixel.alpha_trait != UndefinedPixelTrait)
{
(void) ConcatenateMagickString(tuple,",",MagickPathExtent);
ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance,
tuple);
}
(void) ConcatenateMagickString(tuple,")",MagickPathExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MagickPathExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p+=GetPixelChannels(image);
}
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-835/c/bad_2584_0 |
crossvul-cpp_data_bad_581_0 | #ifndef IGNOREALL
/*
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net
This is a command-line ANSI C program to convert raw photos from
any digital camera on any computer running any operating system.
No license is required to download and use dcraw.c. However,
to lawfully redistribute dcraw, you must either (a) offer, at
no extra charge, full source code* for all executable files
containing RESTRICTED functions, (b) distribute this code under
the GPL Version 2 or later, (c) remove all RESTRICTED functions,
re-implement them, or copy them from an earlier, unrestricted
Revision of dcraw.c, or (d) purchase a license from the author.
The functions that process Foveon images have been RESTRICTED
since Revision 1.237. All other code remains free for all uses.
*If you have not modified dcraw.c in any way, a link to my
homepage qualifies as "full source code".
$Revision: 1.476 $
$Date: 2015/05/25 02:29:14 $
*/
/*@out DEFINES
#ifndef USE_JPEG
#define NO_JPEG
#endif
#ifndef USE_JASPER
#define NO_JASPER
#endif
@end DEFINES */
#define NO_LCMS
#define DCRAW_VERBOSE
//@out DEFINES
#define DCRAW_VERSION "9.26"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _USE_MATH_DEFINES
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
//@end DEFINES
#if defined(DJGPP) || defined(__MINGW32__)
#define fseeko fseek
#define ftello ftell
#else
#define fgetc getc_unlocked
#endif
//@out DEFINES
#ifdef __CYGWIN__
#include <io.h>
#endif
#if defined WIN32 || defined(__MINGW32__)
#include <sys/utime.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
//@end DEFINES
typedef __int64 INT64;
typedef unsigned __int64 UINT64;
//@out DEFINES
#else
#include <unistd.h>
#include <utime.h>
#include <netinet/in.h>
typedef long long INT64;
typedef unsigned long long UINT64;
#endif
#ifdef NODEPS
#define NO_JASPER
#define NO_JPEG
#define NO_LCMS
#endif
#ifndef NO_JASPER
#include <jasper/jasper.h> /* Decode Red camera movies */
#endif
#ifndef NO_JPEG
#include <jpeglib.h> /* Decode compressed Kodak DC120 photos */
#endif /* and Adobe Lossy DNGs */
#ifndef NO_LCMS
#ifdef USE_LCMS
#include <lcms.h> /* Support color profiles */
#else
#include <lcms2.h> /* Support color profiles */
#endif
#endif
#ifdef LOCALEDIR
#include <libintl.h>
#define _(String) gettext(String)
#else
#define _(String) (String)
#endif
#ifdef LJPEG_DECODE
#error Please compile dcraw.c by itself.
#error Do not link it with ljpeg_decode.
#endif
#ifndef LONG_BIT
#define LONG_BIT (8 * sizeof(long))
#endif
//@end DEFINES
#if !defined(uchar)
#define uchar unsigned char
#endif
#if !defined(ushort)
#define ushort unsigned short
#endif
/*
All global variables are defined here, and all functions that
access them are prefixed with "CLASS". Note that a thread-safe
C++ class cannot have non-const static local variables.
*/
FILE *ifp, *ofp;
short order;
const char *ifname;
char *meta_data, xtrans[6][6], xtrans_abs[6][6];
char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64];
float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
time_t timestamp;
off_t strip_offset, data_offset;
off_t thumb_offset, meta_offset, profile_offset;
unsigned shot_order, kodak_cbpp, exif_cfa, unique_id;
unsigned thumb_length, meta_length, profile_length;
unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0;
unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
unsigned black, maximum, mix_green, raw_color, zero_is_bad;
unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
unsigned tile_width, tile_length, gpsdata[32], load_flags;
unsigned flip, tiff_flip, filters, colors;
ushort raw_height, raw_width, height, width, top_margin, left_margin;
ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
ushort *raw_image, (*image)[4], cblack[4102];
ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0};
float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0;
int mask[8][4];
int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0;
int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1;
int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0;
int no_auto_bright = 0;
unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX};
float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
const double xyz_rgb[3][3] = {/* XYZ from RGB */
{0.412453, 0.357580, 0.180423},
{0.212671, 0.715160, 0.072169},
{0.019334, 0.119193, 0.950227}};
const float d65_white[3] = {0.950456, 1, 1.088754};
int histogram[4][0x2000];
void (*write_thumb)(), (*write_fun)();
void (*load_raw)(), (*thumb_load_raw)();
jmp_buf failure;
struct decode
{
struct decode *branch[2];
int leaf;
} first_decode[2048], *second_decode, *free_decode;
struct tiff_ifd
{
int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes;
int t_tile_width, t_tile_length, sample_format, predictor;
float t_shutter;
} tiff_ifd[10];
struct ph1
{
int format, key_off, tag_21a;
int t_black, split_col, black_col, split_row, black_row;
float tag_210;
} ph1;
#define CLASS
//@out DEFINES
#define FORC(cnt) for (c = 0; c < cnt; c++)
#define FORC3 FORC(3)
#define FORC4 FORC(4)
#define FORCC for (c = 0; c < colors && c < 4; c++)
#define SQR(x) ((x) * (x))
#define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define LIM(x, min, max) MAX(min, MIN(x, max))
#define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y))
#define CLIP(x) LIM((int)(x), 0, 65535)
#define CLIP15(x) LIM((int)(x), 0, 32767)
#define SWAP(a, b) \
{ \
a = a + b; \
b = a - b; \
a = a - b; \
}
#define my_swap(type, i, j) \
{ \
type t = i; \
i = j; \
j = t; \
}
static float fMAX(float a, float b) { return MAX(a, b); }
/*
In order to inline this calculation, I make the risky
assumption that all filter patterns can be described
by a repeating pattern of eight rows and two columns
Do not use the FC or BAYER macros with the Leaf CatchLight,
because its pattern is 16x16, not 2x8.
Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1
0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M
1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C
2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y
3 C Y C Y C Y 3 G M G M G M 3 G M G M G M
4 C Y C Y C Y 4 Y C Y C Y C
PowerShot A5 5 G M G M G M 5 G M G M G M
0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y
7 M G M G M G 7 M G M G M G
0 1 2 3 4 5
0 C Y C Y C Y
1 G M G M G M
2 C Y C Y C Y
3 M G M G M G
All RGB cameras use one of these Bayer grids:
0x16161616: 0x61616161: 0x49494949: 0x94949494:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G
1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B
2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G
3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B
*/
#define RAWINDEX(row, col) ((row)*raw_width + (col))
#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, unsigned count)
{
if (fread(pixel, 2, count, ifp) < count)
derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab((char *)pixel, (char *)pixel, count * 2);
}
void CLASS cubic_spline(const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len);
if (!A)
return;
A[0] = (float *)(A + 2 * len);
for (i = 1; i < 2 * len; i++)
A[i] = A[0] + 2 * len * i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i))));
for (i = 0; i < len; i++)
{
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len - 1; i > 0; i--)
{
b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]);
d[i - 1] = x[i] - x[i - 1];
}
for (i = 1; i < len - 1; i++)
{
A[i][i] = 2 * (d[i - 1] + d[i]);
if (i > 1)
{
A[i][i - 1] = d[i - 1];
A[i - 1][i] = d[i - 1];
}
A[i][len - 1] = 6 * (b[i + 1] - b[i]);
}
for (i = 1; i < len - 2; i++)
{
float v = A[i + 1][i] / A[i][i];
for (j = 1; j <= len - 1; j++)
A[i + 1][j] -= v * A[i][j];
}
for (i = len - 2; i > 0; i--)
{
float acc = 0;
for (j = i; j <= len - 2; j++)
acc += A[i][j] * c[j];
c[i] = (A[i][len - 1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++)
{
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len - 1; j++)
{
if (x[j] <= x_out && x_out <= x[j + 1])
{
float v = x_out - x[j];
y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v +
((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5));
}
free(A);
}
void CLASS canon_600_fixed_wb(int temp)
{
static const short mul[4][5] = {
{667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}};
int lo, hi, i;
float frac = 0;
for (lo = 4; --lo;)
if (*mul[lo] <= temp)
break;
for (hi = 0; hi < 3; hi++)
if (*mul[hi] >= temp)
break;
if (lo != hi)
frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i = 1; i < 5; i++)
pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color(int ratio[2], int mar)
{
int clipped = 0, target, miss;
if (flash_used)
{
if (ratio[1] < -104)
{
ratio[1] = -104;
clipped = 1;
}
if (ratio[1] > 12)
{
ratio[1] = 12;
clipped = 1;
}
}
else
{
if (ratio[1] < -264 || ratio[1] > 461)
return 2;
if (ratio[1] < -50)
{
ratio[1] = -50;
clipped = 1;
}
if (ratio[1] > 307)
{
ratio[1] = 307;
clipped = 1;
}
}
target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped)
return 0;
miss = target - ratio[0];
if (abs(miss) >= mar * 4)
return 2;
if (miss < -20)
miss = -20;
if (miss > mar)
miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = {0, 0};
int test[8], total[2][8], ratio[2][2], stat[2];
memset(&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10)
mar = 150;
else if (i > 12)
mar = 20;
else
mar = 280 - 20 * i;
if (flash_used)
mar = 80;
for (row = 14; row < height - 14; row += 4)
for (col = 10; col < width; col += 2)
{
for (i = 0; i < 8; i++)
test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1));
for (i = 0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500)
goto next;
for (i = 0; i < 4; i++)
if (abs(test[i] - test[i + 4]) > 50)
goto next;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 4; j += 2)
ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j];
stat[i] = canon_600_color(ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1)
goto next;
for (i = 0; i < 2; i++)
if (stat[i])
for (j = 0; j < 2; j++)
test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10;
for (i = 0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next:;
}
if (count[0] | count[1])
{
st = count[0] * 200 < count[1];
for (i = 0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409},
{-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007},
{-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528},
{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}};
int t = 0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789)
t = 1;
if (mc > 1.28 && mc <= 2)
{
if (yc < 0.8789)
t = 3;
else if (yc <= 2)
t = 4;
}
if (flash_used)
t = 5;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow = row = 0; irow < height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data, 1, 1120, ifp) < 1120)
derror();
pix = raw_image + row * raw_width;
for (dp = data; dp < data + 1120; dp += 10, pix += 8)
{
pix[0] = (dp[0] << 2) + (dp[1] >> 6);
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6);
}
if ((row += 2) > height)
row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}};
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
{
if ((val = BAYER(row, col) - black) < 0)
val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row, col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row = 0; row < 100; row++)
{
fseek(ifp, row * 3340 + 3284, SEEK_SET);
if (getc(ifp) > 15)
return 1;
}
return 0;
}
unsigned CLASS getbithuff(int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf = 0;
static int vbits = 0, reset = 0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25)
return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0)
return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp)))
{
bitbuf = (bitbuf << 8) + (uchar)c;
vbits += 8;
}
c = bitbuf << (32 - vbits) >> (32 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
c = (uchar)huff[c];
}
else
vbits -= nbits;
if (vbits < 0)
derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n, 0)
#define gethuff(h) getbithuff(*h, h + 1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort *CLASS make_decoder_ref(const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max = 16; max && !count[max]; max--)
;
huff = (ushort *)calloc(1 + (1 << max), sizeof *huff);
merror(huff, "make_decoder()");
huff[0] = max;
for (h = len = 1; len <= max; len++)
for (i = 0; i < count[len]; i++, ++*source)
for (j = 0; j < 1 << (max - len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); }
void CLASS crw_init_tables(unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff},
{0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0,
0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff},
{0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff},
};
static const uchar second_tree[3][180] = {
{0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04,
0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0,
0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29,
0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9,
0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91,
0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4,
0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7,
0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64,
0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3,
0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff},
{0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03,
0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32,
0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61,
0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59,
0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56,
0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85,
0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82,
0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9,
0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64,
0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff},
{0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05,
0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22,
0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58,
0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48,
0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88,
0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94,
0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a,
0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62,
0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1,
0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}};
if (table > 2)
table = 2;
huff[0] = make_decoder(first_tree[table]);
huff[1] = make_decoder(second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret = 1, i;
fseek(ifp, 0, SEEK_SET);
fread(test, 1, sizeof test, ifp);
for (i = 540; i < sizeof test - 1; i++)
if (test[i] == 0xff)
{
if (test[i + 1])
return 1;
ret = 0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2];
crw_init_tables(tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits)
maximum = 0x3ff;
fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
nblocks = MIN(8, raw_height - row) * raw_width >> 6;
for (block = 0; block < nblocks; block++)
{
memset(diffbuf, 0, sizeof diffbuf);
for (i = 0; i < 64; i++)
{
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i)
break;
if (leaf == 0xff)
continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0)
continue;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
if (i < 64)
diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i = 0; i < 64; i++)
{
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits)
{
save = ftell(ifp);
fseek(ifp, 26 + row * raw_width / 4, SEEK_SET);
for (prow = pixel, i = 0; i < raw_width * 2; i++)
{
c = fgetc(ifp);
for (r = 0; r < 8; r += 2, prow++)
{
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512)
val += 2;
*prow = val;
}
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
FORC(2) free(huff[c]);
throw;
}
#endif
FORC(2) free(huff[c]);
}
//@end COMMON
struct jhead
{
int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6];
ushort quant[64], idct[64], *huff[20], *free[20], *row;
};
//@out COMMON
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,
47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
int bypp = tiff_bps <= 8 ? 1 : 2;
int bufsize = width * 3 * bypp;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width > 32767 || raw_height > 32767)
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixel = raw_width*(raw_height+7);
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)
if(todo[i] < maxpixel)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
else
derror();
}
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)
{
#ifdef LIBRAW_LIBRARY_BUILD
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
int row, col;
#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);
}
}
if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF;
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[0x4002];
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(width>640 || height > 480)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
// All kodak radc images are 768x512
if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if (!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
if(col>=0)
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[272]; /* 264 looks enough */
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
{
int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
if (idx >= 0 && idx < 0xffff)
{
if ((RAW(row, col + i) = curve[idx]) >> 12)
derror();
}
else
derror();
}
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixels = raw_width*(raw_height+7);
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)];
unsigned idest = RAWINDEX(row, col + c);
unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);
if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion
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);
else
derror();
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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++)
if(fabs(num)>0.00001f)
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 & 0x55555555U) << 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)
{
#ifdef LIBRAW_IOSPACE_CHECK
INT64 pos = ftell(ifp);
INT64 fsize = ifp->size();
if(fsize < 12 || (fsize-pos) < 12)
throw LIBRAW_EXCEPTION_IO_EOF;
#endif
*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 libraw_powf64l(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 libraw_powf64l(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
unsigned CLASS setCanonBodyFeatures(unsigned id)
{
if (id == 0x03740000) // EOS M3
id = 0x80000374;
else if (id == 0x03840000) // EOS M10
id = 0x80000384;
else if (id == 0x03940000) // EOS M5
id = 0x80000394;
else if (id == 0x04070000) // EOS M6
id = 0x80000407;
else if (id == 0x03980000) // EOS M100
id = 0x80000398;
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) || // M6
(id == 0x80000398) // M100
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return id;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
if (maxlen < 16)
return; // too short
CameraInfo[0] = 0;
CameraInfo[1] = 0;
if (type == 4)
{
if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) ||
(maxlen == 171) || (maxlen == 264) || (maxlen > 400))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2));
else if (maxlen == 72)
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2));
else if ((maxlen == 85) || (maxlen == 93))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2));
else if ((maxlen == 96) || (maxlen == 104))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2));
}
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
imgdata.other.CameraTemperature = 0.0f;
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x80000398) || // M100
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000))) // G1 X Mark III
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if (id == 0x5330303638ULL)
{
strcpy(model, "E-M10MarkIII");
}
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 24, SEEK_CUR);
tempAp = get2();
if (tempAp != 0)
imgdata.other.CameraTemperature = (float)(tempAp - 128);
tempAp = get2();
if (tempAp != -1)
imgdata.other.FlashGN = ((float)tempAp) / 32;
get2();
// fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x000c)
{
unsigned tS = get4();
sprintf (imgdata.shootinginfo.BodySerial, "%d", tS);
}
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 == 0x009a)
{
get4();
imgdata.sizes.raw_crop.cwidth = get4();
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cleft = get4();
imgdata.sizes.raw_crop.ctop = get4();
}
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 == 0x4013)
{
get4();
imgdata.makernotes.canon.AFMicroAdjMode = get4();
imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4());
}
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 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2cf << 1), SEEK_SET); // offset 719 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000) || // G1 X Mark III
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000398) || // EOS M100
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x1fc << 1), SEEK_SET); // offset 508 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2dc << 1), SEEK_SET); // offset 732 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x230 << 1), SEEK_SET); // offset 560 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
libraw_powf64l(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 =
libraw_powf64l(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 =
libraw_powf64l(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)
{
ushort idx;
static const struct
{
ushort scf[8];
/*
scf[0] camera id
scf[1] camera format
scf[2] camera mount: Minolta A, Sony E, fixed,
scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC
scf[4] lens mount
scf[5] tag 0x2010 group (0 if not used)
scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid
scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid
*/
} SonyCamFeatures[] = {
{256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{267, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{268, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{271, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{272, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{276, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{277, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd},
{289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd},
{294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa},
{295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff},
{298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{301, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa},
{303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa},
{304, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa},
{306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff},
{309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa},
{314, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{315, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{316, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{320, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{321, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{322, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{323, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{324, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{325, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{326, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{327, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{328, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{329, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{330, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{331, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{332, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{333, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{334, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{335, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{336, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{337, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{338, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{343, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{345, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{348, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{349, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{351, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{352, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd},
{355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{359, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{361, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{363, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 0, 0x0320, 0x019f},
{364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff},
};
imgdata.lens.makernotes.CamID = id;
if (id == 2)
{
imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
imgdata.makernotes.sony.group2010 = 0;
imgdata.makernotes.sony.real_iso_offset = 0xffff;
imgdata.makernotes.sony.ImageCount3_offset = 0xffff;
return;
}
else
idx = id - 256;
if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures))
{
if (!SonyCamFeatures[idx].scf[2])
return;
imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1];
imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2];
imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3];
if (SonyCamFeatures[idx].scf[4])
imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4];
imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5];
imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6];
imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7];
}
char *sbstr = strstr(software, " v");
if (sbstr != NULL)
{
sbstr += 2;
imgdata.makernotes.sony.firmware = atof(sbstr);
if ((id == 306) || (id == 311))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if (id == 312)
{
if (imgdata.makernotes.sony.firmware < 2.0f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if ((id == 318) || (id == 340))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01a0;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01b6;
}
}
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id)
{
short bufx;
if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2))
bufx = buf[1];
else if ((id >= 273) && (len >= 3))
bufx = buf[2];
else
return;
imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f;
}
void CLASS process_Sony_0x2010(uchar *buf, ushort len)
{
if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) ||
(len < (imgdata.makernotes.sony.real_iso_offset + 2)))
return;
if (imgdata.other.real_ISO < 0.1f)
{
uchar s[2];
s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]];
s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id)
{
ushort lid;
uchar s[4];
int c;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (len < 2)
return;
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(libraw_powf64l(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(libraw_powf64l(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 (len <= 0x106)
return;
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = libraw_powf64l(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)
{
if (len <= 0x108)
return;
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if (len <= 0x10a)
return;
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))
{
if (len <= 0x116)
return;
// "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)
{
if (len <= 0x117)
return;
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
}
if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362) || (id == 363))
{
if (len <= 0x8d)
return;
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)
{
if (len <= 0xf4)
return;
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))
{
if (len <= 0x7f)
return;
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);
}
if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) &&
(len >= (imgdata.makernotes.sony.ImageCount3_offset + 4)))
{
FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]];
imgdata.makernotes.sony.ImageCount3 = sget4(s);
}
if (id == 362)
{
for (c = 0; c < 6; c++)
{
imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]];
}
}
return;
}
void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id)
{
uchar s[4];
int c;
short bufx = buf[0];
if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f))
{ // 0x9400 'c' version
if ((id == 358) || (id == 362) || (id == 363) || (id == 365))
{
imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]];
}
else
{
FORC4 s[c] = SonySubstitution[buf[0x0a + c]];
imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s);
}
imgdata.makernotes.sony.Sony0x9400_version = 0xc;
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]];
FORC4 s[c] = SonySubstitution[buf[0x12 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots
FORC4 s[c] = SonySubstitution[buf[0x1a + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files
}
else if ((bufx == 0x0c) && (len >= 0x1f))
{ // 0x9400 'b' version
imgdata.makernotes.sony.Sony0x9400_version = 0xb;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]];
}
else if ((bufx == 0x0a) && (len >= 0x23))
{ // 0x9400 'a' version
imgdata.makernotes.sony.Sony0x9400_version = 0xa;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]];
}
else
return;
}
void CLASS process_Sony_0x9402(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) ||
(imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA))
return;
if (len < 5)
return;
short bufx = buf[0x00];
if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff))
return;
imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]);
return;
}
void CLASS process_Sony_0x9403(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = SonySubstitution[buf[4]];
if ((bufx == 0x00) || (bufx == 0x94))
return;
imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]);
return;
}
void CLASS process_Sony_0x9406(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = buf[0];
if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b))
return;
bufx = buf[2];
if ((bufx != 0x08) && (bufx != 0x1b))
return;
imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f;
return;
}
void CLASS process_Sony_0x940c(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) &&
(imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX))
return;
if (len <= 0x000a)
return;
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_0x940e(uchar *buf, ushort len, unsigned id)
{
if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]];
}
else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]];
}
else
return;
if (imgdata.makernotes.sony.AFMicroAdjValue != 0)
imgdata.makernotes.sony.AFMicroAdjOn = 1;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116,
ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400,
ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406,
ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len,
uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_len)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
if (table_buf_0x2010_len)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
if (table_buf_0x9050_len)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
if (table_buf_0x9400_len)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
if (table_buf_0x9402_len)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
if (table_buf_0x9403_len)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
if (table_buf_0x9406_len)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
if (table_buf_0x940c_len)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
if (table_buf_0x940e_len)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id);
free(table_buf_0x940e);
table_buf_0x940e_len = 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]);
if (len == 5478)
{
imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20;
imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0);
imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f;
}
}
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 = libraw_powf64l(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 == 0x3000) && (len < 256000))
{
uchar *table_buf_0x3000;
table_buf_0x3000 = (uchar *)malloc(len);
fread(table_buf_0x3000, len, 1, ifp);
for (int i = 0; i < 20; i++)
imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i];
}
else if (tag == 0x0116 && len < 256000)
{
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_len = len;
fread(table_buf_0x0116, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
}
else if (tag == 0x2010 && len < 256000)
{
table_buf_0x2010 = (uchar *)malloc(len);
table_buf_0x2010_len = len;
fread(table_buf_0x2010, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
}
else if (tag == 0x201a)
{
imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4();
}
else if (tag == 0x201b)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.shootinginfo.FocusMode = (short)uc;
}
else if (tag == 0x202c)
{
imgdata.makernotes.sony.MeteringMode2 = get2();
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_len = len;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
}
else if (tag == 0x9400 && len < 256000)
{
table_buf_0x9400 = (uchar *)malloc(len);
table_buf_0x9400_len = len;
fread(table_buf_0x9400, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
}
else if (tag == 0x9402 && len < 256000)
{
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_len = len;
fread(table_buf_0x9402, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
}
else if (tag == 0x9403 && len < 256000)
{
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_len = len;
fread(table_buf_0x9403, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
}
else if ((tag == 0x9405) && (len < 256000) && (len > 0x64))
{
uchar *table_buf_0x9405;
table_buf_0x9405 = (uchar *)malloc(len);
fread(table_buf_0x9405, len, 1, ifp);
uchar bufx = table_buf_0x9405[0x0];
if (imgdata.other.real_ISO < 0.1f)
{
if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) ||
(bufx == 0xb3) || (bufx == 0xe1))
{
uchar s[2];
s[0] = SonySubstitution[table_buf_0x9405[0x04]];
s[1] = SonySubstitution[table_buf_0x9405[0x05]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
free(table_buf_0x9405);
}
else if (tag == 0x9406 && len < 256000)
{
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_len = len;
fread(table_buf_0x9406, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_len = len;
fread(table_buf_0x940c, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
}
else if (tag == 0x940e && len < 256000)
{
table_buf_0x940e = (uchar *)malloc(len);
table_buf_0x940e_len = len;
fread(table_buf_0x940e, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x940e);
table_buf_0x940e_len = 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);
}
else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2))
{
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cwidth = get4();
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
short nWB, tWB;
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) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) ||
(tag == 0x2050) || (tag == 0x3000))
{
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;
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
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;
}
}
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];
}
}
}
else 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;
}
else 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;
}
else 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();
}
}
else 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;
}
}
else 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();
}
else
{
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(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 0x20200306:
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
break;
case 0x20200307:
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{ /*placeholder */
}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) ||
!strncasecmp(model, "KODAK P712", 10))
{
if (tag == 0xf90b)
{
imgdata.makernotes.kodak.clipBlack = get2();
}
else if (tag == 0xf90c)
{
imgdata.makernotes.kodak.clipWhite = get2();
}
}
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) ||
!strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0045)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2);
break;
case 0x20400612:
case 0x30000612:
imgdata.sizes.raw_crop.cleft = get2();
break;
case 0x20400613:
case 0x30000613:
imgdata.sizes.raw_crop.ctop = get2();
break;
case 0x20400614:
case 0x30000614:
imgdata.sizes.raw_crop.cwidth = get2();
break;
case 0x20400615:
case 0x30000615:
imgdata.sizes.raw_crop.cheight = get2();
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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
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 * libraw_powf64l(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 * libraw_powf64l(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = libraw_powf64l(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = libraw_powf64l(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 == 0x20200306)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
if (tag == 0x20200307)
{
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(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 = libraw_powf64l(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = libraw_powf64l(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, MIN(len,511), ifp);
mn_text[511] = 0;
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=");
if(pos)
{
pos +=4;
char *pos2 = strstr(pos, " ");
if(pos2)
{
l = pos2 - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
#if defined WIN32 || defined(__MINGW32__)
// Win32 strtok is already thread-safe
pos = strtok(ccms, ",");
#else
char *last=0;
pos = strtok_r(ccms, ",",&last);
#endif
if(pos)
{
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];
#if defined WIN32 || defined(__MINGW32__)
pos = strtok(NULL, ",");
#else
pos = strtok_r(NULL, ",",&last);
#endif
if(!pos) goto end; // broken
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
}
}
end:;
}
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) * 0x01010101U << 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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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) * 0x01010101U * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
else if(len < 1)
return;
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 j, c, wbi = -2, romm_camTemp[9], romm_camScale[3];
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1003)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 1004)
imgdata.sizes.raw_crop.ctop = get2();
if (tag == 1005)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 1006)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 1007)
imgdata.makernotes.kodak.BlackLevelTop = get2();
if (tag == 1008)
imgdata.makernotes.kodak.BlackLevelBottom = get2();
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 1030) && (len == 1))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 1043) && (len == 1))
imgdata.other.SensorTemperature = getreal(type);
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9))
{
short validM = 0;
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type);
}
validM = 1;
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
validM = 1;
}
}
if (validM)
{
romm_coeff(imgdata.makernotes.kodak.romm_camDaylight);
}
}
if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
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 == 0xfa13)
width = getint(type);
if (tag == 0xfa14)
height = (getint(type) + 1) & -2;
/*
height = getint(type);
if (tag == 0xfa16)
raw_width = get2();
if (tag == 0xfa17)
raw_height = get2();
*/
if (tag == 0xfa18)
{
imgdata.makernotes.kodak.offset_left = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_left += 1;
}
if (tag == 0xfa19)
{
imgdata.makernotes.kodak.offset_top = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_top += 1;
}
if (tag == 0xfa31)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 0xfa32)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 0xfa3e)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 0xfa3f)
imgdata.sizes.raw_crop.ctop = get2();
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 && savepos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), 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:
if (len == 3)
{
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
else if (len == 1)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here??
}
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;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 10:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_bpp = get2();
}
break;
#endif
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;
case 0x0120:
if (pana_raw)
{
unsigned sorder = order;
unsigned long sbase = base;
base = ftell(ifp);
order = get2();
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, get4()-8, SEEK_CUR);
parse_tiff_ifd (base);
base = sbase;
order = sorder;
}
break;
case 0x2009:
if ((libraw_internal_data.unpacker_data.pana_encoding == 4) ||
(libraw_internal_data.unpacker_data.pana_encoding == 5))
{
int n = MIN (8, len);
int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4};
imgdata.makernotes.panasonic.BlackLevelDim = len;
for (int i=0; i < n; i++)
{
imgdata.makernotes.panasonic.BlackLevel[permut[i]] =
(float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp));
}
}
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;
#ifdef LIBRAW_LIBRARY_BUILD
case 45:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_encoding = get2();
}
break;
#endif
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 */
if ((pana_raw) && (tag == 11) && (type == 3))
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.makernotes.panasonic.Compression = get2();
#endif
break;
}
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++)
{
if(cfa_pat[i] > 31) continue; // Skip wrong data
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4
{
int q = get2();
if(q > 0) cam_mul[c ^ 1] = 4096.0 / q;
}
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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);
if(len>0)
{
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 */
{
float q1 = getreal(type);
float q2 = getreal(type);
if(q1 > 0.00001f && q2 > 0.00001f)
{
pixel_aspect = q1/q2;
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0];
imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1];
}
}
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2];
imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3];
}
}
break;
case 0x74c7:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cleft = get4();
imgdata.makernotes.sony.raw_crop.ctop = get4();
}
break;
case 0x74c8:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cwidth = get4();
imgdata.makernotes.sony.raw_crop.cheight = get4();
}
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;
INT64 save_pos = ifp->tell();
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
curr_pos = save_pos + MakN_length - 6;
fseek(ifp, curr_pos, SEEK_SET);
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "SR2 ", 4))
{
order = 0x4d4d;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
unsigned *buf_SR2;
uchar *cbuf_SR2;
unsigned icbuf_SR2;
unsigned entries, tag, type, len, save;
int ival;
unsigned SR2SubIFDOffset = 0;
unsigned SR2SubIFDLength = 0;
unsigned SR2SubIFDKey = 0;
int base = curr_pos + 6 - pos_in_original_raw;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 0x7200)
{
SR2SubIFDOffset = get4();
}
else if (tag == 0x7201)
{
SR2SubIFDLength = get4();
}
else if (tag == 0x7221)
{
SR2SubIFDKey = get4();
}
fseek(ifp, save, SEEK_SET);
}
if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety
{
fseek(ifp, SR2SubIFDOffset + base, SEEK_SET);
fread(buf_SR2, SR2SubIFDLength, 1, ifp);
sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey);
cbuf_SR2 = (uchar *)buf_SR2;
entries = sget2(cbuf_SR2);
icbuf_SR2 = 2;
while (entries--)
{
tag = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
type = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
len = sget4(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 4;
if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4)
{
ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset;
}
else
{
ival = icbuf_SR2;
}
if(ival > SR2SubIFDLength) // points out of orig. buffer size
break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter
icbuf_SR2 += 4;
switch (tag)
{
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c);
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] =
sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
}
}
free(buf_SR2);
}
} /* SR2 processed */
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
if(fabs(asn[c])>0.0001)
cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC if(fabs(cc[c][c])>0.0001) 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( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535
|| tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535)
continue; /* wrong image dimensions */
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:
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height))
#else
if (tiff_ifd[raw].bytes == raw_width * raw_height)
#endif
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
#else
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
#endif
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps))
#else
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
#endif
{
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) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 &&
INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ
{
tiff_bps = 14;
tiff_samples = 4;
load_raw = &CLASS sony_arq_load_raw;
filters = 0;
strcpy(cdesc, "RGBG");
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL)
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
#endif
load_flags = 24;
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL)
#else
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
#endif
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height))
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
#endif
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:
#ifdef LIBRAW_LIBRARY_BUILD
if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes))
#else
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
#endif
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
{
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 (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL)
{
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 = libraw_powf64l(2.0f, -int_to_float((get4(), get4())));
aperture = libraw_powf64l(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 = libraw_powf64l(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 = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = libraw_powf64l(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
{
ushort q = get2();
cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024;
}
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
unique_id = setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0211:
imgdata.other.SensorTemperature2 = int_to_float(data);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.SensorTemperature = ph1.tag_210;
#endif
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED;
#endif
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/
}
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x110)
{
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cleft = get2();
}
else if (tag == 0x111)
{
imgdata.sizes.raw_crop.cheight = get2();
imgdata.sizes.raw_crop.cwidth = get2();
}
else if ((tag == 0x122) && !strcmp(model, "DBP for GX680"))
{
int k = get2();
int l = get2(); /* margins? */
int m = get2(); /* margins? */
int n = get2();
// printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n);
}
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") ||
!strcmp(model, "X-A5") ||
!strcmp(model, "X-A20"))
{
int wb[4];
int nWB, tWB, pWB;
int iCCT = 0;
int cnt;
fseek(ifp, save + 0x200, SEEK_SET);
for (int wb_ind = 0; wb_ind < 42; wb_ind++)
{
nWB = get4();
tWB = get4();
wb[0] = get4() << 1;
wb[1] = get4();
wb[3] = get4();
wb[2] = get4() << 1;
if (tWB && (iCCT < 255))
{
imgdata.color.WBCT_Coeffs[iCCT][0] = tWB;
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt];
iCCT++;
}
if (nWB != 70)
{
for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2)
{
if (Fuji_wb_list2[pWB] == nWB)
{
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt];
break;
}
}
}
}
}
else
{
libraw_internal_data.unpacker_data.posRAFData = save;
libraw_internal_data.unpacker_data.lenRAFData = (len >> 1);
}
#endif
order = c;
}
fseek(ifp, save + len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg(int offset)
{
int len, save, hlen, mark;
fseek(ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)
{
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)
{
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150
#ifdef LIBRAW_LIBRARY_BUILD
&& (save + hlen) >= 0 && (save + hlen) <= ifp->size()
#endif
) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(save + hlen, len - hlen, 0);
}
if (parse_tiff(save + 6))
apply_tiff();
fseek(ifp, save + len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
struct tm t;
order = 0x4949;
fread(tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4))
{
int maxloop = 1000;
get4();
while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--)
parse_riff();
}
else if (!memcmp(tag, "nctg", 4))
{
while (ftell(ifp) + 7 < end)
{
i = get2();
size = get2();
if ((i + 1) >> 1 == 10 && size == 20)
get_timestamp(0);
else
fseek(ifp, size, SEEK_CUR);
}
}
else if (!memcmp(tag, "IDIT", 4) && size < 64)
{
fread(date, 64, 1, ifp);
date[size] = 0;
memset(&t, 0, sizeof t);
if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6)
{
for (i = 0; i < 12 && strcasecmp(mon[i], month); i++)
;
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
}
else
fseek(ifp, size, SEEK_CUR);
}
void CLASS parse_qt(int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp) + 7 < end)
{
save = ftell(ifp);
if ((size = get4()) < 8)
return;
fread(tag, 4, 1, ifp);
if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4))
parse_qt(save + size);
if (!memcmp(tag, "CNDA", 4))
parse_jpeg(ftell(ifp));
fseek(ifp, save + size, SEEK_SET);
}
}
void CLASS parse_smal(int offset, int fsize)
{
int ver;
fseek(ifp, offset + 2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek(ifp, 5, SEEK_CUR);
if (get4() != fsize)
return;
if (ver > 6)
data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy(make, "SMaL");
sprintf(model, "v%d %dx%d", ver, width, height);
if (ver == 6)
load_raw = &CLASS smal_v6_load_raw;
if (ver == 9)
load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek(ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4()))
timestamp = i;
fseek(ifp, off_head + 4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(), get2())
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 16:
load_raw = &CLASS unpacked_load_raw;
}
fseek(ifp, off_setup + 792, SEEK_SET);
strcpy(make, "CINE");
sprintf(model, "%d", get4());
fseek(ifp, 12, SEEK_CUR);
switch ((i = get4()) & 0xffffff)
{
case 3:
filters = 0x94949494;
break;
case 4:
filters = 0x49494949;
break;
default:
is_raw = 0;
}
fseek(ifp, 72, SEEK_CUR);
switch ((get4() + 3600) % 360)
{
case 270:
flip = 4;
break;
case 180:
flip = 1;
break;
case 90:
flip = 7;
break;
case 0:
flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek(ifp, 668, SEEK_CUR);
shutter = get4() / 1000000000.0;
fseek(ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek(ifp, shot_select * 8, SEEK_CUR);
data_offset = (INT64)get4() + 8;
data_offset += (INT64)get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek(ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek(ifp, 0, SEEK_END);
fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek(ifp, 0, SEEK_SET);
while ((len = get4()) != EOF)
{
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek(ifp, len - 8, SEEK_CUR);
}
}
else
{
rdvo = get4();
fseek(ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET);
data_offset = get4();
}
}
//@end COMMON
char *CLASS foveon_gets(int offset, char *str, int len)
{
int i;
fseek(ifp, offset, SEEK_SET);
for (i = 0; i < len - 1; i++)
if ((str[i] = get2()) == 0)
break;
str[i] = 0;
return str;
}
void CLASS parse_foveon()
{
int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2];
char name[64], value[64];
order = 0x4949; /* Little-endian */
fseek(ifp, 36, SEEK_SET);
flip = get4();
fseek(ifp, -4, SEEK_END);
fseek(ifp, get4(), SEEK_SET);
if (get4() != 0x64434553)
return; /* SECd */
entries = (get4(), get4());
while (entries--)
{
off = get4();
len = get4();
tag = get4();
save = ftell(ifp);
fseek(ifp, off, SEEK_SET);
if (get4() != (0x20434553 | (tag << 24)))
return;
switch (tag)
{
case 0x47414d49: /* IMAG */
case 0x32414d49: /* IMA2 */
fseek(ifp, 8, SEEK_CUR);
pent = get4();
wide = get4();
high = get4();
if (wide > raw_width && high > raw_height)
{
switch (pent)
{
case 5:
load_flags = 1;
case 6:
load_raw = &CLASS foveon_sd_load_raw;
break;
case 30:
load_raw = &CLASS foveon_dp_load_raw;
break;
default:
load_raw = 0;
}
raw_width = wide;
raw_height = high;
data_offset = off + 28;
is_foveon = 1;
}
fseek(ifp, off + 28, SEEK_SET);
if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28)
{
thumb_offset = off + 28;
thumb_length = len - 28;
write_thumb = &CLASS jpeg_thumb;
}
if (++img == 2 && !thumb_length)
{
thumb_offset = off + 24;
thumb_width = wide;
thumb_height = high;
write_thumb = &CLASS foveon_thumb;
}
break;
case 0x464d4143: /* CAMF */
meta_offset = off + 8;
meta_length = len - 28;
break;
case 0x504f5250: /* PROP */
pent = (get4(), get4());
fseek(ifp, 12, SEEK_CUR);
off += pent * 8 + 24;
if ((unsigned)pent > 256)
pent = 256;
for (i = 0; i < pent * 2; i++)
((int *)poff)[i] = off + get4() * 2;
for (i = 0; i < pent; i++)
{
foveon_gets(poff[i][0], name, 64);
foveon_gets(poff[i][1], value, 64);
if (!strcmp(name, "ISO"))
iso_speed = atoi(value);
if (!strcmp(name, "CAMMANUF"))
strcpy(make, value);
if (!strcmp(name, "CAMMODEL"))
strcpy(model, value);
if (!strcmp(name, "WB_DESC"))
strcpy(model2, value);
if (!strcmp(name, "TIME"))
timestamp = atoi(value);
if (!strcmp(name, "EXPTIME"))
shutter = atoi(value) / 1000000.0;
if (!strcmp(name, "APERTURE"))
aperture = atof(value);
if (!strcmp(name, "FLENGTH"))
focal_len = atof(value);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(name, "CAMSERIAL"))
strcpy(imgdata.shootinginfo.BodySerial, value);
if (!strcmp(name, "FLEQ35MM"))
imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value);
if (!strcmp(name, "IMAGERTEMP"))
imgdata.other.SensorTemperature = atof(value);
if (!strcmp(name, "LENSARANGE"))
{
char *sp;
imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MinAp4CurFocal = atof(sp);
if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal)
my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal);
}
}
if (!strcmp(name, "LENSFRANGE"))
{
char *sp;
imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MaxFocal = atof(sp);
if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal)
my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal);
}
}
if (!strcmp(name, "LENSMODEL"))
{
char *sp;
imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value);
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = Sigma_X3F;
}
}
#endif
}
#ifdef LOCALTIME
timestamp = mktime(gmtime(×tamp));
#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,
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82,
{7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M100", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark III", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A20", 0, 0, /* temp */
{ 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-A5", 0, 0, /* temp */
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-E3", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-H1", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D850", 0, 0,
{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL9", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-G9", -15, 0,
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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-GH5s", -15, 0,
{ 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } },
{ "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-GF10", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "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 DC-GX9", -15, 0, /* temp */
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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 } },
{ "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// {3984,0,0,0,10000,0,0,0,7666}},
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
// {2423,0,0,0,9901,0,0,0,7989}},
{ 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10M4", -800, 0,
{ 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{"Sony DSC-RX0", -800, 0, /* temp */
{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 16596,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 16596,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A550", 0, 16596,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */
{ 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-7M3", 0, 0,
{ 7374,-2389,-551,-5435,13162,2519,-1006,1795,6552 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM3", 0, 0,
{ 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } },
{ "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};
if(width > 2064) return 0.f; // too wide
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((unsigned char)string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x398, "EOS M100"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16b, "ILCE-7M3"}, {0x16c, "DSC-RX0"},
{0x16d, "DSC-RX10M4"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 =
imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature =
imgdata.other.exifAmbientTemperature = -1000.0f;
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT;
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 = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = libraw_powf64l(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 = libraw_powf64l(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
strncpy(model, head + 0x1c,0x20);
model[0x20]=0;
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4(); // bytes count
width = get2();
height = get2();
#ifdef LIBRAW_LIBRARY_BUILD
// Data integrity check
if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height))
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
/* no foveon support for dcraw build from libraw source */
parse_x3f();
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
break;
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
memmove(model, model + 8,strlen(model)-7);
if (!strncmp(model, "Digital Camera ", 15))
memmove(model, model + 15,strlen(model)-14);
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] * 0x01010101U;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c, A6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
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 = 0x01010101U * (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
/* alloc in unpack() may be fooled by size adjust */
|| ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535))
{
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 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&
tiff_ifd[sidx].dng_levels.default_crop[3] > 0)
{
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 libraw_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 libraw_tiff_tag tag[23];
int nextifd;
ushort pad2, nexif;
struct libraw_tiff_tag exif[4];
ushort pad3, ngps;
struct libraw_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 libraw_tiff_tag *tt;
int c;
tt = (struct libraw_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(×tamp);
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(×tamp));
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-835/c/bad_581_0 |
crossvul-cpp_data_good_4059_1 | /*
* 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.
*/
/*
* vncviewer.c - the Xt-based VNC viewer.
*/
#ifdef WIN32
#include <winsock2.h>
#endif
#ifdef _MSC_VER
#define strdup _strdup /* Prevent POSIX deprecation warnings */
#endif
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <rfb/rfbclient.h>
#include "tls.h"
static void Dummy(rfbClient* client) {
}
static rfbBool DummyPoint(rfbClient* client, int x, int y) {
return TRUE;
}
static void DummyRect(rfbClient* client, int x, int y, int w, int h) {
}
#ifdef WIN32
static char* NoPassword(rfbClient* client) {
return strdup("");
}
#else
#include <stdio.h>
#include <termios.h>
#endif
static char* ReadPassword(rfbClient* client) {
int i;
char* p=calloc(1,9);
#ifndef WIN32
struct termios save,noecho;
if(tcgetattr(fileno(stdin),&save)!=0) return p;
noecho=save; noecho.c_lflag &= ~ECHO;
if(tcsetattr(fileno(stdin),TCSAFLUSH,&noecho)!=0) return p;
#endif
fprintf(stderr,"Password: ");
i=0;
while(1) {
int c=fgetc(stdin);
if(c=='\n')
break;
if(i<8) {
p[i]=c;
i++;
p[i]=0;
}
}
#ifndef WIN32
tcsetattr(fileno(stdin),TCSAFLUSH,&save);
#endif
return p;
}
static rfbBool MallocFrameBuffer(rfbClient* client) {
uint64_t allocSize;
if(client->frameBuffer)
free(client->frameBuffer);
/* SECURITY: promote 'width' into uint64_t so that the multiplication does not overflow
'width' and 'height' are 16-bit integers per RFB protocol design
SIZE_MAX is the maximum value that can fit into size_t
*/
allocSize = (uint64_t)client->width * client->height * client->format.bitsPerPixel/8;
if (allocSize >= SIZE_MAX) {
rfbClientErr("CRITICAL: cannot allocate frameBuffer, requested size is too large\n");
return FALSE;
}
client->frameBuffer=malloc( (size_t)allocSize );
if (client->frameBuffer == NULL)
rfbClientErr("CRITICAL: frameBuffer allocation failed, requested size too large or not enough memory?\n");
return client->frameBuffer?TRUE:FALSE;
}
/* messages */
static rfbBool CheckRect(rfbClient* client, int x, int y, int w, int h) {
return x + w <= client->width && y + h <= client->height;
}
static void FillRectangle(rfbClient* client, int x, int y, int w, int h, uint32_t colour) {
int i,j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, x, y, w, h)) {
rfbClientLog("Rect out of bounds: %dx%d at (%d, %d)\n", x, y, w, h);
return;
}
#define FILL_RECT(BPP) \
for(j=y*client->width;j<(y+h)*client->width;j+=client->width) \
for(i=x;i<x+w;i++) \
((uint##BPP##_t*)client->frameBuffer)[j+i]=colour;
switch(client->format.bitsPerPixel) {
case 8: FILL_RECT(8); break;
case 16: FILL_RECT(16); break;
case 32: FILL_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
static void CopyRectangle(rfbClient* client, const uint8_t* buffer, int x, int y, int w, int h) {
int j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, x, y, w, h)) {
rfbClientLog("Rect out of bounds: %dx%d at (%d, %d)\n", x, y, w, h);
return;
}
#define COPY_RECT(BPP) \
{ \
int rs = w * BPP / 8, rs2 = client->width * BPP / 8; \
for (j = ((x * (BPP / 8)) + (y * rs2)); j < (y + h) * rs2; j += rs2) { \
memcpy(client->frameBuffer + j, buffer, rs); \
buffer += rs; \
} \
}
switch(client->format.bitsPerPixel) {
case 8: COPY_RECT(8); break;
case 16: COPY_RECT(16); break;
case 32: COPY_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
/* TODO: test */
static void CopyRectangleFromRectangle(rfbClient* client, int src_x, int src_y, int w, int h, int dest_x, int dest_y) {
int i,j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, src_x, src_y, w, h)) {
rfbClientLog("Source rect out of bounds: %dx%d at (%d, %d)\n", src_x, src_y, w, h);
return;
}
if (!CheckRect(client, dest_x, dest_y, w, h)) {
rfbClientLog("Dest rect out of bounds: %dx%d at (%d, %d)\n", dest_x, dest_y, w, h);
return;
}
#define COPY_RECT_FROM_RECT(BPP) \
{ \
uint##BPP##_t* _buffer=((uint##BPP##_t*)client->frameBuffer)+(src_y-dest_y)*client->width+src_x-dest_x; \
if (dest_y < src_y) { \
for(j = dest_y*client->width; j < (dest_y+h)*client->width; j += client->width) { \
if (dest_x < src_x) { \
for(i = dest_x; i < dest_x+w; i++) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} else { \
for(i = dest_x+w-1; i >= dest_x; i--) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} \
} \
} else { \
for(j = (dest_y+h-1)*client->width; j >= dest_y*client->width; j-=client->width) { \
if (dest_x < src_x) { \
for(i = dest_x; i < dest_x+w; i++) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} else { \
for(i = dest_x+w-1; i >= dest_x; i--) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} \
} \
} \
}
switch(client->format.bitsPerPixel) {
case 8: COPY_RECT_FROM_RECT(8); break;
case 16: COPY_RECT_FROM_RECT(16); break;
case 32: COPY_RECT_FROM_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
static void initAppData(AppData* data) {
data->shareDesktop=TRUE;
data->viewOnly=FALSE;
data->encodingsString="tight zrle ultra copyrect hextile zlib corre rre raw";
data->useBGR233=FALSE;
data->nColours=0;
data->forceOwnCmap=FALSE;
data->forceTrueColour=FALSE;
data->requestedDepth=0;
data->compressLevel=3;
data->qualityLevel=5;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
data->enableJPEG=TRUE;
#else
data->enableJPEG=FALSE;
#endif
data->useRemoteCursor=FALSE;
}
rfbClient* rfbGetClient(int bitsPerSample,int samplesPerPixel,
int bytesPerPixel) {
#ifdef WIN32
WSADATA unused;
#endif
rfbClient* client=(rfbClient*)calloc(sizeof(rfbClient),1);
if(!client) {
rfbClientErr("Couldn't allocate client structure!\n");
return NULL;
}
#ifdef WIN32
if((errno = WSAStartup(MAKEWORD(2,0), &unused)) != 0) {
rfbClientErr("Could not init Windows Sockets: %s\n", strerror(errno));
return NULL;
}
#endif
initAppData(&client->appData);
client->endianTest = 1;
client->programName="";
client->serverHost=strdup("");
client->serverPort=5900;
client->destHost = NULL;
client->destPort = 5900;
client->connectTimeout = DEFAULT_CONNECT_TIMEOUT;
client->readTimeout = DEFAULT_READ_TIMEOUT;
client->CurrentKeyboardLedState = 0;
client->HandleKeyboardLedState = (HandleKeyboardLedStateProc)DummyPoint;
/* default: use complete frame buffer */
client->updateRect.x = -1;
client->frameBuffer = NULL;
client->outputWindow = 0;
client->format.bitsPerPixel = bytesPerPixel*8;
client->format.depth = bitsPerSample*samplesPerPixel;
client->appData.requestedDepth=client->format.depth;
client->format.bigEndian = *(char *)&client->endianTest?FALSE:TRUE;
client->format.trueColour = 1;
if (client->format.bitsPerPixel == 8) {
client->format.redMax = 7;
client->format.greenMax = 7;
client->format.blueMax = 3;
client->format.redShift = 0;
client->format.greenShift = 3;
client->format.blueShift = 6;
} else {
client->format.redMax = (1 << bitsPerSample) - 1;
client->format.greenMax = (1 << bitsPerSample) - 1;
client->format.blueMax = (1 << bitsPerSample) - 1;
if(!client->format.bigEndian) {
client->format.redShift = 0;
client->format.greenShift = bitsPerSample;
client->format.blueShift = bitsPerSample * 2;
} else {
if(client->format.bitsPerPixel==8*3) {
client->format.redShift = bitsPerSample*2;
client->format.greenShift = bitsPerSample*1;
client->format.blueShift = 0;
} else {
client->format.redShift = bitsPerSample*3;
client->format.greenShift = bitsPerSample*2;
client->format.blueShift = bitsPerSample;
}
}
}
client->bufoutptr=client->buf;
client->buffered=0;
#ifdef LIBVNCSERVER_HAVE_LIBZ
client->raw_buffer_size = -1;
client->decompStreamInited = FALSE;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
memset(client->zlibStreamActive,0,sizeof(rfbBool)*4);
#endif
#endif
client->HandleCursorPos = DummyPoint;
client->SoftCursorLockArea = DummyRect;
client->SoftCursorUnlockScreen = Dummy;
client->GotFrameBufferUpdate = DummyRect;
client->GotCopyRect = CopyRectangleFromRectangle;
client->GotFillRect = FillRectangle;
client->GotBitmap = CopyRectangle;
client->FinishedFrameBufferUpdate = NULL;
client->GetPassword = ReadPassword;
client->MallocFrameBuffer = MallocFrameBuffer;
client->Bell = Dummy;
client->CurrentKeyboardLedState = 0;
client->HandleKeyboardLedState = (HandleKeyboardLedStateProc)DummyPoint;
client->QoS_DSCP = 0;
client->authScheme = 0;
client->subAuthScheme = 0;
client->GetCredential = NULL;
client->tlsSession = NULL;
client->LockWriteToTLS = NULL;
client->UnlockWriteToTLS = NULL;
client->sock = RFB_INVALID_SOCKET;
client->listenSock = RFB_INVALID_SOCKET;
client->listenAddress = NULL;
client->listen6Sock = RFB_INVALID_SOCKET;
client->listen6Address = NULL;
client->clientAuthSchemes = NULL;
#ifdef LIBVNCSERVER_HAVE_SASL
client->GetSASLMechanism = NULL;
client->GetUser = NULL;
client->saslSecret = NULL;
#endif /* LIBVNCSERVER_HAVE_SASL */
return client;
}
static rfbBool rfbInitConnection(rfbClient* client)
{
/* Unless we accepted an incoming connection, make a TCP connection to the
given VNC server */
if (!client->listenSpecified) {
if (!client->serverHost)
return FALSE;
if (client->destHost) {
if (!ConnectToRFBRepeater(client,client->serverHost,client->serverPort,client->destHost,client->destPort))
return FALSE;
} else {
if (!ConnectToRFBServer(client,client->serverHost,client->serverPort))
return FALSE;
}
}
/* Initialise the VNC connection, including reading the password */
if (!InitialiseRFBConnection(client))
return FALSE;
client->width=client->si.framebufferWidth;
client->height=client->si.framebufferHeight;
if (!client->MallocFrameBuffer(client))
return FALSE;
if (!SetFormatAndEncodings(client))
return FALSE;
if (client->updateRect.x < 0) {
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
}
if (client->appData.scaleSetting>1)
{
if (!SendScaleSetting(client, client->appData.scaleSetting))
return FALSE;
if (!SendFramebufferUpdateRequest(client,
client->updateRect.x / client->appData.scaleSetting,
client->updateRect.y / client->appData.scaleSetting,
client->updateRect.w / client->appData.scaleSetting,
client->updateRect.h / client->appData.scaleSetting,
FALSE))
return FALSE;
}
else
{
if (!SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h,
FALSE))
return FALSE;
}
return TRUE;
}
rfbBool rfbInitClient(rfbClient* client,int* argc,char** argv) {
int i,j;
if(argv && argc && *argc) {
if(client->programName==0)
client->programName=argv[0];
for (i = 1; i < *argc; i++) {
j = i;
if (strcmp(argv[i], "-listen") == 0) {
listenForIncomingConnections(client);
break;
} else if (strcmp(argv[i], "-listennofork") == 0) {
listenForIncomingConnectionsNoFork(client, -1);
break;
} else if (strcmp(argv[i], "-play") == 0) {
client->serverPort = -1;
j++;
} else if (i+1<*argc && strcmp(argv[i], "-encodings") == 0) {
client->appData.encodingsString = argv[i+1];
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-compress") == 0) {
client->appData.compressLevel = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-quality") == 0) {
client->appData.qualityLevel = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-scale") == 0) {
client->appData.scaleSetting = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-qosdscp") == 0) {
client->QoS_DSCP = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-repeaterdest") == 0) {
char* colon=strchr(argv[i+1],':');
if(client->destHost)
free(client->destHost);
client->destPort = 5900;
client->destHost = strdup(argv[i+1]);
if(colon) {
client->destHost[(int)(colon-argv[i+1])] = '\0';
client->destPort = atoi(colon+1);
}
j+=2;
} else {
char* colon=strrchr(argv[i],':');
if(client->serverHost)
free(client->serverHost);
if(colon) {
client->serverHost = strdup(argv[i]);
client->serverHost[(int)(colon-argv[i])] = '\0';
client->serverPort = atoi(colon+1);
} else {
client->serverHost = strdup(argv[i]);
}
if(client->serverPort >= 0 && client->serverPort < 5900)
client->serverPort += 5900;
}
/* purge arguments */
if (j>i) {
*argc-=j-i;
memmove(argv+i,argv+j,(*argc-i)*sizeof(char*));
i--;
}
}
}
if(!rfbInitConnection(client)) {
rfbClientCleanup(client);
return FALSE;
}
return TRUE;
}
void rfbClientCleanup(rfbClient* client) {
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
int i;
for ( i = 0; i < 4; i++ ) {
if (client->zlibStreamActive[i] == TRUE ) {
if (inflateEnd (&client->zlibStream[i]) != Z_OK &&
client->zlibStream[i].msg != NULL)
rfbClientLog("inflateEnd: %s\n", client->zlibStream[i].msg);
}
}
if ( client->decompStreamInited == TRUE ) {
if (inflateEnd (&client->decompStream) != Z_OK &&
client->decompStream.msg != NULL)
rfbClientLog("inflateEnd: %s\n", client->decompStream.msg );
}
#endif
#endif
if (client->ultra_buffer)
free(client->ultra_buffer);
if (client->raw_buffer)
free(client->raw_buffer);
FreeTLS(client);
while (client->clientData) {
rfbClientData* next = client->clientData->next;
free(client->clientData);
client->clientData = next;
}
if (client->sock != RFB_INVALID_SOCKET)
rfbCloseSocket(client->sock);
if (client->listenSock != RFB_INVALID_SOCKET)
rfbCloseSocket(client->listenSock);
free(client->desktopName);
free(client->serverHost);
if (client->destHost)
free(client->destHost);
if (client->clientAuthSchemes)
free(client->clientAuthSchemes);
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslSecret)
free(client->saslSecret);
#endif /* LIBVNCSERVER_HAVE_SASL */
#ifdef WIN32
if(WSACleanup() != 0) {
errno=WSAGetLastError();
rfbClientErr("Could not terminate Windows Sockets: %s\n", strerror(errno));
}
#endif
free(client);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_4059_1 |
crossvul-cpp_data_bad_4059_0 | /*
* Copyright (C) 2011-2012 Christian Beier <dontmind@freeshell.org>
* 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.
*/
/*
* sockets.c - functions to deal with sockets.
*/
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#ifdef __linux__
/* Setting this on other systems hides definitions such as INADDR_LOOPBACK.
* The check should be for __GLIBC__ in fact. */
# define _POSIX_SOURCE
#endif
#endif
#if LIBVNCSERVER_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#include <rfb/rfbclient.h>
#include "sockets.h"
#include "tls.h"
#include "sasl.h"
void PrintInHex(char *buf, int len);
rfbBool errorMessageOnReadFailure = TRUE;
/*
* ReadFromRFBServer is called whenever we want to read some data from the RFB
* server. It is non-trivial for two reasons:
*
* 1. For efficiency it performs some intelligent buffering, avoiding invoking
* the read() system call too often. For small chunks of data, it simply
* copies the data out of an internal buffer. For large amounts of data it
* reads directly into the buffer provided by the caller.
*
* 2. Whenever read() would block, it invokes the Xt event dispatching
* mechanism to process X events. In fact, this is the only place these
* events are processed, as there is no XtAppMainLoop in the program.
*/
rfbBool
ReadFromRFBServer(rfbClient* client, char *out, unsigned int n)
{
#undef DEBUG_READ_EXACT
#ifdef DEBUG_READ_EXACT
char* oout=out;
unsigned int nn=n;
rfbClientLog("ReadFromRFBServer %d bytes\n",n);
#endif
/* Handle attempts to write to NULL out buffer that might occur
when an outside malloc() fails. For instance, memcpy() to NULL
results in undefined behaviour and probably memory corruption.*/
if(!out)
return FALSE;
if (client->serverPort==-1) {
/* vncrec playing */
rfbVNCRec* rec = client->vncRec;
struct timeval tv;
if (rec->readTimestamp) {
rec->readTimestamp = FALSE;
if (!fread(&tv,sizeof(struct timeval),1,rec->file))
return FALSE;
tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec);
tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec);
if (rec->tv.tv_sec!=0 && !rec->doNotSleep) {
struct timeval diff;
diff.tv_sec = tv.tv_sec - rec->tv.tv_sec;
diff.tv_usec = tv.tv_usec - rec->tv.tv_usec;
if(diff.tv_usec<0) {
diff.tv_sec--;
diff.tv_usec+=1000000;
}
#ifndef WIN32
sleep (diff.tv_sec);
usleep (diff.tv_usec);
#else
Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000);
#endif
}
rec->tv=tv;
}
return (fread(out,1,n,rec->file) != n ? FALSE : TRUE);
}
if (n <= client->buffered) {
memcpy(out, client->bufoutptr, n);
client->bufoutptr += n;
client->buffered -= n;
#ifdef DEBUG_READ_EXACT
goto hexdump;
#endif
return TRUE;
}
memcpy(out, client->bufoutptr, client->buffered);
out += client->buffered;
n -= client->buffered;
client->bufoutptr = client->buf;
client->buffered = 0;
if (n <= RFB_BUF_SIZE) {
while (client->buffered < n) {
int i;
if (client->tlsSession)
i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
else
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn)
i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
else {
#endif /* LIBVNCSERVER_HAVE_SASL */
i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered);
#ifdef WIN32
if (i < 0) errno=WSAGetLastError();
#endif
#ifdef LIBVNCSERVER_HAVE_SASL
}
#endif
if (i <= 0) {
if (i < 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
/* TODO:
ProcessXtEvents();
*/
WaitForMessage(client, 100000);
i = 0;
} else {
rfbClientErr("read (%d: %s)\n",errno,strerror(errno));
return FALSE;
}
} else {
if (errorMessageOnReadFailure) {
rfbClientLog("VNC server closed connection\n");
}
return FALSE;
}
}
client->buffered += i;
}
memcpy(out, client->bufoutptr, n);
client->bufoutptr += n;
client->buffered -= n;
} else {
while (n > 0) {
int i;
if (client->tlsSession)
i = ReadFromTLS(client, out, n);
else
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn)
i = ReadFromSASL(client, out, n);
else
#endif
i = read(client->sock, out, n);
if (i <= 0) {
if (i < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (errno == EWOULDBLOCK || errno == EAGAIN) {
/* TODO:
ProcessXtEvents();
*/
WaitForMessage(client, 100000);
i = 0;
} else {
rfbClientErr("read (%s)\n",strerror(errno));
return FALSE;
}
} else {
if (errorMessageOnReadFailure) {
rfbClientLog("VNC server closed connection\n");
}
return FALSE;
}
}
out += i;
n -= i;
}
}
#ifdef DEBUG_READ_EXACT
hexdump:
{ unsigned int ii;
for(ii=0;ii<nn;ii++)
fprintf(stderr,"%02x ",(unsigned char)oout[ii]);
fprintf(stderr,"\n");
}
#endif
return TRUE;
}
/*
* Write an exact number of bytes, and don't return until you've sent them.
*/
rfbBool
WriteToRFBServer(rfbClient* client, const char *buf, unsigned int n)
{
fd_set fds;
int i = 0;
int j;
const char *obuf = buf;
#ifdef LIBVNCSERVER_HAVE_SASL
const char *output;
unsigned int outputlen;
int err;
#endif /* LIBVNCSERVER_HAVE_SASL */
if (client->serverPort==-1)
return TRUE; /* vncrec playing */
if (client->tlsSession) {
/* WriteToTLS() will guarantee either everything is written, or error/eof returns */
i = WriteToTLS(client, buf, n);
if (i <= 0) return FALSE;
return TRUE;
}
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslconn) {
err = sasl_encode(client->saslconn,
buf, n,
&output, &outputlen);
if (err != SASL_OK) {
rfbClientLog("Failed to encode SASL data %s",
sasl_errstring(err, NULL, NULL));
return FALSE;
}
obuf = output;
n = outputlen;
}
#endif /* LIBVNCSERVER_HAVE_SASL */
while (i < n) {
j = write(client->sock, obuf + i, (n - i));
if (j <= 0) {
if (j < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (errno == EWOULDBLOCK ||
#ifdef LIBVNCSERVER_ENOENT_WORKAROUND
errno == ENOENT ||
#endif
errno == EAGAIN) {
FD_ZERO(&fds);
FD_SET(client->sock,&fds);
if (select(client->sock+1, NULL, &fds, NULL, NULL) <= 0) {
rfbClientErr("select\n");
return FALSE;
}
j = 0;
} else {
rfbClientErr("write\n");
return FALSE;
}
} else {
rfbClientLog("write failed\n");
return FALSE;
}
}
i += j;
}
return TRUE;
}
static rfbBool WaitForConnected(int socket, unsigned int secs)
{
fd_set writefds;
fd_set exceptfds;
struct timeval timeout;
timeout.tv_sec=secs;
timeout.tv_usec=0;
FD_ZERO(&writefds);
FD_SET(socket, &writefds);
FD_ZERO(&exceptfds);
FD_SET(socket, &exceptfds);
if (select(socket+1, NULL, &writefds, &exceptfds, &timeout)==1) {
#ifdef WIN32
if (FD_ISSET(socket, &exceptfds))
return FALSE;
#else
int so_error;
socklen_t len = sizeof so_error;
getsockopt(socket, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error!=0)
return FALSE;
#endif
return TRUE;
}
return FALSE;
}
rfbSocket
ConnectClientToTcpAddr(unsigned int host, int port)
{
rfbSocket sock = ConnectClientToTcpAddrWithTimeout(host, port, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToTcpAddrWithTimeout(unsigned int host, int port, unsigned int timeout)
{
rfbSocket sock;
struct sockaddr_in addr;
int one = 1;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = host;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbClientErr("ConnectToTcpAddr: socket (%s)\n",strerror(errno));
return RFB_INVALID_SOCKET;
}
if (!SetNonBlocking(sock))
return FALSE;
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if (!((errno == EWOULDBLOCK || errno == EINPROGRESS) && WaitForConnected(sock, timeout))) {
rfbClientErr("ConnectToTcpAddr: connect\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("ConnectToTcpAddr: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
rfbSocket
ConnectClientToTcpAddr6(const char *hostname, int port)
{
rfbSocket sock = ConnectClientToTcpAddr6WithTimeout(hostname, port, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToTcpAddr6WithTimeout(const char *hostname, int port, unsigned int timeout)
{
#ifdef LIBVNCSERVER_IPv6
rfbSocket sock;
int n;
struct addrinfo hints, *res, *ressave;
char port_s[10];
int one = 1;
snprintf(port_s, 10, "%d", port);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((n = getaddrinfo(strcmp(hostname,"") == 0 ? "localhost": hostname, port_s, &hints, &res)))
{
rfbClientErr("ConnectClientToTcpAddr6: getaddrinfo (%s)\n", gai_strerror(n));
return RFB_INVALID_SOCKET;
}
ressave = res;
sock = RFB_INVALID_SOCKET;
while (res)
{
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock != RFB_INVALID_SOCKET)
{
if (SetNonBlocking(sock)) {
if (connect(sock, res->ai_addr, res->ai_addrlen) == 0) {
break;
} else {
#ifdef WIN32
errno=WSAGetLastError();
#endif
if ((errno == EWOULDBLOCK || errno == EINPROGRESS) && WaitForConnected(sock, timeout))
break;
rfbCloseSocket(sock);
sock = RFB_INVALID_SOCKET;
}
} else {
rfbCloseSocket(sock);
sock = RFB_INVALID_SOCKET;
}
}
res = res->ai_next;
}
freeaddrinfo(ressave);
if (sock == RFB_INVALID_SOCKET)
{
rfbClientErr("ConnectClientToTcpAddr6: connect\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("ConnectToTcpAddr: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
#else
rfbClientErr("ConnectClientToTcpAddr6: IPv6 disabled\n");
return RFB_INVALID_SOCKET;
#endif
}
rfbSocket
ConnectClientToUnixSock(const char *sockFile)
{
rfbSocket sock = ConnectClientToUnixSockWithTimeout(sockFile, DEFAULT_CONNECT_TIMEOUT);
/* put socket back into blocking mode for compatibility reasons */
if (sock != RFB_INVALID_SOCKET) {
SetBlocking(sock);
}
return sock;
}
rfbSocket
ConnectClientToUnixSockWithTimeout(const char *sockFile, unsigned int timeout)
{
#ifdef WIN32
rfbClientErr("Windows doesn't support UNIX sockets\n");
return RFB_INVALID_SOCKET;
#else
rfbSocket sock;
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
if(strlen(sockFile) + 1 > sizeof(addr.sun_path)) {
rfbClientErr("ConnectToUnixSock: socket file name too long\n");
return RFB_INVALID_SOCKET;
}
strcpy(addr.sun_path, sockFile);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("ConnectToUnixSock: socket (%s)\n",strerror(errno));
return RFB_INVALID_SOCKET;
}
if (!SetNonBlocking(sock))
return RFB_INVALID_SOCKET;
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr.sun_family) + strlen(addr.sun_path)) < 0 &&
!(errno == EINPROGRESS && WaitForConnected(sock, timeout))) {
rfbClientErr("ConnectToUnixSock: connect\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
#endif
}
/*
* FindFreeTcpPort tries to find unused TCP port in the range
* (TUNNEL_PORT_OFFSET, TUNNEL_PORT_OFFSET + 99]. Returns 0 on failure.
*/
int
FindFreeTcpPort(void)
{
rfbSocket sock;
int port;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr(": FindFreeTcpPort: socket\n");
return 0;
}
for (port = TUNNEL_PORT_OFFSET + 99; port > TUNNEL_PORT_OFFSET; port--) {
addr.sin_port = htons((unsigned short)port);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
rfbCloseSocket(sock);
return port;
}
}
rfbCloseSocket(sock);
return 0;
}
/*
* ListenAtTcpPort starts listening at the given TCP port.
*/
rfbSocket
ListenAtTcpPort(int port)
{
return ListenAtTcpPortAndAddress(port, NULL);
}
/*
* ListenAtTcpPortAndAddress starts listening at the given TCP port on
* the given IP address
*/
rfbSocket
ListenAtTcpPortAndAddress(int port, const char *address)
{
rfbSocket sock = RFB_INVALID_SOCKET;
int one = 1;
#ifndef LIBVNCSERVER_IPv6
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (address) {
addr.sin_addr.s_addr = inet_addr(address);
} else {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("ListenAtTcpPort: socket\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(const char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPort: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
rfbClientErr("ListenAtTcpPort: bind\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
#else
int rv;
struct addrinfo hints, *servinfo, *p;
char port_str[8];
snprintf(port_str, 8, "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; /* fill in wildcard address if address == NULL */
if ((rv = getaddrinfo(address, port_str, &hints, &servinfo)) != 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in getaddrinfo: %s\n", gai_strerror(rv));
return RFB_INVALID_SOCKET;
}
/* loop through all the results and bind to the first we can */
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == RFB_INVALID_SOCKET) {
continue;
}
#ifdef IPV6_V6ONLY
/* we have separate IPv4 and IPv6 sockets since some OS's do not support dual binding */
if (p->ai_family == AF_INET6 && setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in setsockopt IPV6_V6ONLY: %s\n", strerror(errno));
rfbCloseSocket(sock);
freeaddrinfo(servinfo);
return RFB_INVALID_SOCKET;
}
#endif
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one)) < 0) {
rfbClientErr("ListenAtTcpPortAndAddress: error in setsockopt SO_REUSEADDR: %s\n", strerror(errno));
rfbCloseSocket(sock);
freeaddrinfo(servinfo);
return RFB_INVALID_SOCKET;
}
if (bind(sock, p->ai_addr, p->ai_addrlen) < 0) {
rfbCloseSocket(sock);
continue;
}
break;
}
if (p == NULL) {
rfbClientErr("ListenAtTcpPortAndAddress: error in bind: %s\n", strerror(errno));
return RFB_INVALID_SOCKET;
}
/* all done with this structure now */
freeaddrinfo(servinfo);
#endif
if (listen(sock, 5) < 0) {
rfbClientErr("ListenAtTcpPort: listen\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
/*
* AcceptTcpConnection accepts a TCP connection.
*/
rfbSocket
AcceptTcpConnection(rfbSocket listenSock)
{
rfbSocket sock;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int one = 1;
sock = accept(listenSock, (struct sockaddr *) &addr, &addrlen);
if (sock == RFB_INVALID_SOCKET) {
rfbClientErr("AcceptTcpConnection: accept\n");
return RFB_INVALID_SOCKET;
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
(char *)&one, sizeof(one)) < 0) {
rfbClientErr("AcceptTcpConnection: setsockopt\n");
rfbCloseSocket(sock);
return RFB_INVALID_SOCKET;
}
return sock;
}
/*
* SetNonBlocking sets a socket into non-blocking mode.
*/
rfbBool
SetNonBlocking(rfbSocket sock)
{
#ifdef WIN32
unsigned long block=1;
if(ioctlsocket(sock, FIONBIO, &block) == SOCKET_ERROR) {
errno=WSAGetLastError();
#else
int flags = fcntl(sock, F_GETFL);
if(flags < 0 || fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
#endif
rfbClientErr("Setting socket to non-blocking failed: %s\n",strerror(errno));
return FALSE;
}
return TRUE;
}
rfbBool SetBlocking(rfbSocket sock)
{
#ifdef WIN32
unsigned long block=0;
if(ioctlsocket(sock, FIONBIO, &block) == SOCKET_ERROR) {
errno=WSAGetLastError();
#else
int flags = fcntl(sock, F_GETFL);
if(flags < 0 || fcntl(sock, F_SETFL, flags & ~O_NONBLOCK) < 0) {
#endif
rfbClientErr("Setting socket to blocking failed: %s\n",strerror(errno));
return FALSE;
}
return TRUE;
}
/*
* SetDSCP sets a socket's IP QoS parameters aka Differentiated Services Code Point field
*/
rfbBool
SetDSCP(rfbSocket sock, int dscp)
{
#ifdef WIN32
rfbClientErr("Setting of QoS IP DSCP not implemented for Windows\n");
return TRUE;
#else
int level, cmd;
struct sockaddr addr;
socklen_t addrlen = sizeof(addr);
if(getsockname(sock, &addr, &addrlen) != 0) {
rfbClientErr("Setting socket QoS failed while getting socket address: %s\n",strerror(errno));
return FALSE;
}
switch(addr.sa_family)
{
#if defined LIBVNCSERVER_IPv6 && defined IPV6_TCLASS
case AF_INET6:
level = IPPROTO_IPV6;
cmd = IPV6_TCLASS;
break;
#endif
case AF_INET:
level = IPPROTO_IP;
cmd = IP_TOS;
break;
default:
rfbClientErr("Setting socket QoS failed: Not bound to IP address");
return FALSE;
}
if(setsockopt(sock, level, cmd, (void*)&dscp, sizeof(dscp)) != 0) {
rfbClientErr("Setting socket QoS failed: %s\n", strerror(errno));
return FALSE;
}
return TRUE;
#endif
}
/*
* StringToIPAddr - convert a host string to an IP address.
*/
rfbBool
StringToIPAddr(const char *str, unsigned int *addr)
{
struct hostent *hp;
if (strcmp(str,"") == 0) {
*addr = htonl(INADDR_LOOPBACK); /* local */
return TRUE;
}
*addr = inet_addr(str);
if (*addr != -1)
return TRUE;
hp = gethostbyname(str);
if (hp) {
*addr = *(unsigned int *)hp->h_addr;
return TRUE;
}
return FALSE;
}
/*
* Test if the other end of a socket is on the same machine.
*/
rfbBool
SameMachine(rfbSocket sock)
{
struct sockaddr_in peeraddr, myaddr;
socklen_t addrlen = sizeof(struct sockaddr_in);
getpeername(sock, (struct sockaddr *)&peeraddr, &addrlen);
getsockname(sock, (struct sockaddr *)&myaddr, &addrlen);
return (peeraddr.sin_addr.s_addr == myaddr.sin_addr.s_addr);
}
/*
* Print out the contents of a packet for debugging.
*/
void
PrintInHex(char *buf, int len)
{
int i, j;
char c, str[17];
str[16] = 0;
rfbClientLog("ReadExact: ");
for (i = 0; i < len; i++)
{
if ((i % 16 == 0) && (i != 0)) {
rfbClientLog(" ");
}
c = buf[i];
str[i % 16] = (((c > 31) && (c < 127)) ? c : '.');
rfbClientLog("%02x ",(unsigned char)c);
if ((i % 4) == 3)
rfbClientLog(" ");
if ((i % 16) == 15)
{
rfbClientLog("%s\n",str);
}
}
if ((i % 16) != 0)
{
for (j = i % 16; j < 16; j++)
{
rfbClientLog(" ");
if ((j % 4) == 3) rfbClientLog(" ");
}
str[i % 16] = 0;
rfbClientLog("%s\n",str);
}
fflush(stderr);
}
int WaitForMessage(rfbClient* client,unsigned int usecs)
{
fd_set fds;
struct timeval timeout;
int num;
if (client->serverPort==-1)
/* playing back vncrec file */
return 1;
timeout.tv_sec=(usecs/1000000);
timeout.tv_usec=(usecs%1000000);
FD_ZERO(&fds);
FD_SET(client->sock,&fds);
num=select(client->sock+1, &fds, NULL, NULL, &timeout);
if(num<0) {
#ifdef WIN32
errno=WSAGetLastError();
#endif
rfbClientLog("Waiting for message failed: %d (%s)\n",errno,strerror(errno));
}
return num;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_4059_0 |
crossvul-cpp_data_bad_5710_0 | /*
* $Id$
*
* Lookup contacts in usrloc
*
* Copyright (C) 2001-2003 FhG Fokus
*
* This file is part of opensips, a free SIP server.
*
* opensips 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
*
* opensips 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
*
* History:
* ---------
* 2003-03-12 added support for zombie state (nils)
*/
/*!
* \file
* \brief SIP registrar module - lookup contacts in usrloc
* \ingroup registrar
*/
#include <string.h>
#include "../../ut.h"
#include "../../dset.h"
#include "../../str.h"
#include "../../config.h"
#include "../../action.h"
#include "../../mod_fix.h"
#include "../../parser/parse_rr.h"
#include "../usrloc/usrloc.h"
#include "common.h"
#include "regtime.h"
#include "reg_mod.h"
#include "lookup.h"
#define GR_E_PART_SIZE 22
#define GR_A_PART_SIZE 14
#define allowed_method(_msg, _c, _f) \
( !((_f)®_LOOKUP_METHODFILTER_FLAG) || \
((_msg)->REQ_METHOD)&((_c)->methods) )
/*! \brief
* Lookup contact in the database and rewrite Request-URI
* \return: -1 : not found
* -2 : found but method not allowed
* -3 : error
*/
int lookup(struct sip_msg* _m, char* _t, char* _f, char* _s)
{
unsigned int flags;
urecord_t* r;
str aor, uri;
ucontact_t* ptr,*it;
int res;
int ret;
str path_dst;
str flags_s;
pv_value_t val;
int_str istr;
str sip_instance = {0,0},call_id = {0,0};
flags = 0;
if (_f && _f[0]!=0) {
if (fixup_get_svalue( _m, (gparam_p)_f, &flags_s)!=0) {
LM_ERR("invalid owner uri parameter");
return -1;
}
for( res=0 ; res< flags_s.len ; res++ ) {
switch (flags_s.s[res]) {
case 'm': flags |= REG_LOOKUP_METHODFILTER_FLAG; break;
case 'b': flags |= REG_LOOKUP_NOBRANCH_FLAG; break;
default: LM_WARN("unsuported flag %c \n",flags_s.s[res]);
}
}
}
if (_s) {
if (pv_get_spec_value( _m, (pv_spec_p)_s, &val)!=0) {
LM_ERR("failed to get PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("PV vals is not string\n");
return -1;
}
uri = val.rs;
} else {
if (_m->new_uri.s) uri = _m->new_uri;
else uri = _m->first_line.u.request.uri;
}
if (extract_aor(&uri, &aor,&sip_instance,&call_id) < 0) {
LM_ERR("failed to extract address of record\n");
return -3;
}
get_act_time();
ul.lock_udomain((udomain_t*)_t, &aor);
res = ul.get_urecord((udomain_t*)_t, &aor, &r);
if (res > 0) {
LM_DBG("'%.*s' Not found in usrloc\n", aor.len, ZSW(aor.s));
ul.unlock_udomain((udomain_t*)_t, &aor);
return -1;
}
ptr = r->contacts;
ret = -1;
/* look first for an un-expired and suported contact */
search_valid_contact:
while ( (ptr) &&
!(VALID_CONTACT(ptr,act_time) && (ret=-2) && allowed_method(_m,ptr,flags)))
ptr = ptr->next;
if (ptr==0) {
/* nothing found */
LM_DBG("nothing found !\n");
goto done;
}
if (sip_instance.len && sip_instance.s) {
LM_DBG("ruri has gruu in lookup\n");
/* uri has GRUU */
if (ptr->instance.len-2 != sip_instance.len ||
memcmp(ptr->instance.s+1,sip_instance.s,sip_instance.len)) {
LM_DBG("no match to sip instace - [%.*s] - [%.*s]\n",ptr->instance.len-2,ptr->instance.s+1,
sip_instance.len,sip_instance.s);
/* not the targeted instance, search some more */
ptr = ptr->next;
goto search_valid_contact;
}
LM_DBG("matched sip instace\n");
}
if (call_id.len && call_id.s) {
/* decide whether GRUU is expired or not
*
* first - match call-id */
if (ptr->callid.len != call_id.len ||
memcmp(ptr->callid.s,call_id.s,call_id.len)) {
LM_DBG("no match to call id - [%.*s] - [%.*s]\n",ptr->callid.len,ptr->callid.s,
call_id.len,call_id.s);
ptr = ptr->next;
goto search_valid_contact;
}
/* matched call-id, check if there are newer contacts with
* same sip instace bup newer last_modified */
it = ptr->next;
while ( it ) {
if (VALID_CONTACT(it,act_time)) {
if (it->instance.len-2 == sip_instance.len &&
memcmp(it->instance.s+1,sip_instance.s,sip_instance.len) == 0)
if (it->last_modified > ptr->last_modified) {
/* same instance id, but newer modified -> expired GRUU, no match at all */
break;
}
}
}
if (it != NULL) {
ret = -1;
goto done;
}
}
LM_DBG("found a complete match\n");
ret = 1;
if (ptr) {
LM_DBG("setting as ruri <%.*s>\n",ptr->c.len,ptr->c.s);
if (set_ruri(_m, &ptr->c) < 0) {
LM_ERR("unable to rewrite Request-URI\n");
ret = -3;
goto done;
}
/* If a Path is present, use first path-uri in favour of
* received-uri because in that case the last hop towards the uac
* has to handle NAT. - agranig */
if (ptr->path.s && ptr->path.len) {
if (get_path_dst_uri(&ptr->path, &path_dst) < 0) {
LM_ERR("failed to get dst_uri for Path\n");
ret = -3;
goto done;
}
if (set_path_vector(_m, &ptr->path) < 0) {
LM_ERR("failed to set path vector\n");
ret = -3;
goto done;
}
if (set_dst_uri(_m, &path_dst) < 0) {
LM_ERR("failed to set dst_uri of Path\n");
ret = -3;
goto done;
}
} else if (ptr->received.s && ptr->received.len) {
if (set_dst_uri(_m, &ptr->received) < 0) {
ret = -3;
goto done;
}
}
set_ruri_q(ptr->q);
setbflag( 0, ptr->cflags);
if (ptr->sock)
_m->force_send_socket = ptr->sock;
/* populate the 'attributes' avp */
if (attr_avp_name != -1) {
istr.s = ptr->attr;
if (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {
LM_ERR("Failed to populate attr avp!\n");
}
}
ptr = ptr->next;
}
/* Append branches if enabled */
/* If we got to this point and the URI had a ;gr parameter and it was matched
* to a contact. No point in branching */
if ( flags®_LOOKUP_NOBRANCH_FLAG || (sip_instance.len && sip_instance.s) ) goto done;
LM_DBG("looking for branches\n");
for( ; ptr ; ptr = ptr->next ) {
if (VALID_CONTACT(ptr, act_time) && allowed_method(_m,ptr,flags)) {
path_dst.len = 0;
if(ptr->path.s && ptr->path.len
&& get_path_dst_uri(&ptr->path, &path_dst) < 0) {
LM_ERR("failed to get dst_uri for Path\n");
continue;
}
/* The same as for the first contact applies for branches
* regarding path vs. received. */
LM_DBG("setting branch <%.*s>\n",ptr->c.len,ptr->c.s);
if (append_branch(_m,&ptr->c,path_dst.len?&path_dst:&ptr->received,
&ptr->path, ptr->q, ptr->cflags, ptr->sock) == -1) {
LM_ERR("failed to append a branch\n");
/* Also give a chance to the next branches*/
continue;
}
/* populate the 'attributes' avp */
if (attr_avp_name != -1) {
istr.s = ptr->attr;
if (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {
LM_ERR("Failed to populate attr avp!\n");
}
}
}
}
done:
ul.release_urecord(r);
ul.unlock_udomain((udomain_t*)_t, &aor);
return ret;
}
/*! \brief the is_registered() function
* Return true if the AOR in the Request-URI is registered,
* it is similar to lookup but registered neither rewrites
* the Request-URI nor appends branches
*/
int registered(struct sip_msg* _m, char* _t, char* _s, char *_c)
{
str uri, aor;
urecord_t* r;
ucontact_t* ptr;
pv_value_t val;
str callid;
int res;
/* get the AOR */
if (_s) {
if (pv_get_spec_value( _m, (pv_spec_p)_s, &val)!=0) {
LM_ERR("failed to getAOR PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("AOR PV vals is not string\n");
return -1;
}
uri = val.rs;
} else {
if (_m->first_line.type!=SIP_REQUEST) {
LM_ERR("no AOR and called for a reply!");
return -1;
}
if (_m->new_uri.s) uri = _m->new_uri;
else uri = _m->first_line.u.request.uri;
}
if (extract_aor(&uri, &aor,0,0) < 0) {
LM_ERR("failed to extract address of record\n");
return -1;
}
/* get the callid */
if (_c) {
if (pv_get_spec_value( _m, (pv_spec_p)_c, &val)!=0) {
LM_ERR("failed to get callid PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("callid PV vals is not string\n");
return -1;
}
callid = val.rs;
} else {
callid.s = NULL;
callid.len = 0;
}
ul.lock_udomain((udomain_t*)_t, &aor);
res = ul.get_urecord((udomain_t*)_t, &aor, &r);
if (res < 0) {
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_ERR("failed to query usrloc\n");
return -1;
}
if (res == 0) {
ptr = r->contacts;
while (ptr && !VALID_CONTACT(ptr, act_time)) {
ptr = ptr->next;
}
for( ; ptr ; ptr=ptr->next ) {
if (callid.len==0 || (callid.len==ptr->callid.len &&
memcmp(callid.s,ptr->callid.s,callid.len)==0 ) ) {
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_DBG("'%.*s' found in usrloc\n", aor.len, ZSW(aor.s));
return 1;
}
}
}
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_DBG("'%.*s' not found in usrloc\n", aor.len, ZSW(aor.s));
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_5710_0 |
crossvul-cpp_data_good_2585_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.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/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/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MaxTextExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p,
text[MaxTextExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("SPARSE-COLOR");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Sparse Color");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TEXT");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Text");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TXT");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->description=ConstantString("Text");
entry->magick=(IsImageFormatHandler *) IsTXT;
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
colorspace[MaxTextExtent],
tuple[MaxTextExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
/*
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,WriteBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MaxTextExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->matte != MagickFalse)
(void) ConcatenateMagickString(colorspace,"a",MaxTextExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MaxTextExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetMagickPixelPacket(image,&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);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelOpacity(p) == (Quantum) OpaqueOpacity)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g,",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p++;
continue;
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g: ",(double)
x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MaxTextExtent);
ConcatenateColorComponent(&pixel,RedChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,GreenChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,BlueChannel,compliance,tuple);
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,IndexChannel,compliance,tuple);
}
if (pixel.matte != MagickFalse)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,AlphaChannel,compliance,tuple);
}
(void) ConcatenateMagickString(tuple,")",MaxTextExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MaxTextExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p++;
}
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-835/c/good_2585_0 |
crossvul-cpp_data_good_587_0 | /* $Id: table.c,v 1.58 2010/08/09 11:59:19 htrb Exp $ */
/*
* HTML table
*/
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "fm.h"
#include "html.h"
#include "parsetagx.h"
#include "Str.h"
#include "myctype.h"
int symbol_width = 0;
int symbol_width0 = 0;
#define RULE_WIDTH symbol_width
#define RULE(mode,n) (((mode) == BORDER_THICK) ? ((n) + 16) : (n))
#define TK_VERTICALBAR(mode) RULE(mode,5)
#define BORDERWIDTH 2
#define BORDERHEIGHT 1
#define NOBORDERWIDTH 1
#define NOBORDERHEIGHT 0
#define HTT_X 1
#define HTT_Y 2
#define HTT_ALIGN 0x30
#define HTT_LEFT 0x00
#define HTT_CENTER 0x10
#define HTT_RIGHT 0x20
#define HTT_TRSET 0x40
#define HTT_VALIGN 0x700
#define HTT_TOP 0x100
#define HTT_MIDDLE 0x200
#define HTT_BOTTOM 0x400
#define HTT_VTRSET 0x800
#ifdef NOWRAP
#define HTT_NOWRAP 4
#endif /* NOWRAP */
#define TAG_IS(s,tag,len) (strncasecmp(s,tag,len)==0&&(s[len] == '>' || IS_SPACE((int)s[len])))
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif /* not max */
#ifndef min
#define min(a,b) ((a) > (b) ? (b) : (a))
#endif /* not min */
#ifndef abs
#define abs(a) ((a) >= 0. ? (a) : -(a))
#endif /* not abs */
#define set_prevchar(x,y,n) Strcopy_charp_n((x),(y),(n))
#define set_space_to_prevchar(x) Strcopy_charp_n((x)," ",1)
#ifdef MATRIX
#ifndef MESCHACH
#include "matrix.c"
#endif /* not MESCHACH */
#endif /* MATRIX */
#ifdef MATRIX
int correct_table_matrix(struct table *, int, int, int, double);
void set_table_matrix(struct table *, int);
#endif /* MATRIX */
#ifdef MATRIX
static double
weight(int x)
{
if (x < COLS)
return (double)x;
else
return COLS * (log((double)x / COLS) + 1.);
}
static double
weight2(int a)
{
return (double)a / COLS * 4 + 1.;
}
#define sigma_td(a) (0.5*weight2(a)) /* <td width=...> */
#define sigma_td_nw(a) (32*weight2(a)) /* <td ...> */
#define sigma_table(a) (0.25*weight2(a)) /* <table width=...> */
#define sigma_table_nw(a) (2*weight2(a)) /* <table...> */
#else /* not MATRIX */
#define LOG_MIN 1.0
static double
weight3(int x)
{
if (x < 0.1)
return 0.1;
if (x < LOG_MIN)
return (double)x;
else
return LOG_MIN * (log((double)x / LOG_MIN) + 1.);
}
#endif /* not MATRIX */
static int
bsearch_2short(short e1, short *ent1, short e2, short *ent2, int base,
short *indexarray, int nent)
{
int n = nent;
int k = 0;
int e = e1 * base + e2;
while (n > 0) {
int nn = n / 2;
int idx = indexarray[k + nn];
int ne = ent1[idx] * base + ent2[idx];
if (ne == e) {
k += nn;
break;
}
else if (ne < e) {
n -= nn + 1;
k += nn + 1;
}
else {
n = nn;
}
}
return k;
}
static int
bsearch_double(double e, double *ent, short *indexarray, int nent)
{
int n = nent;
int k = 0;
while (n > 0) {
int nn = n / 2;
int idx = indexarray[k + nn];
double ne = ent[idx];
if (ne == e) {
k += nn;
break;
}
else if (ne > e) {
n -= nn + 1;
k += nn + 1;
}
else {
n = nn;
}
}
return k;
}
static int
ceil_at_intervals(int x, int step)
{
int mo = x % step;
if (mo > 0)
x += step - mo;
else if (mo < 0)
x -= mo;
return x;
}
static int
floor_at_intervals(int x, int step)
{
int mo = x % step;
if (mo > 0)
x -= mo;
else if (mo < 0)
x += step - mo;
return x;
}
#define round(x) ((int)floor((x)+0.5))
#ifndef MATRIX
static void
dv2sv(double *dv, short *iv, int size)
{
int i, k, iw;
short *indexarray;
double *edv;
double w = 0., x;
indexarray = NewAtom_N(short, size);
edv = NewAtom_N(double, size);
for (i = 0; i < size; i++) {
iv[i] = (short) ceil(dv[i]);
edv[i] = (double)iv[i] - dv[i];
}
w = 0.;
for (k = 0; k < size; k++) {
x = edv[k];
w += x;
i = bsearch_double(x, edv, indexarray, k);
if (k > i) {
int ii;
for (ii = k; ii > i; ii--)
indexarray[ii] = indexarray[ii - 1];
}
indexarray[i] = k;
}
iw = min((int)(w + 0.5), size);
if (iw <= 1)
return;
x = edv[(int)indexarray[iw - 1]];
for (i = 0; i < size; i++) {
k = indexarray[i];
if (i >= iw && abs(edv[k] - x) > 1e-6)
break;
iv[k]--;
}
}
#endif
static int
table_colspan(struct table *t, int row, int col)
{
int i;
for (i = col + 1; i <= t->maxcol && (t->tabattr[row][i] & HTT_X); i++) ;
return i - col;
}
static int
table_rowspan(struct table *t, int row, int col)
{
int i;
if (!t->tabattr[row])
return 0;
for (i = row + 1; i <= t->maxrow && t->tabattr[i] &&
(t->tabattr[i][col] & HTT_Y); i++) ;
return i - row;
}
static int
minimum_cellspacing(int border_mode)
{
switch (border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
return RULE_WIDTH;
case BORDER_NONE:
return 1;
default:
/* not reached */
return 0;
}
}
static int
table_border_width(struct table *t)
{
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
return t->maxcol * t->cellspacing + 2 * (RULE_WIDTH + t->cellpadding);
case BORDER_NOWIN:
case BORDER_NONE:
return t->maxcol * t->cellspacing;
default:
/* not reached */
return 0;
}
}
struct table *
newTable()
{
struct table *t;
int i, j;
t = New(struct table);
t->max_rowsize = MAXROW;
t->tabdata = New_N(GeneralList **, MAXROW);
t->tabattr = New_N(table_attr *, MAXROW);
t->tabheight = NewAtom_N(short, MAXROW);
#ifdef ID_EXT
t->tabidvalue = New_N(Str *, MAXROW);
t->tridvalue = New_N(Str, MAXROW);
#endif /* ID_EXT */
for (i = 0; i < MAXROW; i++) {
t->tabdata[i] = NULL;
t->tabattr[i] = 0;
t->tabheight[i] = 0;
#ifdef ID_EXT
t->tabidvalue[i] = NULL;
t->tridvalue[i] = NULL;
#endif /* ID_EXT */
}
for (j = 0; j < MAXCOL; j++) {
t->tabwidth[j] = 0;
t->minimum_width[j] = 0;
t->fixed_width[j] = 0;
}
t->cell.maxcell = -1;
t->cell.icell = -1;
t->ntable = 0;
t->tables_size = 0;
t->tables = NULL;
#ifdef MATRIX
t->matrix = NULL;
t->vector = NULL;
#endif /* MATRIX */
#if 0
t->tabcontentssize = 0;
t->indent = 0;
t->linfo.prev_ctype = PC_ASCII;
t->linfo.prev_spaces = -1;
#endif
t->linfo.prevchar = Strnew_size(8);
set_prevchar(t->linfo.prevchar, "", 0);
t->trattr = 0;
t->caption = Strnew();
t->suspended_data = NULL;
#ifdef ID_EXT
t->id = NULL;
#endif
return t;
}
static void
check_row(struct table *t, int row)
{
int i, r;
GeneralList ***tabdata;
table_attr **tabattr;
short *tabheight;
#ifdef ID_EXT
Str **tabidvalue;
Str *tridvalue;
#endif /* ID_EXT */
if (row >= t->max_rowsize) {
r = max(t->max_rowsize * 2, row + 1);
tabdata = New_N(GeneralList **, r);
tabattr = New_N(table_attr *, r);
tabheight = NewAtom_N(short, r);
#ifdef ID_EXT
tabidvalue = New_N(Str *, r);
tridvalue = New_N(Str, r);
#endif /* ID_EXT */
for (i = 0; i < t->max_rowsize; i++) {
tabdata[i] = t->tabdata[i];
tabattr[i] = t->tabattr[i];
tabheight[i] = t->tabheight[i];
#ifdef ID_EXT
tabidvalue[i] = t->tabidvalue[i];
tridvalue[i] = t->tridvalue[i];
#endif /* ID_EXT */
}
for (; i < r; i++) {
tabdata[i] = NULL;
tabattr[i] = NULL;
tabheight[i] = 0;
#ifdef ID_EXT
tabidvalue[i] = NULL;
tridvalue[i] = NULL;
#endif /* ID_EXT */
}
t->tabdata = tabdata;
t->tabattr = tabattr;
t->tabheight = tabheight;
#ifdef ID_EXT
t->tabidvalue = tabidvalue;
t->tridvalue = tridvalue;
#endif /* ID_EXT */
t->max_rowsize = r;
}
if (t->tabdata[row] == NULL) {
t->tabdata[row] = New_N(GeneralList *, MAXCOL);
t->tabattr[row] = NewAtom_N(table_attr, MAXCOL);
#ifdef ID_EXT
t->tabidvalue[row] = New_N(Str, MAXCOL);
#endif /* ID_EXT */
for (i = 0; i < MAXCOL; i++) {
t->tabdata[row][i] = NULL;
t->tabattr[row][i] = 0;
#ifdef ID_EXT
t->tabidvalue[row][i] = NULL;
#endif /* ID_EXT */
}
}
}
void
pushdata(struct table *t, int row, int col, char *data)
{
check_row(t, row);
if (t->tabdata[row][col] == NULL)
t->tabdata[row][col] = newGeneralList();
pushText(t->tabdata[row][col], data ? data : "");
}
void
suspend_or_pushdata(struct table *tbl, char *line)
{
if (tbl->flag & TBL_IN_COL)
pushdata(tbl, tbl->row, tbl->col, line);
else {
if (!tbl->suspended_data)
tbl->suspended_data = newTextList();
pushText(tbl->suspended_data, line ? line : "");
}
}
#ifdef USE_M17N
#define PUSH_TAG(str,n) Strcat_charp_n(tagbuf, str, n)
#else
#define PUSH_TAG(str,n) Strcat_char(tagbuf, *str)
#endif
int visible_length_offset = 0;
int
visible_length(char *str)
{
int len = 0, n, max_len = 0;
int status = R_ST_NORMAL;
int prev_status = status;
Str tagbuf = Strnew();
char *t, *r2;
int amp_len = 0;
while (*str) {
prev_status = status;
if (next_status(*str, &status)) {
#ifdef USE_M17N
len += get_mcwidth(str);
n = get_mclen(str);
}
else {
n = 1;
}
#else
len++;
}
#endif
if (status == R_ST_TAG0) {
Strclear(tagbuf);
PUSH_TAG(str, n);
}
else if (status == R_ST_TAG || status == R_ST_DQUOTE
|| status == R_ST_QUOTE || status == R_ST_EQL
|| status == R_ST_VALUE) {
PUSH_TAG(str, n);
}
else if (status == R_ST_AMP) {
if (prev_status == R_ST_NORMAL) {
Strclear(tagbuf);
len--;
amp_len = 0;
}
else {
PUSH_TAG(str, n);
amp_len++;
}
}
else if (status == R_ST_NORMAL && prev_status == R_ST_AMP) {
PUSH_TAG(str, n);
r2 = tagbuf->ptr;
t = getescapecmd(&r2);
if (!*r2 && (*t == '\r' || *t == '\n')) {
if (len > max_len)
max_len = len;
len = 0;
}
else
len += get_strwidth(t) + get_strwidth(r2);
}
else if (status == R_ST_NORMAL && ST_IS_REAL_TAG(prev_status)) {
;
}
else if (*str == '\t') {
len--;
do {
len++;
} while ((visible_length_offset + len) % Tabstop != 0);
}
else if (*str == '\r' || *str == '\n') {
len--;
if (len > max_len)
max_len = len;
len = 0;
}
#ifdef USE_M17N
str += n;
#else
str++;
#endif
}
if (status == R_ST_AMP) {
r2 = tagbuf->ptr;
t = getescapecmd(&r2);
if (*t != '\r' && *t != '\n')
len += get_strwidth(t) + get_strwidth(r2);
}
return len > max_len ? len : max_len;
}
int
visible_length_plain(char *str)
{
int len = 0, max_len = 0;
while (*str) {
if (*str == '\t') {
do {
len++;
} while ((visible_length_offset + len) % Tabstop != 0);
str++;
}
else if (*str == '\r' || *str == '\n') {
if (len > max_len)
max_len = len;
len = 0;
str++;
}
else {
#ifdef USE_M17N
len += get_mcwidth(str);
str += get_mclen(str);
#else
len++;
str++;
#endif
}
}
return len > max_len ? len : max_len;
}
static int
maximum_visible_length(char *str, int offset)
{
visible_length_offset = offset;
return visible_length(str);
}
static int
maximum_visible_length_plain(char *str, int offset)
{
visible_length_offset = offset;
return visible_length_plain(str);
}
void
align(TextLine *lbuf, int width, int mode)
{
int i, l, l1, l2;
Str buf, line = lbuf->line;
if (line->length == 0) {
for (i = 0; i < width; i++)
Strcat_char(line, ' ');
lbuf->pos = width;
return;
}
buf = Strnew();
l = width - lbuf->pos;
switch (mode) {
case ALIGN_CENTER:
l1 = l / 2;
l2 = l - l1;
for (i = 0; i < l1; i++)
Strcat_char(buf, ' ');
Strcat(buf, line);
for (i = 0; i < l2; i++)
Strcat_char(buf, ' ');
break;
case ALIGN_LEFT:
Strcat(buf, line);
for (i = 0; i < l; i++)
Strcat_char(buf, ' ');
break;
case ALIGN_RIGHT:
for (i = 0; i < l; i++)
Strcat_char(buf, ' ');
Strcat(buf, line);
break;
default:
return;
}
lbuf->line = buf;
if (lbuf->pos < width)
lbuf->pos = width;
}
void
print_item(struct table *t, int row, int col, int width, Str buf)
{
int alignment;
TextLine *lbuf;
if (t->tabdata[row])
lbuf = popTextLine(t->tabdata[row][col]);
else
lbuf = NULL;
if (lbuf != NULL) {
check_row(t, row);
alignment = ALIGN_CENTER;
if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_LEFT)
alignment = ALIGN_LEFT;
else if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_RIGHT)
alignment = ALIGN_RIGHT;
else if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_CENTER)
alignment = ALIGN_CENTER;
align(lbuf, width, alignment);
Strcat(buf, lbuf->line);
}
else {
lbuf = newTextLine(NULL, 0);
align(lbuf, width, ALIGN_CENTER);
Strcat(buf, lbuf->line);
}
}
#define T_TOP 0
#define T_MIDDLE 1
#define T_BOTTOM 2
void
print_sep(struct table *t, int row, int type, int maxcol, Str buf)
{
int forbid;
int rule_mode;
int i, k, l, m;
if (row >= 0)
check_row(t, row);
check_row(t, row + 1);
if ((type == T_TOP || type == T_BOTTOM) && t->border_mode == BORDER_THICK) {
rule_mode = BORDER_THICK;
}
else {
rule_mode = BORDER_THIN;
}
forbid = 1;
if (type == T_TOP)
forbid |= 2;
else if (type == T_BOTTOM)
forbid |= 8;
else if (t->tabattr[row + 1][0] & HTT_Y) {
forbid |= 4;
}
if (t->border_mode != BORDER_NOWIN) {
push_symbol(buf, RULE(t->border_mode, forbid), symbol_width, 1);
}
for (i = 0; i <= maxcol; i++) {
forbid = 10;
if (type != T_BOTTOM && (t->tabattr[row + 1][i] & HTT_Y)) {
if (t->tabattr[row + 1][i] & HTT_X) {
goto do_last_sep;
}
else {
for (k = row;
k >= 0 && t->tabattr[k] && (t->tabattr[k][i] & HTT_Y);
k--) ;
m = t->tabwidth[i] + 2 * t->cellpadding;
for (l = i + 1; l <= t->maxcol && (t->tabattr[row][l] & HTT_X);
l++)
m += t->tabwidth[l] + t->cellspacing;
print_item(t, k, i, m, buf);
}
}
else {
int w = t->tabwidth[i] + 2 * t->cellpadding;
if (RULE_WIDTH == 2)
w = (w + 1) / RULE_WIDTH;
push_symbol(buf, RULE(rule_mode, forbid), symbol_width, w);
}
do_last_sep:
if (i < maxcol) {
forbid = 0;
if (type == T_TOP)
forbid |= 2;
else if (t->tabattr[row][i + 1] & HTT_X) {
forbid |= 2;
}
if (type == T_BOTTOM)
forbid |= 8;
else {
if (t->tabattr[row + 1][i + 1] & HTT_X) {
forbid |= 8;
}
if (t->tabattr[row + 1][i + 1] & HTT_Y) {
forbid |= 4;
}
if (t->tabattr[row + 1][i] & HTT_Y) {
forbid |= 1;
}
}
if (forbid != 15) /* forbid==15 means 'no rule at all' */
push_symbol(buf, RULE(rule_mode, forbid), symbol_width, 1);
}
}
forbid = 4;
if (type == T_TOP)
forbid |= 2;
if (type == T_BOTTOM)
forbid |= 8;
if (t->tabattr[row + 1][maxcol] & HTT_Y) {
forbid |= 1;
}
if (t->border_mode != BORDER_NOWIN)
push_symbol(buf, RULE(t->border_mode, forbid), symbol_width, 1);
}
static int
get_spec_cell_width(struct table *tbl, int row, int col)
{
int i, w;
w = tbl->tabwidth[col];
for (i = col + 1; i <= tbl->maxcol; i++) {
check_row(tbl, row);
if (tbl->tabattr[row][i] & HTT_X)
w += tbl->tabwidth[i] + tbl->cellspacing;
else
break;
}
return w;
}
void
do_refill(struct table *tbl, int row, int col, int maxlimit)
{
TextList *orgdata;
TextListItem *l;
struct readbuffer obuf;
struct html_feed_environ h_env;
struct environment envs[MAX_ENV_LEVEL];
int colspan, icell;
if (tbl->tabdata[row] == NULL || tbl->tabdata[row][col] == NULL)
return;
orgdata = (TextList *)tbl->tabdata[row][col];
tbl->tabdata[row][col] = newGeneralList();
init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL,
(TextLineList *)tbl->tabdata[row][col],
get_spec_cell_width(tbl, row, col), 0);
obuf.flag |= RB_INTABLE;
if (h_env.limit > maxlimit)
h_env.limit = maxlimit;
if (tbl->border_mode != BORDER_NONE && tbl->vcellpadding > 0)
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
for (l = orgdata->first; l != NULL; l = l->next) {
if (TAG_IS(l->ptr, "<table_alt", 10)) {
int id = -1;
char *p = l->ptr;
struct parsed_tag *tag;
if ((tag = parse_tag(&p, TRUE)) != NULL)
parsedtag_get_value(tag, ATTR_TID, &id);
if (id >= 0 && id < tbl->ntable && tbl->tables[id].ptr) {
int alignment;
TextLineListItem *ti;
struct table *t = tbl->tables[id].ptr;
int limit = tbl->tables[id].indent + t->total_width;
tbl->tables[id].ptr = NULL;
save_fonteffect(&h_env, h_env.obuf);
flushline(&h_env, &obuf, 0, 2, h_env.limit);
if (t->vspace > 0 && !(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
if (RB_GET_ALIGN(h_env.obuf) == RB_CENTER)
alignment = ALIGN_CENTER;
else if (RB_GET_ALIGN(h_env.obuf) == RB_RIGHT)
alignment = ALIGN_RIGHT;
else
alignment = ALIGN_LEFT;
if (alignment != ALIGN_LEFT) {
for (ti = tbl->tables[id].buf->first;
ti != NULL; ti = ti->next)
align(ti->ptr, h_env.limit, alignment);
}
appendTextLineList(h_env.buf, tbl->tables[id].buf);
if (h_env.maxlimit < limit)
h_env.maxlimit = limit;
restore_fonteffect(&h_env, h_env.obuf);
obuf.flag &= ~RB_IGNORE_P;
h_env.blank_lines = 0;
if (t->vspace > 0) {
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
obuf.flag |= RB_IGNORE_P;
}
}
}
else
HTMLlineproc1(l->ptr, &h_env);
}
if (obuf.status != R_ST_NORMAL) {
obuf.status = R_ST_EOL;
HTMLlineproc1("\n", &h_env);
}
completeHTMLstream(&h_env, &obuf);
flushline(&h_env, &obuf, 0, 2, h_env.limit);
if (tbl->border_mode == BORDER_NONE) {
int rowspan = table_rowspan(tbl, row, col);
if (row + rowspan <= tbl->maxrow) {
if (tbl->vcellpadding > 0 && !(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
}
else {
if (tbl->vspace > 0)
purgeline(&h_env);
}
}
else {
if (tbl->vcellpadding > 0) {
if (!(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
}
else
purgeline(&h_env);
}
if ((colspan = table_colspan(tbl, row, col)) > 1) {
struct table_cell *cell = &tbl->cell;
int k;
k = bsearch_2short(colspan, cell->colspan, col, cell->col, MAXCOL,
cell->index, cell->maxcell + 1);
icell = cell->index[k];
if (cell->minimum_width[icell] < h_env.maxlimit)
cell->minimum_width[icell] = h_env.maxlimit;
}
else {
if (tbl->minimum_width[col] < h_env.maxlimit)
tbl->minimum_width[col] = h_env.maxlimit;
}
}
static int
table_rule_width(struct table *t)
{
if (t->border_mode == BORDER_NONE)
return 1;
return RULE_WIDTH;
}
static void
check_cell_width(short *tabwidth, short *cellwidth,
short *col, short *colspan, short maxcell,
short *indexarray, int space, int dir)
{
int i, j, k, bcol, ecol;
int swidth, width;
for (k = 0; k <= maxcell; k++) {
j = indexarray[k];
if (cellwidth[j] <= 0)
continue;
bcol = col[j];
ecol = bcol + colspan[j];
swidth = 0;
for (i = bcol; i < ecol; i++)
swidth += tabwidth[i];
width = cellwidth[j] - (colspan[j] - 1) * space;
if (width > swidth) {
int w = (width - swidth) / colspan[j];
int r = (width - swidth) % colspan[j];
for (i = bcol; i < ecol; i++)
tabwidth[i] += w;
/* dir {0: horizontal, 1: vertical} */
if (dir == 1 && r > 0)
r = colspan[j];
for (i = 1; i <= r; i++)
tabwidth[ecol - i]++;
}
}
}
void
check_minimum_width(struct table *t, short *tabwidth)
{
int i;
struct table_cell *cell = &t->cell;
for (i = 0; i <= t->maxcol; i++) {
if (tabwidth[i] < t->minimum_width[i])
tabwidth[i] = t->minimum_width[i];
}
check_cell_width(tabwidth, cell->minimum_width, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
void
check_maximum_width(struct table *t)
{
struct table_cell *cell = &t->cell;
#ifdef MATRIX
int i, j, bcol, ecol;
int swidth, width;
cell->necell = 0;
for (j = 0; j <= cell->maxcell; j++) {
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
swidth = 0;
for (i = bcol; i < ecol; i++)
swidth += t->tabwidth[i];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
if (width > swidth) {
cell->eindex[cell->necell] = j;
cell->necell++;
}
}
#else /* not MATRIX */
check_cell_width(t->tabwidth, cell->width, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
check_minimum_width(t, t->tabwidth);
#endif /* not MATRIX */
}
#ifdef MATRIX
static void
set_integered_width(struct table *t, double *dwidth, short *iwidth)
{
int i, j, k, n, bcol, ecol, step;
short *indexarray;
char *fixed;
double *mod;
double sum = 0., x = 0.;
struct table_cell *cell = &t->cell;
int rulewidth = table_rule_width(t);
indexarray = NewAtom_N(short, t->maxcol + 1);
mod = NewAtom_N(double, t->maxcol + 1);
for (i = 0; i <= t->maxcol; i++) {
iwidth[i] = ceil_at_intervals(ceil(dwidth[i]), rulewidth);
mod[i] = (double)iwidth[i] - dwidth[i];
}
sum = 0.;
for (k = 0; k <= t->maxcol; k++) {
x = mod[k];
sum += x;
i = bsearch_double(x, mod, indexarray, k);
if (k > i) {
int ii;
for (ii = k; ii > i; ii--)
indexarray[ii] = indexarray[ii - 1];
}
indexarray[i] = k;
}
fixed = NewAtom_N(char, t->maxcol + 1);
bzero(fixed, t->maxcol + 1);
for (step = 0; step < 2; step++) {
for (i = 0; i <= t->maxcol; i += n) {
int nn;
short *idx;
double nsum;
if (sum < 0.5)
return;
for (n = 0; i + n <= t->maxcol; n++) {
int ii = indexarray[i + n];
if (n == 0)
x = mod[ii];
else if (fabs(mod[ii] - x) > 1e-6)
break;
}
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] < 2 &&
iwidth[ii] - rulewidth < t->minimum_width[ii])
fixed[ii] = 2;
if (fixed[ii] < 1 &&
iwidth[ii] - rulewidth < t->tabwidth[ii] &&
(double)rulewidth - mod[ii] > 0.5)
fixed[ii] = 1;
}
idx = NewAtom_N(short, n);
for (k = 0; k < cell->maxcell; k++) {
int kk, w, width, m;
j = cell->index[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
m = 0;
for (kk = 0; kk < n; kk++) {
int ii = indexarray[i + kk];
if (ii >= bcol && ii < ecol) {
idx[m] = ii;
m++;
}
}
if (m == 0)
continue;
width = (cell->colspan[j] - 1) * t->cellspacing;
for (kk = bcol; kk < ecol; kk++)
width += iwidth[kk];
w = 0;
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 2)
w += rulewidth;
}
if (width - w < cell->minimum_width[j]) {
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 2)
fixed[(int)idx[kk]] = 2;
}
}
w = 0;
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 1 &&
(double)rulewidth - mod[(int)idx[kk]] > 0.5)
w += rulewidth;
}
if (width - w < cell->width[j]) {
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 1 &&
(double)rulewidth - mod[(int)idx[kk]] > 0.5)
fixed[(int)idx[kk]] = 1;
}
}
}
nn = 0;
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] <= step)
nn++;
}
nsum = sum - (double)(nn * rulewidth);
if (nsum < 0. && fabs(sum) <= fabs(nsum))
return;
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] <= step) {
iwidth[ii] -= rulewidth;
fixed[ii] = 3;
}
}
sum = nsum;
}
}
}
static double
correlation_coefficient(double sxx, double syy, double sxy)
{
double coe, tmp;
tmp = sxx * syy;
if (tmp < Tiny)
tmp = Tiny;
coe = sxy / sqrt(tmp);
if (coe > 1.)
return 1.;
if (coe < -1.)
return -1.;
return coe;
}
static double
correlation_coefficient2(double sxx, double syy, double sxy)
{
double coe, tmp;
tmp = (syy + sxx - 2 * sxy) * sxx;
if (tmp < Tiny)
tmp = Tiny;
coe = (sxx - sxy) / sqrt(tmp);
if (coe > 1.)
return 1.;
if (coe < -1.)
return -1.;
return coe;
}
static double
recalc_width(double old, double swidth, int cwidth,
double sxx, double syy, double sxy, int is_inclusive)
{
double delta = swidth - (double)cwidth;
double rat = sxy / sxx,
coe = correlation_coefficient(sxx, syy, sxy), w, ww;
if (old < 0.)
old = 0.;
if (fabs(coe) < 1e-5)
return old;
w = rat * old;
ww = delta;
if (w > 0.) {
double wmin = 5e-3 * sqrt(syy * (1. - coe * coe));
if (swidth < 0.2 && cwidth > 0 && is_inclusive) {
double coe1 = correlation_coefficient2(sxx, syy, sxy);
if (coe > 0.9 || coe1 > 0.9)
return 0.;
}
if (wmin > 0.05)
wmin = 0.05;
if (ww < 0.)
ww = 0.;
ww += wmin;
}
else {
double wmin = 5e-3 * sqrt(syy) * fabs(coe);
if (rat > -0.001)
return old;
if (wmin > 0.01)
wmin = 0.01;
if (ww > 0.)
ww = 0.;
ww -= wmin;
}
if (w > ww)
return ww / rat;
return old;
}
static int
check_compressible_cell(struct table *t, MAT * minv,
double *newwidth, double *swidth, short *cwidth,
double totalwidth, double *Sxx,
int icol, int icell, double sxx, int corr)
{
struct table_cell *cell = &t->cell;
int i, j, k, m, bcol, ecol, span;
double delta, owidth;
double dmax, dmin, sxy;
int rulewidth = table_rule_width(t);
if (sxx < 10.)
return corr;
if (icol >= 0) {
owidth = newwidth[icol];
delta = newwidth[icol] - (double)t->tabwidth[icol];
bcol = icol;
ecol = bcol + 1;
}
else if (icell >= 0) {
owidth = swidth[icell];
delta = swidth[icell] - (double)cwidth[icell];
bcol = cell->col[icell];
ecol = bcol + cell->colspan[icell];
}
else {
owidth = totalwidth;
delta = totalwidth;
bcol = 0;
ecol = t->maxcol + 1;
}
dmin = delta;
dmax = -1.;
for (k = 0; k <= cell->maxcell; k++) {
int bcol1, ecol1;
int is_inclusive = 0;
if (dmin <= 0.)
goto _end;
j = cell->index[k];
if (j == icell)
continue;
bcol1 = cell->col[j];
ecol1 = bcol1 + cell->colspan[j];
sxy = 0.;
for (m = bcol1; m < ecol1; m++) {
for (i = bcol; i < ecol; i++)
sxy += m_entry(minv, i, m);
}
if (bcol1 >= bcol && ecol1 <= ecol) {
is_inclusive = 1;
}
if (sxy > 0.)
dmin = recalc_width(dmin, swidth[j], cwidth[j],
sxx, Sxx[j], sxy, is_inclusive);
else
dmax = recalc_width(dmax, swidth[j], cwidth[j],
sxx, Sxx[j], sxy, is_inclusive);
}
for (m = 0; m <= t->maxcol; m++) {
int is_inclusive = 0;
if (dmin <= 0.)
goto _end;
if (m == icol)
continue;
sxy = 0.;
for (i = bcol; i < ecol; i++)
sxy += m_entry(minv, i, m);
if (m >= bcol && m < ecol) {
is_inclusive = 1;
}
if (sxy > 0.)
dmin = recalc_width(dmin, newwidth[m], t->tabwidth[m],
sxx, m_entry(minv, m, m), sxy, is_inclusive);
else
dmax = recalc_width(dmax, newwidth[m], t->tabwidth[m],
sxx, m_entry(minv, m, m), sxy, is_inclusive);
}
_end:
if (dmax > 0. && dmin > dmax)
dmin = dmax;
span = ecol - bcol;
if ((span == t->maxcol + 1 && dmin >= 0.) ||
(span != t->maxcol + 1 && dmin > rulewidth * 0.5)) {
int nwidth = ceil_at_intervals(round(owidth - dmin), rulewidth);
correct_table_matrix(t, bcol, ecol - bcol, nwidth, 1.);
corr++;
}
return corr;
}
#define MAX_ITERATION 10
int
check_table_width(struct table *t, double *newwidth, MAT * minv, int itr)
{
int i, j, k, m, bcol, ecol;
int corr = 0;
struct table_cell *cell = &t->cell;
#ifdef __GNUC__
short orgwidth[t->maxcol + 1], corwidth[t->maxcol + 1];
short cwidth[cell->maxcell + 1];
double swidth[cell->maxcell + 1];
#else /* __GNUC__ */
short orgwidth[MAXCOL], corwidth[MAXCOL];
short cwidth[MAXCELL];
double swidth[MAXCELL];
#endif /* __GNUC__ */
double twidth, sxy, *Sxx, stotal;
twidth = 0.;
stotal = 0.;
for (i = 0; i <= t->maxcol; i++) {
twidth += newwidth[i];
stotal += m_entry(minv, i, i);
for (m = 0; m < i; m++) {
stotal += 2 * m_entry(minv, i, m);
}
}
Sxx = NewAtom_N(double, cell->maxcell + 1);
for (k = 0; k <= cell->maxcell; k++) {
j = cell->index[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
swidth[j] = 0.;
for (i = bcol; i < ecol; i++)
swidth[j] += newwidth[i];
cwidth[j] = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
Sxx[j] = 0.;
for (i = bcol; i < ecol; i++) {
Sxx[j] += m_entry(minv, i, i);
for (m = bcol; m <= ecol; m++) {
if (m < i)
Sxx[j] += 2 * m_entry(minv, i, m);
}
}
}
/* compress table */
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx, -1, -1, stotal, corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
/* compress multicolumn cell */
for (k = cell->maxcell; k >= 0; k--) {
j = cell->index[k];
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx,
-1, j, Sxx[j], corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
}
/* compress single column cell */
for (i = 0; i <= t->maxcol; i++) {
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx,
i, -1, m_entry(minv, i, i), corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
}
for (i = 0; i <= t->maxcol; i++)
corwidth[i] = orgwidth[i] = round(newwidth[i]);
check_minimum_width(t, corwidth);
for (i = 0; i <= t->maxcol; i++) {
double sx = sqrt(m_entry(minv, i, i));
if (sx < 0.1)
continue;
if (orgwidth[i] < t->minimum_width[i] &&
corwidth[i] == t->minimum_width[i]) {
double w = (sx > 0.5) ? 0.5 : sx * 0.2;
sxy = 0.;
for (m = 0; m <= t->maxcol; m++) {
if (m == i)
continue;
sxy += m_entry(minv, i, m);
}
if (sxy <= 0.) {
correct_table_matrix(t, i, 1, t->minimum_width[i], w);
corr++;
}
}
}
for (k = 0; k <= cell->maxcell; k++) {
int nwidth = 0, mwidth;
double sx;
j = cell->index[k];
sx = sqrt(Sxx[j]);
if (sx < 0.1)
continue;
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
for (i = bcol; i < ecol; i++)
nwidth += corwidth[i];
mwidth =
cell->minimum_width[j] - (cell->colspan[j] - 1) * t->cellspacing;
if (mwidth > swidth[j] && mwidth == nwidth) {
double w = (sx > 0.5) ? 0.5 : sx * 0.2;
sxy = 0.;
for (i = bcol; i < ecol; i++) {
for (m = 0; m <= t->maxcol; m++) {
if (m >= bcol && m < ecol)
continue;
sxy += m_entry(minv, i, m);
}
}
if (sxy <= 0.) {
correct_table_matrix(t, bcol, cell->colspan[j], mwidth, w);
corr++;
}
}
}
if (itr >= MAX_ITERATION)
return 0;
else
return corr;
}
#else /* not MATRIX */
void
set_table_width(struct table *t, short *newwidth, int maxwidth)
{
int i, j, k, bcol, ecol;
struct table_cell *cell = &t->cell;
char *fixed;
int swidth, fwidth, width, nvar;
double s;
double *dwidth;
int try_again;
fixed = NewAtom_N(char, t->maxcol + 1);
bzero(fixed, t->maxcol + 1);
dwidth = NewAtom_N(double, t->maxcol + 1);
for (i = 0; i <= t->maxcol; i++) {
dwidth[i] = 0.0;
if (t->fixed_width[i] < 0) {
t->fixed_width[i] = -t->fixed_width[i] * maxwidth / 100;
}
if (t->fixed_width[i] > 0) {
newwidth[i] = t->fixed_width[i];
fixed[i] = 1;
}
else
newwidth[i] = 0;
if (newwidth[i] < t->minimum_width[i])
newwidth[i] = t->minimum_width[i];
}
for (k = 0; k <= cell->maxcell; k++) {
j = cell->indexarray[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
if (cell->fixed_width[j] < 0)
cell->fixed_width[j] = -cell->fixed_width[j] * maxwidth / 100;
swidth = 0;
fwidth = 0;
nvar = 0;
for (i = bcol; i < ecol; i++) {
if (fixed[i]) {
fwidth += newwidth[i];
}
else {
swidth += newwidth[i];
nvar++;
}
}
width = max(cell->fixed_width[j], cell->minimum_width[j])
- (cell->colspan[j] - 1) * t->cellspacing;
if (nvar > 0 && width > fwidth + swidth) {
s = 0.;
for (i = bcol; i < ecol; i++) {
if (!fixed[i])
s += weight3(t->tabwidth[i]);
}
for (i = bcol; i < ecol; i++) {
if (!fixed[i])
dwidth[i] = (width - fwidth) * weight3(t->tabwidth[i]) / s;
else
dwidth[i] = (double)newwidth[i];
}
dv2sv(dwidth, newwidth, cell->colspan[j]);
if (cell->fixed_width[j] > 0) {
for (i = bcol; i < ecol; i++)
fixed[i] = 1;
}
}
}
do {
nvar = 0;
swidth = 0;
fwidth = 0;
for (i = 0; i <= t->maxcol; i++) {
if (fixed[i]) {
fwidth += newwidth[i];
}
else {
swidth += newwidth[i];
nvar++;
}
}
width = maxwidth - t->maxcol * t->cellspacing;
if (nvar == 0 || width <= fwidth + swidth)
break;
s = 0.;
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i])
s += weight3(t->tabwidth[i]);
}
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i])
dwidth[i] = (width - fwidth) * weight3(t->tabwidth[i]) / s;
else
dwidth[i] = (double)newwidth[i];
}
dv2sv(dwidth, newwidth, t->maxcol + 1);
try_again = 0;
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i]) {
if (newwidth[i] > t->tabwidth[i]) {
newwidth[i] = t->tabwidth[i];
fixed[i] = 1;
try_again = 1;
}
else if (newwidth[i] < t->minimum_width[i]) {
newwidth[i] = t->minimum_width[i];
fixed[i] = 1;
try_again = 1;
}
}
}
} while (try_again);
}
#endif /* not MATRIX */
void
check_table_height(struct table *t)
{
int i, j, k;
struct {
short *row;
short *rowspan;
short *indexarray;
short maxcell;
short size;
short *height;
} cell;
int space = 0;
cell.size = 0;
cell.maxcell = -1;
for (j = 0; j <= t->maxrow; j++) {
if (!t->tabattr[j])
continue;
for (i = 0; i <= t->maxcol; i++) {
int t_dep, rowspan;
if (t->tabattr[j][i] & (HTT_X | HTT_Y))
continue;
if (t->tabdata[j][i] == NULL)
t_dep = 0;
else
t_dep = t->tabdata[j][i]->nitem;
rowspan = table_rowspan(t, j, i);
if (rowspan > 1) {
int c = cell.maxcell + 1;
k = bsearch_2short(rowspan, cell.rowspan,
j, cell.row, t->maxrow + 1, cell.indexarray,
c);
if (k <= cell.maxcell) {
int idx = cell.indexarray[k];
if (cell.row[idx] == j && cell.rowspan[idx] == rowspan)
c = idx;
}
if (c >= MAXROWCELL)
continue;
if (c >= cell.size) {
if (cell.size == 0) {
cell.size = max(MAXCELL, c + 1);
cell.row = NewAtom_N(short, cell.size);
cell.rowspan = NewAtom_N(short, cell.size);
cell.indexarray = NewAtom_N(short, cell.size);
cell.height = NewAtom_N(short, cell.size);
}
else {
cell.size = max(cell.size + MAXCELL, c + 1);
cell.row = New_Reuse(short, cell.row, cell.size);
cell.rowspan = New_Reuse(short, cell.rowspan,
cell.size);
cell.indexarray = New_Reuse(short, cell.indexarray,
cell.size);
cell.height = New_Reuse(short, cell.height, cell.size);
}
}
if (c > cell.maxcell) {
cell.maxcell++;
cell.row[cell.maxcell] = j;
cell.rowspan[cell.maxcell] = rowspan;
cell.height[cell.maxcell] = 0;
if (cell.maxcell > k) {
int ii;
for (ii = cell.maxcell; ii > k; ii--)
cell.indexarray[ii] = cell.indexarray[ii - 1];
}
cell.indexarray[k] = cell.maxcell;
}
if (cell.height[c] < t_dep)
cell.height[c] = t_dep;
continue;
}
if (t->tabheight[j] < t_dep)
t->tabheight[j] = t_dep;
}
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
space = 1;
break;
case BORDER_NONE:
space = 0;
}
check_cell_width(t->tabheight, cell.height, cell.row, cell.rowspan,
cell.maxcell, cell.indexarray, space, 1);
}
#define CHECK_MINIMUM 1
#define CHECK_FIXED 2
int
get_table_width(struct table *t, short *orgwidth, short *cellwidth, int flag)
{
#ifdef __GNUC__
short newwidth[t->maxcol + 1];
#else /* not __GNUC__ */
short newwidth[MAXCOL];
#endif /* not __GNUC__ */
int i;
int swidth;
struct table_cell *cell = &t->cell;
int rulewidth = table_rule_width(t);
for (i = 0; i <= t->maxcol; i++)
newwidth[i] = max(orgwidth[i], 0);
if (flag & CHECK_FIXED) {
#ifdef __GNUC__
short ccellwidth[cell->maxcell + 1];
#else /* not __GNUC__ */
short ccellwidth[MAXCELL];
#endif /* not __GNUC__ */
for (i = 0; i <= t->maxcol; i++) {
if (newwidth[i] < t->fixed_width[i])
newwidth[i] = t->fixed_width[i];
}
for (i = 0; i <= cell->maxcell; i++) {
ccellwidth[i] = cellwidth[i];
if (ccellwidth[i] < cell->fixed_width[i])
ccellwidth[i] = cell->fixed_width[i];
}
check_cell_width(newwidth, ccellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
else {
check_cell_width(newwidth, cellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
if (flag & CHECK_MINIMUM)
check_minimum_width(t, newwidth);
swidth = 0;
for (i = 0; i <= t->maxcol; i++) {
swidth += ceil_at_intervals(newwidth[i], rulewidth);
}
swidth += table_border_width(t);
return swidth;
}
#define minimum_table_width(t)\
(get_table_width(t,t->minimum_width,t->cell.minimum_width,0))
#define maximum_table_width(t)\
(get_table_width(t,t->tabwidth,t->cell.width,CHECK_FIXED))
#define fixed_table_width(t)\
(get_table_width(t,t->fixed_width,t->cell.fixed_width,CHECK_MINIMUM))
#define MAX_COTABLE_LEVEL 100
static int cotable_level;
void
initRenderTable(void)
{
cotable_level = 0;
}
void
renderCoTable(struct table *tbl, int maxlimit)
{
struct readbuffer obuf;
struct html_feed_environ h_env;
struct environment envs[MAX_ENV_LEVEL];
struct table *t;
int i, col, row;
int indent, maxwidth;
if (cotable_level >= MAX_COTABLE_LEVEL)
return; /* workaround to prevent infinite recursion */
cotable_level++;
for (i = 0; i < tbl->ntable; i++) {
t = tbl->tables[i].ptr;
if (t == NULL)
continue;
col = tbl->tables[i].col;
row = tbl->tables[i].row;
indent = tbl->tables[i].indent;
init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL, tbl->tables[i].buf,
get_spec_cell_width(tbl, row, col), indent);
check_row(tbl, row);
if (h_env.limit > maxlimit)
h_env.limit = maxlimit;
if (t->total_width == 0)
maxwidth = h_env.limit - indent;
else if (t->total_width > 0)
maxwidth = t->total_width;
else
maxwidth = t->total_width = -t->total_width * h_env.limit / 100;
renderTable(t, maxwidth, &h_env);
}
}
static void
make_caption(struct table *t, struct html_feed_environ *h_env)
{
struct html_feed_environ henv;
struct readbuffer obuf;
struct environment envs[MAX_ENV_LEVEL];
int limit;
if (t->caption->length <= 0)
return;
if (t->total_width > 0)
limit = t->total_width;
else
limit = h_env->limit;
init_henv(&henv, &obuf, envs, MAX_ENV_LEVEL, newTextLineList(),
limit, h_env->envs[h_env->envc].indent);
HTMLlineproc1("<center>", &henv);
HTMLlineproc0(t->caption->ptr, &henv, FALSE);
HTMLlineproc1("</center>", &henv);
if (t->total_width < henv.maxlimit)
t->total_width = henv.maxlimit;
limit = h_env->limit;
h_env->limit = t->total_width;
HTMLlineproc1("<center>", h_env);
HTMLlineproc0(t->caption->ptr, h_env, FALSE);
HTMLlineproc1("</center>", h_env);
h_env->limit = limit;
}
void
renderTable(struct table *t, int max_width, struct html_feed_environ *h_env)
{
int i, j, w, r, h;
Str renderbuf;
short new_tabwidth[MAXCOL] = { 0 };
#ifdef MATRIX
int itr;
VEC *newwidth;
MAT *mat, *minv;
PERM *pivot;
#endif /* MATRIX */
int width;
int rulewidth;
Str vrulea = NULL, vruleb = NULL, vrulec = NULL;
#ifdef ID_EXT
Str idtag;
#endif /* ID_EXT */
t->total_height = 0;
if (t->maxcol < 0) {
make_caption(t, h_env);
return;
}
if (t->sloppy_width > max_width)
max_width = t->sloppy_width;
rulewidth = table_rule_width(t);
max_width -= table_border_width(t);
if (rulewidth > 1)
max_width = floor_at_intervals(max_width, rulewidth);
if (max_width < rulewidth)
max_width = rulewidth;
#define MAX_TABWIDTH 10000
if (max_width > MAX_TABWIDTH)
max_width = MAX_TABWIDTH;
check_maximum_width(t);
#ifdef MATRIX
if (t->maxcol == 0) {
if (t->tabwidth[0] > max_width)
t->tabwidth[0] = max_width;
if (t->total_width > 0)
t->tabwidth[0] = max_width;
else if (t->fixed_width[0] > 0)
t->tabwidth[0] = t->fixed_width[0];
if (t->tabwidth[0] < t->minimum_width[0])
t->tabwidth[0] = t->minimum_width[0];
}
else {
set_table_matrix(t, max_width);
itr = 0;
mat = m_get(t->maxcol + 1, t->maxcol + 1);
pivot = px_get(t->maxcol + 1);
newwidth = v_get(t->maxcol + 1);
minv = m_get(t->maxcol + 1, t->maxcol + 1);
do {
m_copy(t->matrix, mat);
LUfactor(mat, pivot);
LUsolve(mat, pivot, t->vector, newwidth);
LUinverse(mat, pivot, minv);
#ifdef TABLE_DEBUG
set_integered_width(t, newwidth->ve, new_tabwidth);
fprintf(stderr, "itr=%d\n", itr);
fprintf(stderr, "max_width=%d\n", max_width);
fprintf(stderr, "minimum : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", t->minimum_width[i]);
fprintf(stderr, "\nfixed : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", t->fixed_width[i]);
fprintf(stderr, "\ndecided : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", new_tabwidth[i]);
fprintf(stderr, "\n");
#endif /* TABLE_DEBUG */
itr++;
} while (check_table_width(t, newwidth->ve, minv, itr));
set_integered_width(t, newwidth->ve, new_tabwidth);
check_minimum_width(t, new_tabwidth);
v_free(newwidth);
px_free(pivot);
m_free(mat);
m_free(minv);
m_free(t->matrix);
v_free(t->vector);
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = new_tabwidth[i];
}
}
#else /* not MATRIX */
set_table_width(t, new_tabwidth, max_width);
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = new_tabwidth[i];
}
#endif /* not MATRIX */
check_minimum_width(t, t->tabwidth);
for (i = 0; i <= t->maxcol; i++)
t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);
renderCoTable(t, h_env->limit);
for (i = 0; i <= t->maxcol; i++) {
for (j = 0; j <= t->maxrow; j++) {
check_row(t, j);
if (t->tabattr[j][i] & HTT_Y)
continue;
do_refill(t, j, i, h_env->limit);
}
}
check_minimum_width(t, t->tabwidth);
t->total_width = 0;
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);
t->total_width += t->tabwidth[i];
}
t->total_width += table_border_width(t);
check_table_height(t);
for (i = 0; i <= t->maxcol; i++) {
for (j = 0; j <= t->maxrow; j++) {
TextLineList *l;
int k;
if ((t->tabattr[j][i] & HTT_Y) ||
(t->tabattr[j][i] & HTT_TOP) || (t->tabdata[j][i] == NULL))
continue;
h = t->tabheight[j];
for (k = j + 1; k <= t->maxrow; k++) {
if (!(t->tabattr[k][i] & HTT_Y))
break;
h += t->tabheight[k];
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
h += 1;
break;
}
}
h -= t->tabdata[j][i]->nitem;
if (t->tabattr[j][i] & HTT_MIDDLE)
h /= 2;
if (h <= 0)
continue;
l = newTextLineList();
for (k = 0; k < h; k++)
pushTextLine(l, newTextLine(NULL, 0));
t->tabdata[j][i] = appendGeneralList((GeneralList *)l,
t->tabdata[j][i]);
}
}
/* table output */
width = t->total_width;
make_caption(t, h_env);
HTMLlineproc1("<pre for_table>", h_env);
#ifdef ID_EXT
if (t->id != NULL) {
idtag = Sprintf("<_id id=\"%s\">", html_quote((t->id)->ptr));
HTMLlineproc1(idtag->ptr, h_env);
}
#endif /* ID_EXT */
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
renderbuf = Strnew();
print_sep(t, -1, T_TOP, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
t->total_height += 1;
break;
}
vruleb = Strnew();
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
vrulea = Strnew();
vrulec = Strnew();
push_symbol(vrulea, TK_VERTICALBAR(t->border_mode), symbol_width, 1);
for (i = 0; i < t->cellpadding; i++) {
Strcat_char(vrulea, ' ');
Strcat_char(vruleb, ' ');
Strcat_char(vrulec, ' ');
}
push_symbol(vrulec, TK_VERTICALBAR(t->border_mode), symbol_width, 1);
case BORDER_NOWIN:
push_symbol(vruleb, TK_VERTICALBAR(BORDER_THIN), symbol_width, 1);
for (i = 0; i < t->cellpadding; i++)
Strcat_char(vruleb, ' ');
break;
case BORDER_NONE:
for (i = 0; i < t->cellspacing; i++)
Strcat_char(vruleb, ' ');
}
for (r = 0; r <= t->maxrow; r++) {
for (h = 0; h < t->tabheight[r]; h++) {
renderbuf = Strnew();
if (t->border_mode == BORDER_THIN
|| t->border_mode == BORDER_THICK)
Strcat(renderbuf, vrulea);
#ifdef ID_EXT
if (t->tridvalue[r] != NULL && h == 0) {
idtag = Sprintf("<_id id=\"%s\">",
html_quote((t->tridvalue[r])->ptr));
Strcat(renderbuf, idtag);
}
#endif /* ID_EXT */
for (i = 0; i <= t->maxcol; i++) {
check_row(t, r);
#ifdef ID_EXT
if (t->tabidvalue[r][i] != NULL && h == 0) {
idtag = Sprintf("<_id id=\"%s\">",
html_quote((t->tabidvalue[r][i])->ptr));
Strcat(renderbuf, idtag);
}
#endif /* ID_EXT */
if (!(t->tabattr[r][i] & HTT_X)) {
w = t->tabwidth[i];
for (j = i + 1;
j <= t->maxcol && (t->tabattr[r][j] & HTT_X); j++)
w += t->tabwidth[j] + t->cellspacing;
if (t->tabattr[r][i] & HTT_Y) {
for (j = r - 1; j >= 0 && t->tabattr[j]
&& (t->tabattr[j][i] & HTT_Y); j--) ;
print_item(t, j, i, w, renderbuf);
}
else
print_item(t, r, i, w, renderbuf);
}
if (i < t->maxcol && !(t->tabattr[r][i + 1] & HTT_X))
Strcat(renderbuf, vruleb);
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
Strcat(renderbuf, vrulec);
t->total_height += 1;
break;
}
push_render_image(renderbuf, width, t->total_width, h_env);
}
if (r < t->maxrow && t->border_mode != BORDER_NONE) {
renderbuf = Strnew();
print_sep(t, r, T_MIDDLE, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
}
t->total_height += t->tabheight[r];
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
renderbuf = Strnew();
print_sep(t, t->maxrow, T_BOTTOM, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
t->total_height += 1;
break;
}
if (t->total_height == 0) {
renderbuf = Strnew_charp(" ");
t->total_height++;
t->total_width = 1;
push_render_image(renderbuf, 1, t->total_width, h_env);
}
HTMLlineproc1("</pre>", h_env);
}
#ifdef TABLE_NO_COMPACT
#define THR_PADDING 2
#else
#define THR_PADDING 4
#endif
struct table *
begin_table(int border, int spacing, int padding, int vspace)
{
struct table *t;
int mincell = minimum_cellspacing(border);
int rcellspacing;
int mincell_pixels = round(mincell * pixel_per_char);
int ppc = round(pixel_per_char);
t = newTable();
t->row = t->col = -1;
t->maxcol = -1;
t->maxrow = -1;
t->border_mode = border;
t->flag = 0;
if (border == BORDER_NOWIN)
t->flag |= TBL_EXPAND_OK;
rcellspacing = spacing + 2 * padding;
switch (border) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
t->cellpadding = padding - (mincell_pixels - 4) / 2;
break;
case BORDER_NONE:
t->cellpadding = rcellspacing - mincell_pixels;
}
if (t->cellpadding >= ppc)
t->cellpadding /= ppc;
else if (t->cellpadding > 0)
t->cellpadding = 1;
else
t->cellpadding = 0;
switch (border) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
t->cellspacing = 2 * t->cellpadding + mincell;
break;
case BORDER_NONE:
t->cellspacing = t->cellpadding + mincell;
}
if (border == BORDER_NONE) {
if (rcellspacing / 2 + vspace <= 1)
t->vspace = 0;
else
t->vspace = 1;
}
else {
if (vspace < ppc)
t->vspace = 0;
else
t->vspace = 1;
}
if (border == BORDER_NONE) {
if (rcellspacing <= THR_PADDING)
t->vcellpadding = 0;
else
t->vcellpadding = 1;
}
else {
if (padding < 2 * ppc - 2)
t->vcellpadding = 0;
else
t->vcellpadding = 1;
}
return t;
}
void
end_table(struct table *tbl)
{
struct table_cell *cell = &tbl->cell;
int i, rulewidth = table_rule_width(tbl);
if (rulewidth > 1) {
if (tbl->total_width > 0)
tbl->total_width = ceil_at_intervals(tbl->total_width, rulewidth);
for (i = 0; i <= tbl->maxcol; i++) {
tbl->minimum_width[i] =
ceil_at_intervals(tbl->minimum_width[i], rulewidth);
tbl->tabwidth[i] = ceil_at_intervals(tbl->tabwidth[i], rulewidth);
if (tbl->fixed_width[i] > 0)
tbl->fixed_width[i] =
ceil_at_intervals(tbl->fixed_width[i], rulewidth);
}
for (i = 0; i <= cell->maxcell; i++) {
cell->minimum_width[i] =
ceil_at_intervals(cell->minimum_width[i], rulewidth);
cell->width[i] = ceil_at_intervals(cell->width[i], rulewidth);
if (cell->fixed_width[i] > 0)
cell->fixed_width[i] =
ceil_at_intervals(cell->fixed_width[i], rulewidth);
}
}
tbl->sloppy_width = fixed_table_width(tbl);
if (tbl->total_width > tbl->sloppy_width)
tbl->sloppy_width = tbl->total_width;
}
static void
check_minimum0(struct table *t, int min)
{
int i, w, ww;
struct table_cell *cell;
if (t->col < 0)
return;
if (t->tabwidth[t->col] < 0)
return;
check_row(t, t->row);
w = table_colspan(t, t->row, t->col);
min += t->indent;
if (w == 1)
ww = min;
else {
cell = &t->cell;
ww = 0;
if (cell->icell >= 0 && cell->minimum_width[cell->icell] < min)
cell->minimum_width[cell->icell] = min;
}
for (i = t->col;
i <= t->maxcol && (i == t->col || (t->tabattr[t->row][i] & HTT_X));
i++) {
if (t->minimum_width[i] < ww)
t->minimum_width[i] = ww;
}
}
static int
setwidth0(struct table *t, struct table_mode *mode)
{
int w;
int width = t->tabcontentssize;
struct table_cell *cell = &t->cell;
if (t->col < 0)
return -1;
if (t->tabwidth[t->col] < 0)
return -1;
check_row(t, t->row);
if (t->linfo.prev_spaces > 0)
width -= t->linfo.prev_spaces;
w = table_colspan(t, t->row, t->col);
if (w == 1) {
if (t->tabwidth[t->col] < width)
t->tabwidth[t->col] = width;
}
else if (cell->icell >= 0) {
if (cell->width[cell->icell] < width)
cell->width[cell->icell] = width;
}
return width;
}
static void
setwidth(struct table *t, struct table_mode *mode)
{
int width = setwidth0(t, mode);
if (width < 0)
return;
#ifdef NOWRAP
if (t->tabattr[t->row][t->col] & HTT_NOWRAP)
check_minimum0(t, width);
#endif /* NOWRAP */
if (mode->pre_mode & (TBLM_NOBR | TBLM_PRE | TBLM_PRE_INT) &&
mode->nobr_offset >= 0)
check_minimum0(t, width - mode->nobr_offset);
}
static void
addcontentssize(struct table *t, int width)
{
if (t->col < 0)
return;
if (t->tabwidth[t->col] < 0)
return;
check_row(t, t->row);
t->tabcontentssize += width;
}
static void table_close_anchor0(struct table *tbl, struct table_mode *mode);
static void
clearcontentssize(struct table *t, struct table_mode *mode)
{
table_close_anchor0(t, mode);
mode->nobr_offset = 0;
t->linfo.prev_spaces = -1;
set_space_to_prevchar(t->linfo.prevchar);
t->linfo.prev_ctype = PC_ASCII;
t->linfo.length = 0;
t->tabcontentssize = 0;
}
static void
begin_cell(struct table *t, struct table_mode *mode)
{
clearcontentssize(t, mode);
mode->indent_level = 0;
mode->nobr_level = 0;
mode->pre_mode = 0;
t->indent = 0;
t->flag |= TBL_IN_COL;
if (t->suspended_data) {
check_row(t, t->row);
if (t->tabdata[t->row][t->col] == NULL)
t->tabdata[t->row][t->col] = newGeneralList();
appendGeneralList(t->tabdata[t->row][t->col],
(GeneralList *)t->suspended_data);
t->suspended_data = NULL;
}
}
void
check_rowcol(struct table *tbl, struct table_mode *mode)
{
int row = tbl->row, col = tbl->col;
if (!(tbl->flag & TBL_IN_ROW)) {
tbl->flag |= TBL_IN_ROW;
tbl->row++;
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
tbl->col = -1;
}
if (tbl->row == -1)
tbl->row = 0;
if (tbl->col == -1)
tbl->col = 0;
for (;; tbl->row++) {
check_row(tbl, tbl->row);
for (; tbl->col < MAXCOL &&
tbl->tabattr[tbl->row][tbl->col] & (HTT_X | HTT_Y); tbl->col++) ;
if (tbl->col < MAXCOL)
break;
tbl->col = 0;
}
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
if (tbl->col > tbl->maxcol)
tbl->maxcol = tbl->col;
if (tbl->row != row || tbl->col != col)
begin_cell(tbl, mode);
tbl->flag |= TBL_IN_COL;
}
int
skip_space(struct table *t, char *line, struct table_linfo *linfo,
int checkminimum)
{
int skip = 0, s = linfo->prev_spaces;
Lineprop ctype, prev_ctype = linfo->prev_ctype;
Str prevchar = linfo->prevchar;
int w = linfo->length;
int min = 1;
if (*line == '<' && line[strlen(line) - 1] == '>') {
if (checkminimum)
check_minimum0(t, visible_length(line));
return 0;
}
while (*line) {
char *save = line, *c = line;
int ec, len, wlen, plen;
ctype = get_mctype(line);
len = get_mcwidth(line);
wlen = plen = get_mclen(line);
if (min < w)
min = w;
if (ctype == PC_ASCII && IS_SPACE(*c)) {
w = 0;
s++;
}
else {
if (*c == '&') {
ec = getescapechar(&line);
if (ec >= 0) {
c = conv_entity(ec);
ctype = get_mctype(c);
len = get_strwidth(c);
wlen = line - save;
plen = get_mclen(c);
}
}
if (prevchar->length && is_boundary((unsigned char *)prevchar->ptr,
(unsigned char *)c)) {
w = len;
}
else {
w += len;
}
if (s > 0) {
#ifdef USE_M17N
if (ctype == PC_KANJI1 && prev_ctype == PC_KANJI1)
skip += s;
else
#endif
skip += s - 1;
}
s = 0;
prev_ctype = ctype;
}
set_prevchar(prevchar, c, plen);
line = save + wlen;
}
if (s > 1) {
skip += s - 1;
linfo->prev_spaces = 1;
}
else {
linfo->prev_spaces = s;
}
linfo->prev_ctype = prev_ctype;
linfo->prevchar = prevchar;
if (checkminimum) {
if (min < w)
min = w;
linfo->length = w;
check_minimum0(t, min);
}
return skip;
}
static void
feed_table_inline_tag(struct table *tbl,
char *line, struct table_mode *mode, int width)
{
check_rowcol(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
if (width >= 0) {
check_minimum0(tbl, width);
addcontentssize(tbl, width);
setwidth(tbl, mode);
}
}
static void
feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
if (mode->indent_level >= CHAR_MAX && indent == 1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
if (tbl->indent < 0)
tbl->indent = 0;
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
if (offset < 0)
offset = 0;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
}
static void
table_close_select(struct table *tbl, struct table_mode *mode, int width)
{
Str tmp = process_n_select();
mode->pre_mode &= ~TBLM_INSELECT;
mode->end_tag = 0;
feed_table1(tbl, tmp, mode, width);
}
static void
table_close_textarea(struct table *tbl, struct table_mode *mode, int width)
{
Str tmp = process_n_textarea();
mode->pre_mode &= ~TBLM_INTXTA;
mode->end_tag = 0;
feed_table1(tbl, tmp, mode, width);
}
static void
table_close_anchor0(struct table *tbl, struct table_mode *mode)
{
if (!(mode->pre_mode & TBLM_ANCHOR))
return;
mode->pre_mode &= ~TBLM_ANCHOR;
if (tbl->tabcontentssize == mode->anchor_offset) {
check_minimum0(tbl, 1);
addcontentssize(tbl, 1);
setwidth(tbl, mode);
}
else if (tbl->linfo.prev_spaces > 0 &&
tbl->tabcontentssize - 1 == mode->anchor_offset) {
if (tbl->linfo.prev_spaces > 0)
tbl->linfo.prev_spaces = -1;
}
}
#define TAG_ACTION_NONE 0
#define TAG_ACTION_FEED 1
#define TAG_ACTION_TABLE 2
#define TAG_ACTION_N_TABLE 3
#define TAG_ACTION_PLAIN 4
#define CASE_TABLE_TAG \
case HTML_TABLE:\
case HTML_N_TABLE:\
case HTML_TR:\
case HTML_N_TR:\
case HTML_TD:\
case HTML_N_TD:\
case HTML_TH:\
case HTML_N_TH:\
case HTML_THEAD:\
case HTML_N_THEAD:\
case HTML_TBODY:\
case HTML_N_TBODY:\
case HTML_TFOOT:\
case HTML_N_TFOOT:\
case HTML_COLGROUP:\
case HTML_N_COLGROUP:\
case HTML_COL
#define ATTR_ROWSPAN_MAX 32766
static int
feed_table_tag(struct table *tbl, char *line, struct table_mode *mode,
int width, struct parsed_tag *tag)
{
int cmd;
#ifdef ID_EXT
char *p;
#endif
struct table_cell *cell = &tbl->cell;
int colspan, rowspan;
int col, prev_col;
int i, j, k, v, v0, w, id;
Str tok, tmp, anchor;
table_attr align, valign;
cmd = tag->tagid;
if (mode->pre_mode & TBLM_PLAIN) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_PLAIN;
mode->end_tag = 0;
feed_table_block_tag(tbl, line, mode, 0, cmd);
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
if (mode->pre_mode & TBLM_INTXTA) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_TEXTAREA:
table_close_textarea(tbl, mode, width);
if (cmd == HTML_N_TEXTAREA)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->pre_mode & TBLM_SCRIPT) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_SCRIPT;
mode->end_tag = 0;
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
if (mode->pre_mode & TBLM_STYLE) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_STYLE;
mode->end_tag = 0;
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
/* failsafe: a tag other than <option></option>and </select> in *
* <select> environment is regarded as the end of <select>. */
if (mode->pre_mode & TBLM_INSELECT) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_FORM:
case HTML_N_SELECT: /* mode->end_tag */
table_close_select(tbl, mode, width);
if (cmd == HTML_N_SELECT)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->caption) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_CAPTION:
mode->caption = 0;
if (cmd == HTML_N_CAPTION)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->pre_mode & TBLM_PRE) {
switch (cmd) {
case HTML_NOBR:
case HTML_N_NOBR:
case HTML_PRE_INT:
case HTML_N_PRE_INT:
return TAG_ACTION_NONE;
}
}
switch (cmd) {
case HTML_TABLE:
check_rowcol(tbl, mode);
return TAG_ACTION_TABLE;
case HTML_N_TABLE:
if (tbl->suspended_data)
check_rowcol(tbl, mode);
return TAG_ACTION_N_TABLE;
case HTML_TR:
if (tbl->col >= 0 && tbl->tabcontentssize > 0)
setwidth(tbl, mode);
tbl->col = -1;
tbl->row++;
tbl->flag |= TBL_IN_ROW;
tbl->flag &= ~TBL_IN_COL;
align = 0;
valign = 0;
if (parsedtag_get_value(tag, ATTR_ALIGN, &i)) {
switch (i) {
case ALIGN_LEFT:
align = (HTT_LEFT | HTT_TRSET);
break;
case ALIGN_RIGHT:
align = (HTT_RIGHT | HTT_TRSET);
break;
case ALIGN_CENTER:
align = (HTT_CENTER | HTT_TRSET);
break;
}
}
if (parsedtag_get_value(tag, ATTR_VALIGN, &i)) {
switch (i) {
case VALIGN_TOP:
valign = (HTT_TOP | HTT_VTRSET);
break;
case VALIGN_MIDDLE:
valign = (HTT_MIDDLE | HTT_VTRSET);
break;
case VALIGN_BOTTOM:
valign = (HTT_BOTTOM | HTT_VTRSET);
break;
}
}
#ifdef ID_EXT
if (parsedtag_get_value(tag, ATTR_ID, &p)) {
check_row(tbl, tbl->row);
tbl->tridvalue[tbl->row] = Strnew_charp(p);
}
#endif /* ID_EXT */
tbl->trattr = align | valign;
break;
case HTML_TH:
case HTML_TD:
prev_col = tbl->col;
if (tbl->col >= 0 && tbl->tabcontentssize > 0)
setwidth(tbl, mode);
if (tbl->row == -1) {
/* for broken HTML... */
tbl->row = -1;
tbl->col = -1;
tbl->maxrow = tbl->row;
}
if (tbl->col == -1) {
if (!(tbl->flag & TBL_IN_ROW)) {
tbl->row++;
tbl->flag |= TBL_IN_ROW;
}
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
}
tbl->col++;
check_row(tbl, tbl->row);
while (tbl->col < MAXCOL && tbl->tabattr[tbl->row][tbl->col]) {
tbl->col++;
}
if (tbl->col > MAXCOL - 1) {
tbl->col = prev_col;
return TAG_ACTION_NONE;
}
if (tbl->col > tbl->maxcol) {
tbl->maxcol = tbl->col;
}
colspan = rowspan = 1;
if (tbl->trattr & HTT_TRSET)
align = (tbl->trattr & HTT_ALIGN);
else if (cmd == HTML_TH)
align = HTT_CENTER;
else
align = HTT_LEFT;
if (tbl->trattr & HTT_VTRSET)
valign = (tbl->trattr & HTT_VALIGN);
else
valign = HTT_MIDDLE;
if (parsedtag_get_value(tag, ATTR_ROWSPAN, &rowspan)) {
if(rowspan > ATTR_ROWSPAN_MAX) {
rowspan = ATTR_ROWSPAN_MAX;
}
if ((tbl->row + rowspan) >= tbl->max_rowsize)
check_row(tbl, tbl->row + rowspan);
}
if (rowspan < 1)
rowspan = 1;
if (parsedtag_get_value(tag, ATTR_COLSPAN, &colspan)) {
if ((tbl->col + colspan) >= MAXCOL) {
/* Can't expand column */
colspan = MAXCOL - tbl->col;
}
}
if (colspan < 1)
colspan = 1;
if (parsedtag_get_value(tag, ATTR_ALIGN, &i)) {
switch (i) {
case ALIGN_LEFT:
align = HTT_LEFT;
break;
case ALIGN_RIGHT:
align = HTT_RIGHT;
break;
case ALIGN_CENTER:
align = HTT_CENTER;
break;
}
}
if (parsedtag_get_value(tag, ATTR_VALIGN, &i)) {
switch (i) {
case VALIGN_TOP:
valign = HTT_TOP;
break;
case VALIGN_MIDDLE:
valign = HTT_MIDDLE;
break;
case VALIGN_BOTTOM:
valign = HTT_BOTTOM;
break;
}
}
#ifdef NOWRAP
if (parsedtag_exists(tag, ATTR_NOWRAP))
tbl->tabattr[tbl->row][tbl->col] |= HTT_NOWRAP;
#endif /* NOWRAP */
v = 0;
if (parsedtag_get_value(tag, ATTR_WIDTH, &v)) {
#ifdef TABLE_EXPAND
if (v > 0) {
if (tbl->real_width > 0)
v = -(v * 100) / (tbl->real_width * pixel_per_char);
else
v = (int)(v / pixel_per_char);
}
#else
v = RELATIVE_WIDTH(v);
#endif /* not TABLE_EXPAND */
}
#ifdef ID_EXT
if (parsedtag_get_value(tag, ATTR_ID, &p))
tbl->tabidvalue[tbl->row][tbl->col] = Strnew_charp(p);
#endif /* ID_EXT */
#ifdef NOWRAP
if (v != 0) {
/* NOWRAP and WIDTH= conflicts each other */
tbl->tabattr[tbl->row][tbl->col] &= ~HTT_NOWRAP;
}
#endif /* NOWRAP */
tbl->tabattr[tbl->row][tbl->col] &= ~(HTT_ALIGN | HTT_VALIGN);
tbl->tabattr[tbl->row][tbl->col] |= (align | valign);
if (colspan > 1) {
col = tbl->col;
cell->icell = cell->maxcell + 1;
k = bsearch_2short(colspan, cell->colspan, col, cell->col, MAXCOL,
cell->index, cell->icell);
if (k <= cell->maxcell) {
i = cell->index[k];
if (cell->col[i] == col && cell->colspan[i] == colspan)
cell->icell = i;
}
if (cell->icell > cell->maxcell && cell->icell < MAXCELL) {
cell->maxcell++;
cell->col[cell->maxcell] = col;
cell->colspan[cell->maxcell] = colspan;
cell->width[cell->maxcell] = 0;
cell->minimum_width[cell->maxcell] = 0;
cell->fixed_width[cell->maxcell] = 0;
if (cell->maxcell > k) {
int ii;
for (ii = cell->maxcell; ii > k; ii--)
cell->index[ii] = cell->index[ii - 1];
}
cell->index[k] = cell->maxcell;
}
if (cell->icell > cell->maxcell)
cell->icell = -1;
}
if (v != 0) {
if (colspan == 1) {
v0 = tbl->fixed_width[tbl->col];
if (v0 == 0 || (v0 > 0 && v > v0) || (v0 < 0 && v < v0)) {
#ifdef FEED_TABLE_DEBUG
fprintf(stderr, "width(%d) = %d\n", tbl->col, v);
#endif /* TABLE_DEBUG */
tbl->fixed_width[tbl->col] = v;
}
}
else if (cell->icell >= 0) {
v0 = cell->fixed_width[cell->icell];
if (v0 == 0 || (v0 > 0 && v > v0) || (v0 < 0 && v < v0))
cell->fixed_width[cell->icell] = v;
}
}
for (i = 0; i < rowspan; i++) {
check_row(tbl, tbl->row + i);
for (j = 0; j < colspan; j++) {
#if 0
tbl->tabattr[tbl->row + i][tbl->col + j] &= ~(HTT_X | HTT_Y);
#endif
if (!(tbl->tabattr[tbl->row + i][tbl->col + j] &
(HTT_X | HTT_Y))) {
tbl->tabattr[tbl->row + i][tbl->col + j] |=
((i > 0) ? HTT_Y : 0) | ((j > 0) ? HTT_X : 0);
}
if (tbl->col + j > tbl->maxcol) {
tbl->maxcol = tbl->col + j;
}
}
if (tbl->row + i > tbl->maxrow) {
tbl->maxrow = tbl->row + i;
}
}
begin_cell(tbl, mode);
break;
case HTML_N_TR:
setwidth(tbl, mode);
tbl->col = -1;
tbl->flag &= ~(TBL_IN_ROW | TBL_IN_COL);
return TAG_ACTION_NONE;
case HTML_N_TH:
case HTML_N_TD:
setwidth(tbl, mode);
tbl->flag &= ~TBL_IN_COL;
#ifdef FEED_TABLE_DEBUG
{
TextListItem *it;
int i = tbl->col, j = tbl->row;
fprintf(stderr, "(a) row,col: %d, %d\n", j, i);
if (tbl->tabdata[j] && tbl->tabdata[j][i]) {
for (it = ((TextList *)tbl->tabdata[j][i])->first;
it; it = it->next)
fprintf(stderr, " [%s] \n", it->ptr);
}
}
#endif
return TAG_ACTION_NONE;
case HTML_P:
case HTML_BR:
case HTML_CENTER:
case HTML_N_CENTER:
case HTML_DIV:
case HTML_N_DIV:
if (!(tbl->flag & TBL_IN_ROW))
break;
case HTML_DT:
case HTML_DD:
case HTML_H:
case HTML_N_H:
case HTML_LI:
case HTML_PRE:
case HTML_N_PRE:
case HTML_HR:
case HTML_LISTING:
case HTML_XMP:
case HTML_PLAINTEXT:
case HTML_PRE_PLAIN:
case HTML_N_PRE_PLAIN:
feed_table_block_tag(tbl, line, mode, 0, cmd);
switch (cmd) {
case HTML_PRE:
case HTML_PRE_PLAIN:
mode->pre_mode |= TBLM_PRE;
break;
case HTML_N_PRE:
case HTML_N_PRE_PLAIN:
mode->pre_mode &= ~TBLM_PRE;
break;
case HTML_LISTING:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = HTML_N_LISTING;
break;
case HTML_XMP:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = HTML_N_XMP;
break;
case HTML_PLAINTEXT:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = MAX_HTMLTAG;
break;
}
break;
case HTML_DL:
case HTML_BLQ:
case HTML_OL:
case HTML_UL:
feed_table_block_tag(tbl, line, mode, 1, cmd);
break;
case HTML_N_DL:
case HTML_N_BLQ:
case HTML_N_OL:
case HTML_N_UL:
feed_table_block_tag(tbl, line, mode, -1, cmd);
break;
case HTML_NOBR:
case HTML_WBR:
if (!(tbl->flag & TBL_IN_ROW))
break;
case HTML_PRE_INT:
feed_table_inline_tag(tbl, line, mode, -1);
switch (cmd) {
case HTML_NOBR:
mode->nobr_level++;
if (mode->pre_mode & TBLM_NOBR)
return TAG_ACTION_NONE;
mode->pre_mode |= TBLM_NOBR;
break;
case HTML_PRE_INT:
if (mode->pre_mode & TBLM_PRE_INT)
return TAG_ACTION_NONE;
mode->pre_mode |= TBLM_PRE_INT;
tbl->linfo.prev_spaces = 0;
break;
}
mode->nobr_offset = -1;
if (tbl->linfo.length > 0) {
check_minimum0(tbl, tbl->linfo.length);
tbl->linfo.length = 0;
}
break;
case HTML_N_NOBR:
if (!(tbl->flag & TBL_IN_ROW))
break;
feed_table_inline_tag(tbl, line, mode, -1);
if (mode->nobr_level > 0)
mode->nobr_level--;
if (mode->nobr_level == 0)
mode->pre_mode &= ~TBLM_NOBR;
break;
case HTML_N_PRE_INT:
feed_table_inline_tag(tbl, line, mode, -1);
mode->pre_mode &= ~TBLM_PRE_INT;
break;
case HTML_IMG:
check_rowcol(tbl, mode);
w = tbl->fixed_width[tbl->col];
if (w < 0) {
if (tbl->total_width > 0)
w = -tbl->total_width * w / 100;
else if (width > 0)
w = -width * w / 100;
else
w = 0;
}
else if (w == 0) {
if (tbl->total_width > 0)
w = tbl->total_width;
else if (width > 0)
w = width;
}
tok = process_img(tag, w);
feed_table1(tbl, tok, mode, width);
break;
case HTML_FORM:
feed_table_block_tag(tbl, "", mode, 0, cmd);
tmp = process_form(tag);
if (tmp)
feed_table1(tbl, tmp, mode, width);
break;
case HTML_N_FORM:
feed_table_block_tag(tbl, "", mode, 0, cmd);
process_n_form();
break;
case HTML_INPUT:
tmp = process_input(tag);
feed_table1(tbl, tmp, mode, width);
break;
case HTML_BUTTON:
tmp = process_button(tag);
feed_table1(tbl, tmp, mode, width);
break;
case HTML_N_BUTTON:
tmp = process_n_button();
feed_table1(tbl, tmp, mode, width);
break;
case HTML_SELECT:
tmp = process_select(tag);
if (tmp)
feed_table1(tbl, tmp, mode, width);
mode->pre_mode |= TBLM_INSELECT;
mode->end_tag = HTML_N_SELECT;
break;
case HTML_N_SELECT:
case HTML_OPTION:
/* nothing */
break;
case HTML_TEXTAREA:
w = 0;
check_rowcol(tbl, mode);
if (tbl->col + 1 <= tbl->maxcol &&
tbl->tabattr[tbl->row][tbl->col + 1] & HTT_X) {
if (cell->icell >= 0 && cell->fixed_width[cell->icell] > 0)
w = cell->fixed_width[cell->icell];
}
else {
if (tbl->fixed_width[tbl->col] > 0)
w = tbl->fixed_width[tbl->col];
}
tmp = process_textarea(tag, w);
if (tmp)
feed_table1(tbl, tmp, mode, width);
mode->pre_mode |= TBLM_INTXTA;
mode->end_tag = HTML_N_TEXTAREA;
break;
case HTML_A:
table_close_anchor0(tbl, mode);
anchor = NULL;
i = 0;
parsedtag_get_value(tag, ATTR_HREF, &anchor);
parsedtag_get_value(tag, ATTR_HSEQ, &i);
if (anchor) {
check_rowcol(tbl, mode);
if (i == 0) {
Str tmp = process_anchor(tag, line);
if (displayLinkNumber)
{
Str t = getLinkNumberStr(-1);
feed_table_inline_tag(tbl, NULL, mode, t->length);
Strcat(tmp, t);
}
pushdata(tbl, tbl->row, tbl->col, tmp->ptr);
}
else
pushdata(tbl, tbl->row, tbl->col, line);
if (i >= 0) {
mode->pre_mode |= TBLM_ANCHOR;
mode->anchor_offset = tbl->tabcontentssize;
}
}
else
suspend_or_pushdata(tbl, line);
break;
case HTML_DEL:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode |= TBLM_DEL;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* [DEL: */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_N_DEL:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode &= ~TBLM_DEL;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* :DEL] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_S:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode |= TBLM_S;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 3); /* [S: */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_N_S:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode &= ~TBLM_S;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 3); /* :S] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_INS:
case HTML_N_INS:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* [INS:, :INS] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_SUP:
case HTML_SUB:
case HTML_N_SUB:
if (!(mode->pre_mode & (TBLM_DEL | TBLM_S)))
feed_table_inline_tag(tbl, line, mode, 1); /* ^, [, ] */
break;
case HTML_N_SUP:
break;
case HTML_TABLE_ALT:
id = -1;
parsedtag_get_value(tag, ATTR_TID, &id);
if (id >= 0 && id < tbl->ntable) {
struct table *tbl1 = tbl->tables[id].ptr;
feed_table_block_tag(tbl, line, mode, 0, cmd);
addcontentssize(tbl, maximum_table_width(tbl1));
check_minimum0(tbl, tbl1->sloppy_width);
#ifdef TABLE_EXPAND
w = tbl1->total_width;
v = 0;
colspan = table_colspan(tbl, tbl->row, tbl->col);
if (colspan > 1) {
if (cell->icell >= 0)
v = cell->fixed_width[cell->icell];
}
else
v = tbl->fixed_width[tbl->col];
if (v < 0 && tbl->real_width > 0 && tbl1->real_width > 0)
w = -(tbl1->real_width * 100) / tbl->real_width;
else
w = tbl1->real_width;
if (w > 0)
check_minimum0(tbl, w);
else if (w < 0 && v < w) {
if (colspan > 1) {
if (cell->icell >= 0)
cell->fixed_width[cell->icell] = w;
}
else
tbl->fixed_width[tbl->col] = w;
}
#endif
setwidth0(tbl, mode);
clearcontentssize(tbl, mode);
}
break;
case HTML_CAPTION:
mode->caption = 1;
break;
case HTML_N_CAPTION:
case HTML_THEAD:
case HTML_N_THEAD:
case HTML_TBODY:
case HTML_N_TBODY:
case HTML_TFOOT:
case HTML_N_TFOOT:
case HTML_COLGROUP:
case HTML_N_COLGROUP:
case HTML_COL:
break;
case HTML_SCRIPT:
mode->pre_mode |= TBLM_SCRIPT;
mode->end_tag = HTML_N_SCRIPT;
break;
case HTML_STYLE:
mode->pre_mode |= TBLM_STYLE;
mode->end_tag = HTML_N_STYLE;
break;
case HTML_N_A:
table_close_anchor0(tbl, mode);
case HTML_FONT:
case HTML_N_FONT:
case HTML_NOP:
suspend_or_pushdata(tbl, line);
break;
case HTML_INTERNAL:
case HTML_N_INTERNAL:
case HTML_FORM_INT:
case HTML_N_FORM_INT:
case HTML_INPUT_ALT:
case HTML_N_INPUT_ALT:
case HTML_SELECT_INT:
case HTML_N_SELECT_INT:
case HTML_OPTION_INT:
case HTML_TEXTAREA_INT:
case HTML_N_TEXTAREA_INT:
case HTML_IMG_ALT:
case HTML_SYMBOL:
case HTML_N_SYMBOL:
default:
/* unknown tag: put into table */
return TAG_ACTION_FEED;
}
return TAG_ACTION_NONE;
}
int
feed_table(struct table *tbl, char *line, struct table_mode *mode,
int width, int internal)
{
int i;
char *p;
Str tmp;
struct table_linfo *linfo = &tbl->linfo;
if (*line == '<' && line[1] && REALLY_THE_BEGINNING_OF_A_TAG(line)) {
struct parsed_tag *tag;
p = line;
tag = parse_tag(&p, internal);
if (tag) {
switch (feed_table_tag(tbl, line, mode, width, tag)) {
case TAG_ACTION_NONE:
return -1;
case TAG_ACTION_N_TABLE:
return 0;
case TAG_ACTION_TABLE:
return 1;
case TAG_ACTION_PLAIN:
break;
case TAG_ACTION_FEED:
default:
if (parsedtag_need_reconstruct(tag))
line = parsedtag2str(tag)->ptr;
}
}
else {
if (!(mode->pre_mode & (TBLM_PLAIN | TBLM_INTXTA | TBLM_INSELECT |
TBLM_SCRIPT | TBLM_STYLE)))
return -1;
}
}
else {
if (mode->pre_mode & (TBLM_DEL | TBLM_S))
return -1;
}
if (mode->caption) {
Strcat_charp(tbl->caption, line);
return -1;
}
if (mode->pre_mode & TBLM_SCRIPT)
return -1;
if (mode->pre_mode & TBLM_STYLE)
return -1;
if (mode->pre_mode & TBLM_INTXTA) {
feed_textarea(line);
return -1;
}
if (mode->pre_mode & TBLM_INSELECT) {
feed_select(line);
return -1;
}
if (!(mode->pre_mode & TBLM_PLAIN) &&
!(*line == '<' && line[strlen(line) - 1] == '>') &&
strchr(line, '&') != NULL) {
tmp = Strnew();
for (p = line; *p;) {
char *q, *r;
if (*p == '&') {
if (!strncasecmp(p, "&", 5) ||
!strncasecmp(p, ">", 4) || !strncasecmp(p, "<", 4)) {
/* do not convert */
Strcat_char(tmp, *p);
p++;
}
else {
int ec;
q = p;
switch (ec = getescapechar(&p)) {
case '<':
Strcat_charp(tmp, "<");
break;
case '>':
Strcat_charp(tmp, ">");
break;
case '&':
Strcat_charp(tmp, "&");
break;
case '\r':
Strcat_char(tmp, '\n');
break;
default:
r = conv_entity(ec);
if (r != NULL && strlen(r) == 1 &&
ec == (unsigned char)*r) {
Strcat_char(tmp, *r);
break;
}
case -1:
Strcat_char(tmp, *q);
p = q + 1;
break;
}
}
}
else {
Strcat_char(tmp, *p);
p++;
}
}
line = tmp->ptr;
}
if (!(mode->pre_mode & (TBLM_SPECIAL & ~TBLM_NOBR))) {
if (!(tbl->flag & TBL_IN_COL) || linfo->prev_spaces != 0)
while (IS_SPACE(*line))
line++;
if (*line == '\0')
return -1;
check_rowcol(tbl, mode);
if (mode->pre_mode & TBLM_NOBR && mode->nobr_offset < 0)
mode->nobr_offset = tbl->tabcontentssize;
/* count of number of spaces skipped in normal mode */
i = skip_space(tbl, line, linfo, !(mode->pre_mode & TBLM_NOBR));
addcontentssize(tbl, visible_length(line) - i);
setwidth(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
}
else if (mode->pre_mode & TBLM_PRE_INT) {
check_rowcol(tbl, mode);
if (mode->nobr_offset < 0)
mode->nobr_offset = tbl->tabcontentssize;
addcontentssize(tbl, maximum_visible_length(line, tbl->tabcontentssize));
setwidth(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
}
else {
/* <pre> mode or something like it */
check_rowcol(tbl, mode);
while (*line) {
int nl = FALSE;
if ((p = strchr(line, '\r')) || (p = strchr(line, '\n'))) {
if (*p == '\r' && p[1] == '\n')
p++;
if (p[1]) {
p++;
tmp = Strnew_charp_n(line, p - line);
line = p;
p = tmp->ptr;
}
else {
p = line;
line = "";
}
nl = TRUE;
}
else {
p = line;
line = "";
}
if (mode->pre_mode & TBLM_PLAIN)
i = maximum_visible_length_plain(p, tbl->tabcontentssize);
else
i = maximum_visible_length(p, tbl->tabcontentssize);
addcontentssize(tbl, i);
setwidth(tbl, mode);
if (nl)
clearcontentssize(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, p);
}
}
return -1;
}
void
feed_table1(struct table *tbl, Str tok, struct table_mode *mode, int width)
{
Str tokbuf;
int status;
char *line;
if (!tok)
return;
tokbuf = Strnew();
status = R_ST_NORMAL;
line = tok->ptr;
while (read_token
(tokbuf, &line, &status, mode->pre_mode & TBLM_PREMODE, 0))
feed_table(tbl, tokbuf->ptr, mode, width, TRUE);
}
void
pushTable(struct table *tbl, struct table *tbl1)
{
int col;
int row;
col = tbl->col;
row = tbl->row;
if (tbl->ntable >= tbl->tables_size) {
struct table_in *tmp;
tbl->tables_size += MAX_TABLE_N;
tmp = New_N(struct table_in, tbl->tables_size);
if (tbl->tables)
bcopy(tbl->tables, tmp, tbl->ntable * sizeof(struct table_in));
tbl->tables = tmp;
}
tbl->tables[tbl->ntable].ptr = tbl1;
tbl->tables[tbl->ntable].col = col;
tbl->tables[tbl->ntable].row = row;
tbl->tables[tbl->ntable].indent = tbl->indent;
tbl->tables[tbl->ntable].buf = newTextLineList();
check_row(tbl, row);
if (col + 1 <= tbl->maxcol && tbl->tabattr[row][col + 1] & HTT_X)
tbl->tables[tbl->ntable].cell = tbl->cell.icell;
else
tbl->tables[tbl->ntable].cell = -1;
tbl->ntable++;
}
#ifdef MATRIX
int
correct_table_matrix(struct table *t, int col, int cspan, int a, double b)
{
int i, j;
int ecol = col + cspan;
double w = 1. / (b * b);
for (i = col; i < ecol; i++) {
v_add_val(t->vector, i, w * a);
for (j = i; j < ecol; j++) {
m_add_val(t->matrix, i, j, w);
m_set_val(t->matrix, j, i, m_entry(t->matrix, i, j));
}
}
return i;
}
static void
correct_table_matrix2(struct table *t, int col, int cspan, double s, double b)
{
int i, j;
int ecol = col + cspan;
int size = t->maxcol + 1;
double w = 1. / (b * b);
double ss;
for (i = 0; i < size; i++) {
for (j = i; j < size; j++) {
if (i >= col && i < ecol && j >= col && j < ecol)
ss = (1. - s) * (1. - s);
else if ((i >= col && i < ecol) || (j >= col && j < ecol))
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
correct_table_matrix3(struct table *t, int col, char *flags, double s,
double b)
{
int i, j;
double ss;
int size = t->maxcol + 1;
double w = 1. / (b * b);
int flg = (flags[col] == 0);
for (i = 0; i < size; i++) {
if (!((flg && flags[i] == 0) || (!flg && flags[i] != 0)))
continue;
for (j = i; j < size; j++) {
if (!((flg && flags[j] == 0) || (!flg && flags[j] != 0)))
continue;
if (i == col && j == col)
ss = (1. - s) * (1. - s);
else if (i == col || j == col)
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
correct_table_matrix4(struct table *t, int col, int cspan, char *flags,
double s, double b)
{
int i, j;
double ss;
int ecol = col + cspan;
int size = t->maxcol + 1;
double w = 1. / (b * b);
for (i = 0; i < size; i++) {
if (flags[i] && !(i >= col && i < ecol))
continue;
for (j = i; j < size; j++) {
if (flags[j] && !(j >= col && j < ecol))
continue;
if (i >= col && i < ecol && j >= col && j < ecol)
ss = (1. - s) * (1. - s);
else if ((i >= col && i < ecol) || (j >= col && j < ecol))
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
set_table_matrix0(struct table *t, int maxwidth)
{
int size = t->maxcol + 1;
int i, j, k, bcol, ecol;
int width;
double w0, w1, w, s, b;
#ifdef __GNUC__
double we[size];
char expand[size];
#else /* not __GNUC__ */
double we[MAXCOL];
char expand[MAXCOL];
#endif /* not __GNUC__ */
struct table_cell *cell = &t->cell;
w0 = 0.;
for (i = 0; i < size; i++) {
we[i] = weight(t->tabwidth[i]);
w0 += we[i];
}
if (w0 <= 0.)
w0 = 1.;
if (cell->necell == 0) {
for (i = 0; i < size; i++) {
s = we[i] / w0;
b = sigma_td_nw((int)(s * maxwidth));
correct_table_matrix2(t, i, 1, s, b);
}
return;
}
bzero(expand, size);
for (k = 0; k < cell->necell; k++) {
j = cell->eindex[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
w1 = 0.;
for (i = bcol; i < ecol; i++) {
w1 += t->tabwidth[i] + 0.1;
expand[i]++;
}
for (i = bcol; i < ecol; i++) {
w = weight(width * (t->tabwidth[i] + 0.1) / w1);
if (w > we[i])
we[i] = w;
}
}
w0 = 0.;
w1 = 0.;
for (i = 0; i < size; i++) {
w0 += we[i];
if (expand[i] == 0)
w1 += we[i];
}
if (w0 <= 0.)
w0 = 1.;
for (k = 0; k < cell->necell; k++) {
j = cell->eindex[k];
bcol = cell->col[j];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
w = weight(width);
s = w / (w1 + w);
b = sigma_td_nw((int)(s * maxwidth));
correct_table_matrix4(t, bcol, cell->colspan[j], expand, s, b);
}
for (i = 0; i < size; i++) {
if (expand[i] == 0) {
s = we[i] / max(w1, 1.);
b = sigma_td_nw((int)(s * maxwidth));
}
else {
s = we[i] / max(w0 - w1, 1.);
b = sigma_td_nw(maxwidth);
}
correct_table_matrix3(t, i, expand, s, b);
}
}
void
check_relative_width(struct table *t, int maxwidth)
{
int i;
double rel_total = 0;
int size = t->maxcol + 1;
double *rcolwidth = New_N(double, size);
struct table_cell *cell = &t->cell;
int n_leftcol = 0;
for (i = 0; i < size; i++)
rcolwidth[i] = 0;
for (i = 0; i < size; i++) {
if (t->fixed_width[i] < 0)
rcolwidth[i] = -(double)t->fixed_width[i] / 100.0;
else if (t->fixed_width[i] > 0)
rcolwidth[i] = (double)t->fixed_width[i] / maxwidth;
else
n_leftcol++;
}
for (i = 0; i <= cell->maxcell; i++) {
if (cell->fixed_width[i] < 0) {
double w = -(double)cell->fixed_width[i] / 100.0;
double r;
int j, k;
int n_leftcell = 0;
k = cell->col[i];
r = 0.0;
for (j = 0; j < cell->colspan[i]; j++) {
if (rcolwidth[j + k] > 0)
r += rcolwidth[j + k];
else
n_leftcell++;
}
if (n_leftcell == 0) {
/* w must be identical to r */
if (w != r)
cell->fixed_width[i] = -100 * r;
}
else {
if (w <= r) {
/* make room for the left(width-unspecified) cell */
/* the next formula is an estimation of required width */
w = r * cell->colspan[i] / (cell->colspan[i] - n_leftcell);
cell->fixed_width[i] = -100 * w;
}
for (j = 0; j < cell->colspan[i]; j++) {
if (rcolwidth[j + k] == 0)
rcolwidth[j + k] = (w - r) / n_leftcell;
}
}
}
else if (cell->fixed_width[i] > 0) {
/* todo */
}
}
/* sanity check */
for (i = 0; i < size; i++)
rel_total += rcolwidth[i];
if ((n_leftcol == 0 && rel_total < 0.9) || 1.1 < rel_total) {
for (i = 0; i < size; i++) {
rcolwidth[i] /= rel_total;
}
for (i = 0; i < size; i++) {
if (t->fixed_width[i] < 0)
t->fixed_width[i] = -rcolwidth[i] * 100;
}
for (i = 0; i <= cell->maxcell; i++) {
if (cell->fixed_width[i] < 0) {
double r;
int j, k;
k = cell->col[i];
r = 0.0;
for (j = 0; j < cell->colspan[i]; j++)
r += rcolwidth[j + k];
cell->fixed_width[i] = -r * 100;
}
}
}
}
void
set_table_matrix(struct table *t, int width)
{
int size = t->maxcol + 1;
int i, j;
double b, s;
int a;
struct table_cell *cell = &t->cell;
if (size < 1)
return;
t->matrix = m_get(size, size);
t->vector = v_get(size);
for (i = 0; i < size; i++) {
for (j = i; j < size; j++)
m_set_val(t->matrix, i, j, 0.);
v_set_val(t->vector, i, 0.);
}
check_relative_width(t, width);
for (i = 0; i < size; i++) {
if (t->fixed_width[i] > 0) {
a = max(t->fixed_width[i], t->minimum_width[i]);
b = sigma_td(a);
correct_table_matrix(t, i, 1, a, b);
}
else if (t->fixed_width[i] < 0) {
s = -(double)t->fixed_width[i] / 100.;
b = sigma_td((int)(s * width));
correct_table_matrix2(t, i, 1, s, b);
}
}
for (j = 0; j <= cell->maxcell; j++) {
if (cell->fixed_width[j] > 0) {
a = max(cell->fixed_width[j], cell->minimum_width[j]);
b = sigma_td(a);
correct_table_matrix(t, cell->col[j], cell->colspan[j], a, b);
}
else if (cell->fixed_width[j] < 0) {
s = -(double)cell->fixed_width[j] / 100.;
b = sigma_td((int)(s * width));
correct_table_matrix2(t, cell->col[j], cell->colspan[j], s, b);
}
}
set_table_matrix0(t, width);
if (t->total_width > 0) {
b = sigma_table(width);
}
else {
b = sigma_table_nw(width);
}
correct_table_matrix(t, 0, size, width, b);
}
#endif /* MATRIX */
/* Local Variables: */
/* c-basic-offset: 4 */
/* tab-width: 8 */
/* End: */
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_587_0 |
crossvul-cpp_data_good_2948_0 | /*
* 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 == 0) \
xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \
} 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 == 0) \
xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \
} 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);
}
#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);
}
#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; \
} 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 expandPE = ((ctxt->external != 0) || (ctxt->inputNr != 1));
while (1) {
if (IS_BLANK_CH(CUR)) { /* CHECKED tstblanks.xml */
NEXT;
} else if (CUR == '%') {
/*
* Need to handle support of entities branching here
*/
if ((expandPE == 0) || (IS_BLANK_CH(NXT(1))) || (NXT(1) == 0))
break;
xmlParsePEReference(ctxt);
} else if (CUR == 0) {
if (ctxt->inputNr <= 1)
break;
xmlPopInput(ctxt);
} else {
break;
}
/*
* Also increase the counter when entering or exiting a PERef.
* The spec says: "When a parameter-entity reference is recognized
* in the DTD and included, its replacement text MUST be enlarged
* by the attachment of one leading and one following space (#x20)
* character."
*/
res++;
}
}
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);
if ((ctxt->inputNr > 1) && (ctxt->inSubset == 0) &&
(ctxt->instate != XML_PARSER_EOF))
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"Unfinished entity outside the DTD");
xmlFreeInputStream(inputPop(ctxt));
if (*ctxt->input->cur == 0)
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
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);
}
if (((ctxt->inputNr > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
(ctxt->inputNr > 1024)) {
xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
while (ctxt->inputNr > 1)
xmlFreeInputStream(inputPop(ctxt));
return(-1);
}
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);
}
/**
* 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) {
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;
}
xmlParsePEReference(ctxt);
}
/*
* 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 ((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 - ctxt->input->base < len) {
/*
* There were a couple of bugs where PERefs lead to to a change
* of the buffer. Check the buffer size to avoid passing an invalid
* pointer to xmlDictLookup.
*/
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"unexpected change of input buffer");
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);
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 ">",
* and must, for compatibility, be escaped using ">" 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 + 1;
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 ((ctxt->input->cur < ctxt->input->end) && (!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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'SYSTEM'\n");
}
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'PUBLIC'\n");
}
*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 (SKIP_BLANKS == 0) {
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. We skip blanks if no
* system literal was found, but this is harmless since we must
* be at the end of a NotationDecl.
*/
if (SKIP_BLANKS == 0) return(NULL);
if ((CUR != '\'') && (CUR != '"')) return(NULL);
}
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) == '?')) {
int inputid = ctxt->input->id;
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 (inputid != ctxt->input->id) {
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;
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
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 (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"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')) {
int inputid = ctxt->input->id;
SHRINK;
SKIP(10);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!NOTATION'\n");
return;
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colons are forbidden from notation names '%s'\n",
name, NULL, NULL);
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the NOTATION name'\n");
return;
}
/*
* Parse the IDs.
*/
Systemid = xmlParseExternalID(ctxt, &Pubid, 0);
SKIP_BLANKS;
if (RAW == '>') {
if (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"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;
/* GROW; done in the caller */
if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) {
int inputid = ctxt->input->id;
SHRINK;
SKIP(8);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ENTITY'\n");
}
if (RAW == '%') {
NEXT;
if (SKIP_BLANKS == 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);
}
if (SKIP_BLANKS == 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 != '>') && (SKIP_BLANKS == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required before 'NDATA'\n");
}
if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
SKIP(5);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NDATA'\n");
}
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)
goto done;
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
"xmlParseEntityDecl: entity %s not terminated\n", name);
xmlHaltParser(ctxt);
} else {
if (inputid != ctxt->input->id) {
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) && (cur->orig == NULL)) {
cur->orig = orig;
orig = NULL;
}
}
done:
if (value != NULL) xmlFree(value);
if (URI != NULL) xmlFree(URI);
if (literal != NULL) xmlFree(literal);
if (orig != NULL) xmlFree(orig);
}
}
/**
* 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '#FIXED'\n");
}
}
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NOTATION'\n");
return(0);
}
*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')) {
int inputid = ctxt->input->id;
SKIP(9);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
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)) {
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
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 (SKIP_BLANKS == 0) {
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;
}
}
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 (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in"
" the same entity\n");
}
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')) {
int inputid = ctxt->input->id;
SKIP(9);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'ELEMENT'\n");
return(-1);
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseElementDecl: no name for Element\n");
return(-1);
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the element name\n");
}
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;
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
if (content != NULL) {
xmlFreeDocElementContent(ctxt->myDoc, content);
}
} else {
if (inputid != ctxt->input->id) {
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not"
" in the same entity\n");
}
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");
}
SKIP_BLANKS;
GROW;
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
xmlParseMarkupDecl(ctxt);
SKIP_BLANKS;
GROW;
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not"
" in the same entity\n");
}
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in"
" the same entity\n");
}
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;
/*
* 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space needed after '<?xml'\n");
}
/*
* We may have the VersionInfo here.
*/
version = xmlParseVersionInfo(ctxt);
if (version == NULL)
version = xmlCharStrdup(XML_DEFAULT_VERSION);
else {
if (SKIP_BLANKS == 0) {
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;
SKIP_BLANKS;
while (((RAW == '<') && (NXT(1) == '?')) ||
((RAW == '<') && (NXT(1) == '!')) ||
(RAW == '%')) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
GROW;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else
xmlParseMarkupDecl(ctxt);
SKIP_BLANKS;
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;
/* Prevent entity from being parsed and expanded twice (Bug 760367). */
was_checked = 0;
} 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 "<") 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 "<") 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_PEREF_NO_NAME, "PEReference: no name\n");
return;
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_PEREF_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...
*/
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 {
/*
* 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 {
xmlChar start[4];
xmlCharEncoding enc;
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;
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0) {
xmlFreeInputStream(input);
return;
}
if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
/*
* 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 ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
}
}
}
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);
*str = ptr;
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->inputNr > 1)) &&
(ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
if (ctxt->inputNr > 1)
xmlPopInput(ctxt);
else
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 "<") 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 mandates 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
}
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 mandates 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, inputid;
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;
inputid = ctxt->input->id;
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
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;
}
if (ctxt->input->id != inputid) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"Unexpected change of input\n");
localname = NULL;
goto done;
}
/* 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);
}
done:
/*
* 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;
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 occurred 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);
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);
}
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;
while (ctxt->inputNr > 1)
xmlFreeInputStream(inputPop(ctxt));
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;
ctxt->input->end = 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 ((oldctxt != NULL) && (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_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-835/c/good_2948_0 |
crossvul-cpp_data_bad_4059_1 | /*
* 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.
*/
/*
* vncviewer.c - the Xt-based VNC viewer.
*/
#ifdef WIN32
#include <winsock2.h>
#endif
#ifdef _MSC_VER
#define strdup _strdup /* Prevent POSIX deprecation warnings */
#endif
#ifdef __STRICT_ANSI__
#define _BSD_SOURCE
#define _POSIX_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <rfb/rfbclient.h>
#include "tls.h"
static void Dummy(rfbClient* client) {
}
static rfbBool DummyPoint(rfbClient* client, int x, int y) {
return TRUE;
}
static void DummyRect(rfbClient* client, int x, int y, int w, int h) {
}
#ifdef WIN32
static char* NoPassword(rfbClient* client) {
return strdup("");
}
#else
#include <stdio.h>
#include <termios.h>
#endif
static char* ReadPassword(rfbClient* client) {
int i;
char* p=calloc(1,9);
#ifndef WIN32
struct termios save,noecho;
if(tcgetattr(fileno(stdin),&save)!=0) return p;
noecho=save; noecho.c_lflag &= ~ECHO;
if(tcsetattr(fileno(stdin),TCSAFLUSH,&noecho)!=0) return p;
#endif
fprintf(stderr,"Password: ");
i=0;
while(1) {
int c=fgetc(stdin);
if(c=='\n')
break;
if(i<8) {
p[i]=c;
i++;
p[i]=0;
}
}
#ifndef WIN32
tcsetattr(fileno(stdin),TCSAFLUSH,&save);
#endif
return p;
}
static rfbBool MallocFrameBuffer(rfbClient* client) {
uint64_t allocSize;
if(client->frameBuffer)
free(client->frameBuffer);
/* SECURITY: promote 'width' into uint64_t so that the multiplication does not overflow
'width' and 'height' are 16-bit integers per RFB protocol design
SIZE_MAX is the maximum value that can fit into size_t
*/
allocSize = (uint64_t)client->width * client->height * client->format.bitsPerPixel/8;
if (allocSize >= SIZE_MAX) {
rfbClientErr("CRITICAL: cannot allocate frameBuffer, requested size is too large\n");
return FALSE;
}
client->frameBuffer=malloc( (size_t)allocSize );
if (client->frameBuffer == NULL)
rfbClientErr("CRITICAL: frameBuffer allocation failed, requested size too large or not enough memory?\n");
return client->frameBuffer?TRUE:FALSE;
}
/* messages */
static rfbBool CheckRect(rfbClient* client, int x, int y, int w, int h) {
return x + w <= client->width && y + h <= client->height;
}
static void FillRectangle(rfbClient* client, int x, int y, int w, int h, uint32_t colour) {
int i,j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, x, y, w, h)) {
rfbClientLog("Rect out of bounds: %dx%d at (%d, %d)\n", x, y, w, h);
return;
}
#define FILL_RECT(BPP) \
for(j=y*client->width;j<(y+h)*client->width;j+=client->width) \
for(i=x;i<x+w;i++) \
((uint##BPP##_t*)client->frameBuffer)[j+i]=colour;
switch(client->format.bitsPerPixel) {
case 8: FILL_RECT(8); break;
case 16: FILL_RECT(16); break;
case 32: FILL_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
static void CopyRectangle(rfbClient* client, const uint8_t* buffer, int x, int y, int w, int h) {
int j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, x, y, w, h)) {
rfbClientLog("Rect out of bounds: %dx%d at (%d, %d)\n", x, y, w, h);
return;
}
#define COPY_RECT(BPP) \
{ \
int rs = w * BPP / 8, rs2 = client->width * BPP / 8; \
for (j = ((x * (BPP / 8)) + (y * rs2)); j < (y + h) * rs2; j += rs2) { \
memcpy(client->frameBuffer + j, buffer, rs); \
buffer += rs; \
} \
}
switch(client->format.bitsPerPixel) {
case 8: COPY_RECT(8); break;
case 16: COPY_RECT(16); break;
case 32: COPY_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
/* TODO: test */
static void CopyRectangleFromRectangle(rfbClient* client, int src_x, int src_y, int w, int h, int dest_x, int dest_y) {
int i,j;
if (client->frameBuffer == NULL) {
return;
}
if (!CheckRect(client, src_x, src_y, w, h)) {
rfbClientLog("Source rect out of bounds: %dx%d at (%d, %d)\n", src_x, src_y, w, h);
return;
}
if (!CheckRect(client, dest_x, dest_y, w, h)) {
rfbClientLog("Dest rect out of bounds: %dx%d at (%d, %d)\n", dest_x, dest_y, w, h);
return;
}
#define COPY_RECT_FROM_RECT(BPP) \
{ \
uint##BPP##_t* _buffer=((uint##BPP##_t*)client->frameBuffer)+(src_y-dest_y)*client->width+src_x-dest_x; \
if (dest_y < src_y) { \
for(j = dest_y*client->width; j < (dest_y+h)*client->width; j += client->width) { \
if (dest_x < src_x) { \
for(i = dest_x; i < dest_x+w; i++) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} else { \
for(i = dest_x+w-1; i >= dest_x; i--) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} \
} \
} else { \
for(j = (dest_y+h-1)*client->width; j >= dest_y*client->width; j-=client->width) { \
if (dest_x < src_x) { \
for(i = dest_x; i < dest_x+w; i++) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} else { \
for(i = dest_x+w-1; i >= dest_x; i--) { \
((uint##BPP##_t*)client->frameBuffer)[j+i]=_buffer[j+i]; \
} \
} \
} \
} \
}
switch(client->format.bitsPerPixel) {
case 8: COPY_RECT_FROM_RECT(8); break;
case 16: COPY_RECT_FROM_RECT(16); break;
case 32: COPY_RECT_FROM_RECT(32); break;
default:
rfbClientLog("Unsupported bitsPerPixel: %d\n",client->format.bitsPerPixel);
}
}
static void initAppData(AppData* data) {
data->shareDesktop=TRUE;
data->viewOnly=FALSE;
data->encodingsString="tight zrle ultra copyrect hextile zlib corre rre raw";
data->useBGR233=FALSE;
data->nColours=0;
data->forceOwnCmap=FALSE;
data->forceTrueColour=FALSE;
data->requestedDepth=0;
data->compressLevel=3;
data->qualityLevel=5;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
data->enableJPEG=TRUE;
#else
data->enableJPEG=FALSE;
#endif
data->useRemoteCursor=FALSE;
}
rfbClient* rfbGetClient(int bitsPerSample,int samplesPerPixel,
int bytesPerPixel) {
#ifdef WIN32
WSADATA unused;
#endif
rfbClient* client=(rfbClient*)calloc(sizeof(rfbClient),1);
if(!client) {
rfbClientErr("Couldn't allocate client structure!\n");
return NULL;
}
#ifdef WIN32
if((errno = WSAStartup(MAKEWORD(2,0), &unused)) != 0) {
rfbClientErr("Could not init Windows Sockets: %s\n", strerror(errno));
return NULL;
}
#endif
initAppData(&client->appData);
client->endianTest = 1;
client->programName="";
client->serverHost=strdup("");
client->serverPort=5900;
client->destHost = NULL;
client->destPort = 5900;
client->connectTimeout = DEFAULT_CONNECT_TIMEOUT;
client->CurrentKeyboardLedState = 0;
client->HandleKeyboardLedState = (HandleKeyboardLedStateProc)DummyPoint;
/* default: use complete frame buffer */
client->updateRect.x = -1;
client->frameBuffer = NULL;
client->outputWindow = 0;
client->format.bitsPerPixel = bytesPerPixel*8;
client->format.depth = bitsPerSample*samplesPerPixel;
client->appData.requestedDepth=client->format.depth;
client->format.bigEndian = *(char *)&client->endianTest?FALSE:TRUE;
client->format.trueColour = 1;
if (client->format.bitsPerPixel == 8) {
client->format.redMax = 7;
client->format.greenMax = 7;
client->format.blueMax = 3;
client->format.redShift = 0;
client->format.greenShift = 3;
client->format.blueShift = 6;
} else {
client->format.redMax = (1 << bitsPerSample) - 1;
client->format.greenMax = (1 << bitsPerSample) - 1;
client->format.blueMax = (1 << bitsPerSample) - 1;
if(!client->format.bigEndian) {
client->format.redShift = 0;
client->format.greenShift = bitsPerSample;
client->format.blueShift = bitsPerSample * 2;
} else {
if(client->format.bitsPerPixel==8*3) {
client->format.redShift = bitsPerSample*2;
client->format.greenShift = bitsPerSample*1;
client->format.blueShift = 0;
} else {
client->format.redShift = bitsPerSample*3;
client->format.greenShift = bitsPerSample*2;
client->format.blueShift = bitsPerSample;
}
}
}
client->bufoutptr=client->buf;
client->buffered=0;
#ifdef LIBVNCSERVER_HAVE_LIBZ
client->raw_buffer_size = -1;
client->decompStreamInited = FALSE;
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
memset(client->zlibStreamActive,0,sizeof(rfbBool)*4);
#endif
#endif
client->HandleCursorPos = DummyPoint;
client->SoftCursorLockArea = DummyRect;
client->SoftCursorUnlockScreen = Dummy;
client->GotFrameBufferUpdate = DummyRect;
client->GotCopyRect = CopyRectangleFromRectangle;
client->GotFillRect = FillRectangle;
client->GotBitmap = CopyRectangle;
client->FinishedFrameBufferUpdate = NULL;
client->GetPassword = ReadPassword;
client->MallocFrameBuffer = MallocFrameBuffer;
client->Bell = Dummy;
client->CurrentKeyboardLedState = 0;
client->HandleKeyboardLedState = (HandleKeyboardLedStateProc)DummyPoint;
client->QoS_DSCP = 0;
client->authScheme = 0;
client->subAuthScheme = 0;
client->GetCredential = NULL;
client->tlsSession = NULL;
client->LockWriteToTLS = NULL;
client->UnlockWriteToTLS = NULL;
client->sock = RFB_INVALID_SOCKET;
client->listenSock = RFB_INVALID_SOCKET;
client->listenAddress = NULL;
client->listen6Sock = RFB_INVALID_SOCKET;
client->listen6Address = NULL;
client->clientAuthSchemes = NULL;
#ifdef LIBVNCSERVER_HAVE_SASL
client->GetSASLMechanism = NULL;
client->GetUser = NULL;
client->saslSecret = NULL;
#endif /* LIBVNCSERVER_HAVE_SASL */
return client;
}
static rfbBool rfbInitConnection(rfbClient* client)
{
/* Unless we accepted an incoming connection, make a TCP connection to the
given VNC server */
if (!client->listenSpecified) {
if (!client->serverHost)
return FALSE;
if (client->destHost) {
if (!ConnectToRFBRepeater(client,client->serverHost,client->serverPort,client->destHost,client->destPort))
return FALSE;
} else {
if (!ConnectToRFBServer(client,client->serverHost,client->serverPort))
return FALSE;
}
}
/* Initialise the VNC connection, including reading the password */
if (!InitialiseRFBConnection(client))
return FALSE;
client->width=client->si.framebufferWidth;
client->height=client->si.framebufferHeight;
if (!client->MallocFrameBuffer(client))
return FALSE;
if (!SetFormatAndEncodings(client))
return FALSE;
if (client->updateRect.x < 0) {
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
}
if (client->appData.scaleSetting>1)
{
if (!SendScaleSetting(client, client->appData.scaleSetting))
return FALSE;
if (!SendFramebufferUpdateRequest(client,
client->updateRect.x / client->appData.scaleSetting,
client->updateRect.y / client->appData.scaleSetting,
client->updateRect.w / client->appData.scaleSetting,
client->updateRect.h / client->appData.scaleSetting,
FALSE))
return FALSE;
}
else
{
if (!SendFramebufferUpdateRequest(client,
client->updateRect.x, client->updateRect.y,
client->updateRect.w, client->updateRect.h,
FALSE))
return FALSE;
}
return TRUE;
}
rfbBool rfbInitClient(rfbClient* client,int* argc,char** argv) {
int i,j;
if(argv && argc && *argc) {
if(client->programName==0)
client->programName=argv[0];
for (i = 1; i < *argc; i++) {
j = i;
if (strcmp(argv[i], "-listen") == 0) {
listenForIncomingConnections(client);
break;
} else if (strcmp(argv[i], "-listennofork") == 0) {
listenForIncomingConnectionsNoFork(client, -1);
break;
} else if (strcmp(argv[i], "-play") == 0) {
client->serverPort = -1;
j++;
} else if (i+1<*argc && strcmp(argv[i], "-encodings") == 0) {
client->appData.encodingsString = argv[i+1];
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-compress") == 0) {
client->appData.compressLevel = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-quality") == 0) {
client->appData.qualityLevel = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-scale") == 0) {
client->appData.scaleSetting = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-qosdscp") == 0) {
client->QoS_DSCP = atoi(argv[i+1]);
j+=2;
} else if (i+1<*argc && strcmp(argv[i], "-repeaterdest") == 0) {
char* colon=strchr(argv[i+1],':');
if(client->destHost)
free(client->destHost);
client->destPort = 5900;
client->destHost = strdup(argv[i+1]);
if(colon) {
client->destHost[(int)(colon-argv[i+1])] = '\0';
client->destPort = atoi(colon+1);
}
j+=2;
} else {
char* colon=strrchr(argv[i],':');
if(client->serverHost)
free(client->serverHost);
if(colon) {
client->serverHost = strdup(argv[i]);
client->serverHost[(int)(colon-argv[i])] = '\0';
client->serverPort = atoi(colon+1);
} else {
client->serverHost = strdup(argv[i]);
}
if(client->serverPort >= 0 && client->serverPort < 5900)
client->serverPort += 5900;
}
/* purge arguments */
if (j>i) {
*argc-=j-i;
memmove(argv+i,argv+j,(*argc-i)*sizeof(char*));
i--;
}
}
}
if(!rfbInitConnection(client)) {
rfbClientCleanup(client);
return FALSE;
}
return TRUE;
}
void rfbClientCleanup(rfbClient* client) {
#ifdef LIBVNCSERVER_HAVE_LIBZ
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
int i;
for ( i = 0; i < 4; i++ ) {
if (client->zlibStreamActive[i] == TRUE ) {
if (inflateEnd (&client->zlibStream[i]) != Z_OK &&
client->zlibStream[i].msg != NULL)
rfbClientLog("inflateEnd: %s\n", client->zlibStream[i].msg);
}
}
if ( client->decompStreamInited == TRUE ) {
if (inflateEnd (&client->decompStream) != Z_OK &&
client->decompStream.msg != NULL)
rfbClientLog("inflateEnd: %s\n", client->decompStream.msg );
}
#endif
#endif
if (client->ultra_buffer)
free(client->ultra_buffer);
if (client->raw_buffer)
free(client->raw_buffer);
FreeTLS(client);
while (client->clientData) {
rfbClientData* next = client->clientData->next;
free(client->clientData);
client->clientData = next;
}
if (client->sock != RFB_INVALID_SOCKET)
rfbCloseSocket(client->sock);
if (client->listenSock != RFB_INVALID_SOCKET)
rfbCloseSocket(client->listenSock);
free(client->desktopName);
free(client->serverHost);
if (client->destHost)
free(client->destHost);
if (client->clientAuthSchemes)
free(client->clientAuthSchemes);
#ifdef LIBVNCSERVER_HAVE_SASL
if (client->saslSecret)
free(client->saslSecret);
#endif /* LIBVNCSERVER_HAVE_SASL */
#ifdef WIN32
if(WSACleanup() != 0) {
errno=WSAGetLastError();
rfbClientErr("Could not terminate Windows Sockets: %s\n", strerror(errno));
}
#endif
free(client);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_4059_1 |
crossvul-cpp_data_good_505_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colormap-private.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/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/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__)
#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
/*
Enumerated declaractions.
*/
typedef enum
{
UndefinedSubtype,
RGB555,
RGB565,
ARGB4444,
ARGB1555
} BMPSubtype;
/*
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;
long
colorspace;
PrimaryInfo
red_primary,
green_primary,
blue_primary,
gamma_scale;
} BMPInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteBMPImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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,const size_t number_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.
%
% o number_pixels: The number of pixels.
%
*/
static MagickBooleanType DecodeImage(Image *image,const size_t compression,
unsigned char *pixels,const size_t number_pixels)
{
int
byte,
count;
register ssize_t
i,
x;
register unsigned char
*p,
*q;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
(void) memset(pixels,0,number_pixels*sizeof(*pixels));
byte=0;
x=0;
p=pixels;
q=pixels+number_pixels;
for (y=0; y < (ssize_t) image->rows; )
{
MagickBooleanType
status;
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=ReadBlobByte(image);
if (byte == EOF)
break;
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 == EOF)
break;
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++)
{
byte=ReadBlobByte(image);
if (byte == EOF)
break;
*p++=(unsigned char) byte;
}
else
for (i=0; i < (ssize_t) count; i++)
{
if ((i & 0x01) == 0)
{
byte=ReadBlobByte(image);
if (byte == EOF)
break;
}
*p++=(unsigned char)
((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f));
}
x+=count;
/*
Read pad byte.
*/
if (compression == BI_RLE8)
{
if ((count & 0x01) != 0)
if (ReadBlobByte(image) == EOF)
break;
}
else
if (((count & 0x03) == 1) || ((count & 0x03) == 2))
if (ReadBlobByte(image) == EOF)
break;
break;
}
}
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) ReadBlobByte(image); /* end of line */
(void) ReadBlobByte(image);
return(y < (ssize_t) image->rows ? MagickFalse : 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 == MagickCoreSignature);
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;
MagickBooleanType
status;
MagickOffsetType
offset,
start_position;
MemoryInfo
*pixel_info;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bit,
bytes_per_line,
length;
ssize_t
count,
y;
unsigned char
magick[12],
*pixels;
unsigned int
blue,
green,
offset_bits,
red;
/*
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);
}
/*
Determine if this a BMP file.
*/
(void) memset(&bmp_info,0,sizeof(bmp_info));
bmp_info.ba_offset=0;
start_position=0;
offset_bits=0;
count=ReadBlob(image,2,magick);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
PixelInfo
quantum_bits;
PixelPacket
shift;
/*
Verify BMP identifier.
*/
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 != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"CI",2) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bmp_info.file_size=ReadBlobLSBLong(image);
(void) ReadBlobLSBLong(image);
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",MagickPathExtent);
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) ReadBlobLSBSignedLong(image);
bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(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);
if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
bmp_info.colors_important=ReadBlobLSBLong(image);
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 (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
gamma;
/*
Read color management information.
*/
bmp_info.alpha_mask=ReadBlobLSBLong(image);
bmp_info.colorspace=ReadBlobLSBSignedLong(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;
gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+
bmp_info.red_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.red_primary.x*=gamma;
bmp_info.red_primary.y*=gamma;
image->chromaticity.red_primary.x=bmp_info.red_primary.x;
image->chromaticity.red_primary.y=bmp_info.red_primary.y;
gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+
bmp_info.green_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.green_primary.x*=gamma;
bmp_info.green_primary.y*=gamma;
image->chromaticity.green_primary.x=bmp_info.green_primary.x;
image->chromaticity.green_primary.y=bmp_info.green_primary.y;
gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+
bmp_info.blue_primary.z;
gamma=PerceptibleReciprocal(gamma);
bmp_info.blue_primary.x*=gamma;
bmp_info.blue_primary.y*=gamma;
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",MagickPathExtent);
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;
}
}
(void) ReadBlobLSBLong(image); /* Profile data */
(void) ReadBlobLSBLong(image); /* 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:
image->compression=NoCompression;
break;
case BI_RLE8:
case BI_RLE4:
image->compression=RLECompression;
break;
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->alpha_trait=((bmp_info.alpha_mask != 0) &&
(bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait :
UndefinedPixelTrait;
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;
}
image->resolution.x=(double) bmp_info.x_pixels/100.0;
image->resolution.y=(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;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
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,exception) == 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)
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
count=ReadBlob(image,packet_size*image->colors,bmp_colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=bmp_colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++);
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++);
if (packet_size == 4)
p++;
}
bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap);
}
/*
Read image data.
*/
if (bmp_info.offset_bits == offset_bits)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
offset_bits=bmp_info.offset_bits;
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;
if ((bmp_info.compression == BI_RGB) ||
(bmp_info.compression == BI_BITFIELDS))
{
if ((MagickSizeType) length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
pixel_info=AcquireVirtualMemory(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 (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.
*/
pixel_info=AcquireVirtualMemory(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);
status=DecodeImage(image,bmp_info.compression,pixels,
image->columns*image->rows);
if (status == MagickFalse)
{
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,
"UnableToRunlengthDecodeImage");
}
}
/*
Convert BMP raster image to pixel packets.
*/
if (bmp_info.compression == BI_RGB)
{
/*
We should ignore the alpha value in BMP3 files but there have been
reports about 32 bit files with alpha. We do a quick check to see if
the alpha channel contains a value that is not zero (default value).
If we find a non zero value we asume the program that wrote the file
wants to use the alpha channel.
*/
if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) &&
(bmp_info.bits_per_pixel == 32))
{
bytes_per_line=4*(image->columns);
for (y=(ssize_t) image->rows-1; y >= 0; y--)
{
p=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (*(p+3) != 0)
{
image->alpha_trait=BlendPixelTrait;
y=-1;
break;
}
p+=4;
}
}
}
bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ?
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;
}
}
(void) memset(&shift,0,sizeof(shift));
(void) memset(&quantum_bits,0,sizeof(quantum_bits));
if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32))
{
register unsigned int
sample;
/*
Get shift and quantum bits info from bitfield masks.
*/
if (bmp_info.red_mask != 0)
while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0)
{
shift.red++;
if (shift.red >= 32U)
break;
}
if (bmp_info.green_mask != 0)
while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0)
{
shift.green++;
if (shift.green >= 32U)
break;
}
if (bmp_info.blue_mask != 0)
while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0)
{
shift.blue++;
if (shift.blue >= 32U)
break;
}
if (bmp_info.alpha_mask != 0)
while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0)
{
shift.alpha++;
if (shift.alpha >= 32U)
break;
}
sample=shift.red;
while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.red=(MagickRealType) (sample-shift.red);
sample=shift.green;
while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.green=(MagickRealType) (sample-shift.green);
sample=shift.blue;
while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.blue=(MagickRealType) (sample-shift.blue);
sample=shift.alpha;
while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0)
{
sample++;
if (sample >= 32U)
break;
}
quantum_bits.alpha=(MagickRealType) (sample-shift.alpha);
}
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 == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (image->columns % 8); bit++)
{
index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
p++;
}
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,exception);
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 == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
}
if ((image->columns % 2) != 0)
{
ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index,
exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
p++;
x++;
}
if (x < (ssize_t) image->columns)
break;
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,exception);
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 == (Quantum *) NULL)
break;
for (x=(ssize_t) image->columns; x != 0; --x)
{
ValidateColormapValue(image,(ssize_t) *p++,&index,exception);
SetPixelIndex(image,index,q);
q+=GetPixelChannels(image);
}
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,exception);
break;
}
case 16:
{
unsigned int
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 == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*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);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha <= 8)
alpha|=((alpha & 0xff00) >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
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 == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
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--)
{
unsigned int
alpha,
pixel;
p=pixels+(image->rows-y-1)*bytes_per_line;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(unsigned int) (*p++);
pixel|=((unsigned int) *p++ << 8);
pixel|=((unsigned int) *p++ << 16);
pixel|=((unsigned int) *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);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
{
alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16;
if (quantum_bits.alpha == 8)
alpha|=(alpha >> 8);
SetPixelAlpha(image,ScaleShortToQuantum(
(unsigned short) alpha),q);
}
q+=GetPixelChannels(image);
}
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 (y > 0)
break;
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);
ReplaceImageInList(&image, flipped_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;
offset=(MagickOffsetType) bmp_info.ba_offset;
if (offset != 0)
if ((offset < TellBlob(image)) ||
(SeekBlob(image,offset,SEEK_SET) != offset))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
*magick='\0';
count=ReadBlob(image,2,magick);
if ((count == 2) && (IsBMP(magick,2) != MagickFalse))
{
/*
Acquire next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
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);
if (status == MagickFalse)
return(DestroyImageList(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=AcquireMagickInfo("BMP","BMP","Microsoft Windows bitmap image");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("BMP","BMP2","Microsoft Windows bitmap image (V2)");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("BMP","BMP3","Microsoft Windows bitmap image (V3)");
entry->decoder=(DecodeImageHandler *) ReadBMPImage;
entry->encoder=(EncodeImageHandler *) WriteBMPImage;
entry->magick=(IsImageFormatHandler *) IsBMP;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(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,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 WriteBMPImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
BMPInfo
bmp_info;
BMPSubtype
bmp_subtype;
const char
*option;
const StringInfo
*profile;
MagickBooleanType
have_color_info,
status;
MagickOffsetType
scene;
MemoryInfo
*pixel_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
size_t
bytes_per_line,
imageListLength,
type;
ssize_t
y;
unsigned char
*bmp_data,
*pixels;
/*
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);
type=4;
if (LocaleCompare(image_info->magick,"BMP2") == 0)
type=2;
else
if (LocaleCompare(image_info->magick,"BMP3") == 0)
type=3;
option=GetImageOption(image_info,"bmp:format");
if (option != (char *) NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Format=%s",option);
if (LocaleCompare(option,"bmp2") == 0)
type=2;
if (LocaleCompare(option,"bmp3") == 0)
type=3;
if (LocaleCompare(option,"bmp4") == 0)
type=4;
}
scene=0;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize BMP raster file header.
*/
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) memset(&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;
bmp_info.red_mask=0x00ff0000U;
bmp_info.green_mask=0x0000ff00U;
bmp_info.blue_mask=0x000000ffU;
bmp_info.alpha_mask=0xff000000U;
bmp_subtype=UndefinedSubtype;
if ((image->storage_class == PseudoClass) && (image->colors > 256))
(void) SetImageStorageClass(image,DirectClass,exception);
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->alpha_trait != UndefinedPixelTrait)
(void) SetImageStorageClass(image,DirectClass,exception);
else
if ((size_t) bmp_info.number_colors < image->colors)
(void) SetImageStorageClass(image,DirectClass,exception);
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;
option=GetImageOption(image_info,"bmp:subtype");
if (option != (const char *) NULL)
{
if (image->alpha_trait != UndefinedPixelTrait)
{
if (LocaleNCompare(option,"ARGB4444",8) == 0)
{
bmp_subtype=ARGB4444;
bmp_info.red_mask=0x00000f00U;
bmp_info.green_mask=0x000000f0U;
bmp_info.blue_mask=0x0000000fU;
bmp_info.alpha_mask=0x0000f000U;
}
else if (LocaleNCompare(option,"ARGB1555",8) == 0)
{
bmp_subtype=ARGB1555;
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0x00008000U;
}
}
else
{
if (LocaleNCompare(option,"RGB555",6) == 0)
{
bmp_subtype=RGB555;
bmp_info.red_mask=0x00007c00U;
bmp_info.green_mask=0x000003e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0U;
}
else if (LocaleNCompare(option,"RGB565",6) == 0)
{
bmp_subtype=RGB565;
bmp_info.red_mask=0x0000f800U;
bmp_info.green_mask=0x000007e0U;
bmp_info.blue_mask=0x0000001fU;
bmp_info.alpha_mask=0U;
}
}
}
if (bmp_subtype != UndefinedSubtype)
{
bmp_info.bits_per_pixel=16;
bmp_info.compression=BI_BITFIELDS;
}
else
{
bmp_info.bits_per_pixel=(unsigned short) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? 32 : 24);
bmp_info.compression=(unsigned int) ((type > 3) &&
(image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB);
if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait))
{
option=GetImageOption(image_info,"bmp3:alpha");
if (IsStringTrue(option))
bmp_info.bits_per_pixel=32;
}
}
}
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->alpha_trait == UndefinedPixelTrait) &&
(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;
}
if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) ||
((ssize_t) image->rows != (ssize_t) ((signed int) image->rows)))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
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->resolution.x/2.54);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54);
break;
}
case PixelsPerCentimeterResolution:
{
bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x);
bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y);
break;
}
}
bmp_info.colors_important=bmp_info.number_colors;
/*
Convert MIFF to BMP raster pixels.
*/
pixel_info=AcquireVirtualMemory(image->rows,
MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
(void) memset(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++)
{
ssize_t
offset;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
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(image,p) != 0 ? 0x01 : 0x00;
bit++;
if (bit == 8)
{
*q++=(unsigned char) byte;
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
{
*q++=(unsigned char) (byte << (8-bit));
x++;
}
offset=(ssize_t) (image->columns+7)/8;
for (x=offset; 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:
{
unsigned int
byte,
nibble;
ssize_t
offset;
/*
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,exception);
if (p == (const Quantum *) NULL)
break;
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|=((unsigned int) GetPixelIndex(image,p) & 0x0f);
nibble++;
if (nibble == 2)
{
*q++=(unsigned char) byte;
nibble=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (nibble != 0)
{
*q++=(unsigned char) (byte << 4);
x++;
}
offset=(ssize_t) (image->columns+1)/2;
for (x=offset; 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,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=(unsigned char) GetPixelIndex(image,p);
p+=GetPixelChannels(image);
}
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 16:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
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+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
unsigned short
pixel;
pixel=0;
if (bmp_subtype == ARGB4444)
{
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelAlpha(image,p),15) << 12);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),15) << 8);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),15) << 4);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),15));
}
else if (bmp_subtype == RGB565)
{
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),31) << 11);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),63) << 5);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),31));
}
else
{
if (bmp_subtype == ARGB1555)
pixel=(unsigned short) (ScaleQuantumToAny(
GetPixelAlpha(image,p),1) << 15);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelRed(image,p),31) << 10);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelGreen(image,p),31) << 5);
pixel|=(unsigned short) (ScaleQuantumToAny(
GetPixelBlue(image,p),31));
}
*((unsigned short *) q)=pixel;
q+=2;
p+=GetPixelChannels(image);
}
for (x=2L*(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 24:
{
/*
Convert DirectClass packet to BMP BGR888.
*/
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+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
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,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels+(image->rows-y-1)*bytes_per_line;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
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->alpha_trait != UndefinedPixelTrait)
(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) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width);
(void) WriteBlobLSBSignedShort(image,(signed 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) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width);
(void) WriteBlobLSBSignedLong(image,(signed 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->alpha_trait != UndefinedPixelTrait) ||
(have_color_info != MagickFalse)))
{
/*
Write the rest of the 108-byte BMP Version 4 header.
*/
(void) WriteBlobLSBLong(image,bmp_info.red_mask);
(void) WriteBlobLSBLong(image,bmp_info.green_mask);
(void) WriteBlobLSBLong(image,bmp_info.blue_mask);
(void) WriteBlobLSBLong(image,bmp_info.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(ClampToQuantum(image->colormap[i].blue));
*q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green));
*q++=ScaleQuantumToChar(ClampToQuantum(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++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_505_0 |
crossvul-cpp_data_good_2564_0 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2007 Novell, Inc.
* Copyright (C) 2008 Red Hat, Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "config.h"
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <gio/gio.h>
#include <glib/gi18n.h>
#include "gsm-xsmp-client.h"
#include "gsm-marshal.h"
#include "gsm-util.h"
#include "gsm-autostart-app.h"
#include "gsm-manager.h"
#define GsmDesktopFile "_GSM_DesktopFile"
#define IS_STRING_EMPTY(x) ((x)==NULL||(x)[0]=='\0')
#define GSM_XSMP_CLIENT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSM_TYPE_XSMP_CLIENT, GsmXSMPClientPrivate))
struct GsmXSMPClientPrivate
{
SmsConn conn;
IceConn ice_connection;
guint watch_id;
char *description;
GPtrArray *props;
/* SaveYourself state */
int current_save_yourself;
int next_save_yourself;
guint next_save_yourself_allow_interact : 1;
};
enum {
PROP_0,
PROP_ICE_CONNECTION
};
enum {
REGISTER_REQUEST,
LOGOUT_REQUEST,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
G_DEFINE_TYPE (GsmXSMPClient, gsm_xsmp_client, GSM_TYPE_CLIENT)
static gboolean
client_iochannel_watch (GIOChannel *channel,
GIOCondition condition,
GsmXSMPClient *client)
{
gboolean keep_going;
g_object_ref (client);
switch (IceProcessMessages (client->priv->ice_connection, NULL, NULL)) {
case IceProcessMessagesSuccess:
keep_going = TRUE;
break;
case IceProcessMessagesIOError:
g_debug ("GsmXSMPClient: IceProcessMessagesIOError on '%s'", client->priv->description);
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
/* Emitting "disconnected" will eventually cause
* IceCloseConnection() to be called.
*/
gsm_client_disconnected (GSM_CLIENT (client));
keep_going = FALSE;
break;
case IceProcessMessagesConnectionClosed:
g_debug ("GsmXSMPClient: IceProcessMessagesConnectionClosed on '%s'",
client->priv->description);
client->priv->ice_connection = NULL;
keep_going = FALSE;
break;
default:
g_assert_not_reached ();
}
g_object_unref (client);
return keep_going;
}
static SmProp *
find_property (GsmXSMPClient *client,
const char *name,
int *index)
{
SmProp *prop;
int i;
for (i = 0; i < client->priv->props->len; i++) {
prop = client->priv->props->pdata[i];
if (!strcmp (prop->name, name)) {
if (index) {
*index = i;
}
return prop;
}
}
return NULL;
}
static void
set_description (GsmXSMPClient *client)
{
SmProp *prop;
const char *id;
prop = find_property (client, SmProgram, NULL);
id = gsm_client_peek_startup_id (GSM_CLIENT (client));
g_free (client->priv->description);
if (prop) {
client->priv->description = g_strdup_printf ("%p [%.*s %s]",
client,
prop->vals[0].length,
(char *)prop->vals[0].value,
id);
} else if (id != NULL) {
client->priv->description = g_strdup_printf ("%p [%s]", client, id);
} else {
client->priv->description = g_strdup_printf ("%p", client);
}
}
static void
setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
static GObject *
gsm_xsmp_client_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_properties)
{
GsmXSMPClient *client;
client = GSM_XSMP_CLIENT (G_OBJECT_CLASS (gsm_xsmp_client_parent_class)->constructor (type,
n_construct_properties,
construct_properties));
setup_connection (client);
return G_OBJECT (client);
}
static void
gsm_xsmp_client_init (GsmXSMPClient *client)
{
client->priv = GSM_XSMP_CLIENT_GET_PRIVATE (client);
client->priv->props = g_ptr_array_new ();
client->priv->current_save_yourself = -1;
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = FALSE;
}
static void
delete_property (GsmXSMPClient *client,
const char *name)
{
int index;
SmProp *prop;
prop = find_property (client, name, &index);
if (!prop) {
return;
}
#if 0
/* This is wrong anyway; we can't unconditionally run the current
* discard command; if this client corresponds to a GsmAppResumed,
* and the current discard command is identical to the app's
* discard_command, then we don't run the discard command now,
* because that would delete a saved state we may want to resume
* again later.
*/
if (!strcmp (name, SmDiscardCommand)) {
gsm_client_run_discard (GSM_CLIENT (client));
}
#endif
g_ptr_array_remove_index_fast (client->priv->props, index);
SmFreeProperty (prop);
}
static void
debug_print_property (SmProp *prop)
{
GString *tmp;
int i;
switch (prop->type[0]) {
case 'C': /* CARD8 */
g_debug ("GsmXSMPClient: %s = %d", prop->name, *(unsigned char *)prop->vals[0].value);
break;
case 'A': /* ARRAY8 */
g_debug ("GsmXSMPClient: %s = '%s'", prop->name, (char *)prop->vals[0].value);
break;
case 'L': /* LISTofARRAY8 */
tmp = g_string_new (NULL);
for (i = 0; i < prop->num_vals; i++) {
g_string_append_printf (tmp, "'%.*s' ", prop->vals[i].length,
(char *)prop->vals[i].value);
}
g_debug ("GsmXSMPClient: %s = %s", prop->name, tmp->str);
g_string_free (tmp, TRUE);
break;
default:
g_debug ("GsmXSMPClient: %s = ??? (%s)", prop->name, prop->type);
break;
}
}
static void
set_properties_callback (SmsConn conn,
SmPointer manager_data,
int num_props,
SmProp **props)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Set properties from client '%s'", client->priv->description);
for (i = 0; i < num_props; i++) {
delete_property (client, props[i]->name);
g_ptr_array_add (client->priv->props, props[i]);
debug_print_property (props[i]);
if (!strcmp (props[i]->name, SmProgram))
set_description (client);
}
free (props);
}
static void
delete_properties_callback (SmsConn conn,
SmPointer manager_data,
int num_props,
char **prop_names)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Delete properties from '%s'", client->priv->description);
for (i = 0; i < num_props; i++) {
delete_property (client, prop_names[i]);
g_debug (" %s", prop_names[i]);
}
free (prop_names);
}
static void
get_properties_callback (SmsConn conn,
SmPointer manager_data)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Get properties request from '%s'", client->priv->description);
SmsReturnProperties (conn,
client->priv->props->len,
(SmProp **)client->priv->props->pdata);
}
static char *
prop_to_command (SmProp *prop)
{
GString *str;
int i, j;
gboolean need_quotes;
str = g_string_new (NULL);
for (i = 0; i < prop->num_vals; i++) {
char *val = prop->vals[i].value;
need_quotes = FALSE;
for (j = 0; j < prop->vals[i].length; j++) {
if (!g_ascii_isalnum (val[j]) && !strchr ("-_=:./", val[j])) {
need_quotes = TRUE;
break;
}
}
if (i > 0) {
g_string_append_c (str, ' ');
}
if (!need_quotes) {
g_string_append_printf (str,
"%.*s",
prop->vals[i].length,
(char *)prop->vals[i].value);
} else {
g_string_append_c (str, '\'');
while (val < (char *)prop->vals[i].value + prop->vals[i].length) {
if (*val == '\'') {
g_string_append (str, "'\''");
} else {
g_string_append_c (str, *val);
}
val++;
}
g_string_append_c (str, '\'');
}
}
return g_string_free (str, FALSE);
}
static char *
xsmp_get_restart_command (GsmClient *client)
{
SmProp *prop;
prop = find_property (GSM_XSMP_CLIENT (client), SmRestartCommand, NULL);
if (!prop || strcmp (prop->type, SmLISTofARRAY8) != 0) {
return NULL;
}
return prop_to_command (prop);
}
static char *
xsmp_get_discard_command (GsmClient *client)
{
SmProp *prop;
prop = find_property (GSM_XSMP_CLIENT (client), SmDiscardCommand, NULL);
if (!prop || strcmp (prop->type, SmLISTofARRAY8) != 0) {
return NULL;
}
return prop_to_command (prop);
}
static void
do_save_yourself (GsmXSMPClient *client,
int save_type,
gboolean allow_interact)
{
g_assert (client->priv->conn != NULL);
if (client->priv->next_save_yourself != -1) {
/* Either we're currently doing a shutdown and there's a checkpoint
* queued after it, or vice versa. Either way, the new SaveYourself
* is redundant.
*/
g_debug ("GsmXSMPClient: skipping redundant SaveYourself for '%s'",
client->priv->description);
} else if (client->priv->current_save_yourself != -1) {
g_debug ("GsmXSMPClient: queuing new SaveYourself for '%s'",
client->priv->description);
client->priv->next_save_yourself = save_type;
client->priv->next_save_yourself_allow_interact = allow_interact;
} else {
client->priv->current_save_yourself = save_type;
/* make sure we don't have anything queued */
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = FALSE;
switch (save_type) {
case SmSaveLocal:
/* Save state */
SmsSaveYourself (client->priv->conn,
SmSaveLocal,
FALSE,
SmInteractStyleNone,
FALSE);
break;
default:
/* Logout */
if (!allow_interact) {
SmsSaveYourself (client->priv->conn,
save_type, /* save type */
TRUE, /* shutdown */
SmInteractStyleNone, /* interact style */
TRUE); /* fast */
} else {
SmsSaveYourself (client->priv->conn,
save_type, /* save type */
TRUE, /* shutdown */
SmInteractStyleAny, /* interact style */
FALSE /* fast */);
}
break;
}
}
}
static void
xsmp_save_yourself_phase2 (GsmClient *client)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_save_yourself_phase2 ('%s')", xsmp->priv->description);
SmsSaveYourselfPhase2 (xsmp->priv->conn);
}
static void
xsmp_interact (GsmClient *client)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_interact ('%s')", xsmp->priv->description);
SmsInteract (xsmp->priv->conn);
}
static gboolean
xsmp_cancel_end_session (GsmClient *client,
GError **error)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_cancel_end_session ('%s')", xsmp->priv->description);
if (xsmp->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
SmsShutdownCancelled (xsmp->priv->conn);
/* reset the state */
xsmp->priv->current_save_yourself = -1;
xsmp->priv->next_save_yourself = -1;
xsmp->priv->next_save_yourself_allow_interact = FALSE;
return TRUE;
}
static char *
get_desktop_file_path (GsmXSMPClient *client)
{
SmProp *prop;
char *desktop_file_path = NULL;
char **dirs;
const char *program_name;
/* XSMP clients using eggsmclient defines a special property
* pointing to their respective desktop entry file */
prop = find_property (client, GsmDesktopFile, NULL);
if (prop) {
GFile *file = g_file_new_for_uri (prop->vals[0].value);
desktop_file_path = g_file_get_path (file);
g_object_unref (file);
goto out;
}
/* If we can't get desktop file from GsmDesktopFile then we
* try to find the desktop file from its program name */
prop = find_property (client, SmProgram, NULL);
program_name = prop->vals[0].value;
dirs = gsm_util_get_autostart_dirs ();
desktop_file_path =
gsm_util_find_desktop_file_for_app_name (program_name,
dirs);
g_strfreev (dirs);
out:
g_debug ("GsmXSMPClient: desktop file for client %s is %s",
gsm_client_peek_id (GSM_CLIENT (client)),
desktop_file_path ? desktop_file_path : "(null)");
return desktop_file_path;
}
static void
set_desktop_file_keys_from_client (GsmClient *client,
GKeyFile *keyfile)
{
SmProp *prop;
char *name;
char *comment;
prop = find_property (GSM_XSMP_CLIENT (client), SmProgram, NULL);
name = g_strdup (prop->vals[0].value);
comment = g_strdup_printf ("Client %s which was automatically saved",
gsm_client_peek_startup_id (client));
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_NAME,
name);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_COMMENT,
comment);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_ICON,
"system-run");
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_TYPE,
"Application");
g_key_file_set_boolean (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY,
TRUE);
g_free (name);
g_free (comment);
}
static GKeyFile *
create_client_key_file (GsmClient *client,
const char *desktop_file_path,
GError **error) {
GKeyFile *keyfile;
keyfile = g_key_file_new ();
if (desktop_file_path != NULL) {
g_key_file_load_from_file (keyfile,
desktop_file_path,
G_KEY_FILE_KEEP_COMMENTS |
G_KEY_FILE_KEEP_TRANSLATIONS,
error);
} else {
set_desktop_file_keys_from_client (client, keyfile);
}
return keyfile;
}
static GsmClientRestartStyle
xsmp_get_restart_style_hint (GsmClient *client);
static GKeyFile *
xsmp_save (GsmClient *client,
GError **error)
{
GsmClientRestartStyle restart_style;
GKeyFile *keyfile = NULL;
char *desktop_file_path = NULL;
char *exec_program = NULL;
char *exec_discard = NULL;
char *startup_id = NULL;
GError *local_error;
g_debug ("GsmXSMPClient: saving client with id %s",
gsm_client_peek_id (client));
local_error = NULL;
restart_style = xsmp_get_restart_style_hint (client);
if (restart_style == GSM_CLIENT_RESTART_NEVER) {
goto out;
}
exec_program = xsmp_get_restart_command (client);
if (!exec_program) {
goto out;
}
desktop_file_path = get_desktop_file_path (GSM_XSMP_CLIENT (client));
keyfile = create_client_key_file (client,
desktop_file_path,
&local_error);
if (local_error) {
goto out;
}
g_object_get (client,
"startup-id", &startup_id,
NULL);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
GSM_AUTOSTART_APP_STARTUP_ID_KEY,
startup_id);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_EXEC,
exec_program);
exec_discard = xsmp_get_discard_command (client);
if (exec_discard)
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
GSM_AUTOSTART_APP_DISCARD_KEY,
exec_discard);
out:
g_free (desktop_file_path);
g_free (exec_program);
g_free (exec_discard);
g_free (startup_id);
if (local_error != NULL) {
g_propagate_error (error, local_error);
g_key_file_free (keyfile);
return NULL;
}
return keyfile;
}
static gboolean
xsmp_stop (GsmClient *client,
GError **error)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_stop ('%s')", xsmp->priv->description);
if (xsmp->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
SmsDie (xsmp->priv->conn);
return TRUE;
}
static gboolean
xsmp_query_end_session (GsmClient *client,
guint flags,
GError **error)
{
gboolean allow_interact;
int save_type;
if (GSM_XSMP_CLIENT (client)->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
allow_interact = !(flags & GSM_CLIENT_END_SESSION_FLAG_FORCEFUL);
/* we don't want to save the session state, but we just want to know if
* there's user data the client has to save and we want to give the
* client a chance to tell the user about it. This is consistent with
* the manager not setting GSM_CLIENT_END_SESSION_FLAG_SAVE for this
* phase. */
save_type = SmSaveGlobal;
do_save_yourself (GSM_XSMP_CLIENT (client), save_type, allow_interact);
return TRUE;
}
static gboolean
xsmp_end_session (GsmClient *client,
guint flags,
GError **error)
{
gboolean phase2;
if (GSM_XSMP_CLIENT (client)->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
phase2 = (flags & GSM_CLIENT_END_SESSION_FLAG_LAST);
if (phase2) {
xsmp_save_yourself_phase2 (client);
} else {
gboolean allow_interact;
int save_type;
/* we gave a chance to interact to the app during
* xsmp_query_end_session(), now it's too late to interact */
allow_interact = FALSE;
if (flags & GSM_CLIENT_END_SESSION_FLAG_SAVE) {
save_type = SmSaveBoth;
} else {
save_type = SmSaveGlobal;
}
do_save_yourself (GSM_XSMP_CLIENT (client),
save_type, allow_interact);
}
return TRUE;
}
static char *
xsmp_get_app_name (GsmClient *client)
{
SmProp *prop;
char *name;
prop = find_property (GSM_XSMP_CLIENT (client), SmProgram, NULL);
name = prop_to_command (prop);
return name;
}
static void
gsm_client_set_ice_connection (GsmXSMPClient *client,
gpointer conn)
{
client->priv->ice_connection = conn;
}
static void
gsm_xsmp_client_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsmXSMPClient *self;
self = GSM_XSMP_CLIENT (object);
switch (prop_id) {
case PROP_ICE_CONNECTION:
gsm_client_set_ice_connection (self, g_value_get_pointer (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_client_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GsmXSMPClient *self;
self = GSM_XSMP_CLIENT (object);
switch (prop_id) {
case PROP_ICE_CONNECTION:
g_value_set_pointer (value, self->priv->ice_connection);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
}
static void
gsm_xsmp_client_finalize (GObject *object)
{
GsmXSMPClient *client = (GsmXSMPClient *) object;
g_debug ("GsmXSMPClient: xsmp_finalize (%s)", client->priv->description);
gsm_xsmp_client_disconnect (client);
g_free (client->priv->description);
g_ptr_array_foreach (client->priv->props, (GFunc)SmFreeProperty, NULL);
g_ptr_array_free (client->priv->props, TRUE);
G_OBJECT_CLASS (gsm_xsmp_client_parent_class)->finalize (object);
}
static gboolean
_boolean_handled_accumulator (GSignalInvocationHint *ihint,
GValue *return_accu,
const GValue *handler_return,
gpointer dummy)
{
gboolean continue_emission;
gboolean signal_handled;
signal_handled = g_value_get_boolean (handler_return);
g_value_set_boolean (return_accu, signal_handled);
continue_emission = !signal_handled;
return continue_emission;
}
static GsmClientRestartStyle
xsmp_get_restart_style_hint (GsmClient *client)
{
SmProp *prop;
GsmClientRestartStyle hint;
g_debug ("GsmXSMPClient: getting restart style");
hint = GSM_CLIENT_RESTART_IF_RUNNING;
prop = find_property (GSM_XSMP_CLIENT (client), SmRestartStyleHint, NULL);
if (!prop || strcmp (prop->type, SmCARD8) != 0) {
return GSM_CLIENT_RESTART_IF_RUNNING;
}
switch (((unsigned char *)prop->vals[0].value)[0]) {
case SmRestartIfRunning:
hint = GSM_CLIENT_RESTART_IF_RUNNING;
break;
case SmRestartAnyway:
hint = GSM_CLIENT_RESTART_ANYWAY;
break;
case SmRestartImmediately:
hint = GSM_CLIENT_RESTART_IMMEDIATELY;
break;
case SmRestartNever:
hint = GSM_CLIENT_RESTART_NEVER;
break;
default:
break;
}
return hint;
}
static gboolean
_parse_value_as_uint (const char *value,
guint *uintval)
{
char *end_of_valid_uint;
gulong ulong_value;
guint uint_value;
errno = 0;
ulong_value = strtoul (value, &end_of_valid_uint, 10);
if (*value == '\0' || *end_of_valid_uint != '\0') {
return FALSE;
}
uint_value = ulong_value;
if (uint_value != ulong_value || errno == ERANGE) {
return FALSE;
}
*uintval = uint_value;
return TRUE;
}
static guint
xsmp_get_unix_process_id (GsmClient *client)
{
SmProp *prop;
guint pid;
gboolean res;
g_debug ("GsmXSMPClient: getting pid");
prop = find_property (GSM_XSMP_CLIENT (client), SmProcessID, NULL);
if (!prop || strcmp (prop->type, SmARRAY8) != 0) {
return 0;
}
pid = 0;
res = _parse_value_as_uint ((char *)prop->vals[0].value, &pid);
if (! res) {
pid = 0;
}
return pid;
}
static void
gsm_xsmp_client_class_init (GsmXSMPClientClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GsmClientClass *client_class = GSM_CLIENT_CLASS (klass);
object_class->finalize = gsm_xsmp_client_finalize;
object_class->constructor = gsm_xsmp_client_constructor;
object_class->get_property = gsm_xsmp_client_get_property;
object_class->set_property = gsm_xsmp_client_set_property;
client_class->impl_save = xsmp_save;
client_class->impl_stop = xsmp_stop;
client_class->impl_query_end_session = xsmp_query_end_session;
client_class->impl_end_session = xsmp_end_session;
client_class->impl_cancel_end_session = xsmp_cancel_end_session;
client_class->impl_get_app_name = xsmp_get_app_name;
client_class->impl_get_restart_style_hint = xsmp_get_restart_style_hint;
client_class->impl_get_unix_process_id = xsmp_get_unix_process_id;
signals[REGISTER_REQUEST] =
g_signal_new ("register-request",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GsmXSMPClientClass, register_request),
_boolean_handled_accumulator,
NULL,
gsm_marshal_BOOLEAN__POINTER,
G_TYPE_BOOLEAN,
1, G_TYPE_POINTER);
signals[LOGOUT_REQUEST] =
g_signal_new ("logout-request",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GsmXSMPClientClass, logout_request),
NULL,
NULL,
g_cclosure_marshal_VOID__BOOLEAN,
G_TYPE_NONE,
1, G_TYPE_BOOLEAN);
g_object_class_install_property (object_class,
PROP_ICE_CONNECTION,
g_param_spec_pointer ("ice-connection",
"ice-connection",
"ice-connection",
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass, sizeof (GsmXSMPClientPrivate));
}
GsmClient *
gsm_xsmp_client_new (IceConn ice_conn)
{
GsmXSMPClient *xsmp;
xsmp = g_object_new (GSM_TYPE_XSMP_CLIENT,
"ice-connection", ice_conn,
NULL);
return GSM_CLIENT (xsmp);
}
static Status
register_client_callback (SmsConn conn,
SmPointer manager_data,
char *previous_id)
{
GsmXSMPClient *client = manager_data;
gboolean handled;
char *id;
g_debug ("GsmXSMPClient: Client '%s' received RegisterClient(%s)",
client->priv->description,
previous_id ? previous_id : "NULL");
/* There are three cases:
* 1. id is NULL - we'll use a new one
* 2. id is known - we'll use known one
* 3. id is unknown - this is an error
*/
id = g_strdup (previous_id);
handled = FALSE;
g_signal_emit (client, signals[REGISTER_REQUEST], 0, &id, &handled);
if (! handled) {
g_debug ("GsmXSMPClient: RegisterClient not handled!");
g_free (id);
free (previous_id);
g_assert_not_reached ();
return FALSE;
}
if (IS_STRING_EMPTY (id)) {
g_debug ("GsmXSMPClient: rejected: invalid previous_id");
free (previous_id);
return FALSE;
}
g_object_set (client, "startup-id", id, NULL);
set_description (client);
g_debug ("GsmXSMPClient: Sending RegisterClientReply to '%s'", client->priv->description);
SmsRegisterClientReply (conn, id);
if (IS_STRING_EMPTY (previous_id)) {
/* Send the initial SaveYourself. */
g_debug ("GsmXSMPClient: Sending initial SaveYourself");
SmsSaveYourself (conn, SmSaveLocal, False, SmInteractStyleNone, False);
client->priv->current_save_yourself = SmSaveLocal;
}
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_REGISTERED);
g_free (id);
free (previous_id);
return TRUE;
}
static void
save_yourself_request_callback (SmsConn conn,
SmPointer manager_data,
int save_type,
Bool shutdown,
int interact_style,
Bool fast,
Bool global)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfRequest(%s, %s, %s, %s, %s)",
client->priv->description,
save_type == SmSaveLocal ? "SmSaveLocal" :
save_type == SmSaveGlobal ? "SmSaveGlobal" : "SmSaveBoth",
shutdown ? "Shutdown" : "!Shutdown",
interact_style == SmInteractStyleAny ? "SmInteractStyleAny" :
interact_style == SmInteractStyleErrors ? "SmInteractStyleErrors" :
"SmInteractStyleNone", fast ? "Fast" : "!Fast",
global ? "Global" : "!Global");
/* Examining the g_debug above, you can see that there are a total
* of 72 different combinations of options that this could have been
* called with. However, most of them are stupid.
*
* If @shutdown and @global are both TRUE, that means the caller is
* requesting that a logout message be sent to all clients, so we do
* that. We use @fast to decide whether or not to show a
* confirmation dialog. (This isn't really what @fast is for, but
* the old gnome-session and ksmserver both interpret it that way,
* so we do too.) We ignore @save_type because we pick the correct
* save_type ourselves later based on user prefs, dialog choices,
* etc, and we ignore @interact_style, because clients have not used
* it correctly consistently enough to make it worth honoring.
*
* If @shutdown is TRUE and @global is FALSE, the caller is
* confused, so we ignore the request.
*
* If @shutdown is FALSE and @save_type is SmSaveGlobal or
* SmSaveBoth, then the client wants us to ask some or all open
* applications to save open files to disk, but NOT quit. This is
* silly and so we ignore the request.
*
* If @shutdown is FALSE and @save_type is SmSaveLocal, then the
* client wants us to ask some or all open applications to update
* their current saved state, but not log out. At the moment, the
* code only supports this for the !global case (ie, a client
* requesting that it be allowed to update *its own* saved state,
* but not having everyone else update their saved state).
*/
if (shutdown && global) {
g_debug ("GsmXSMPClient: initiating shutdown");
g_signal_emit (client, signals[LOGOUT_REQUEST], 0, !fast);
} else if (!shutdown && !global) {
g_debug ("GsmXSMPClient: initiating checkpoint");
do_save_yourself (client, SmSaveLocal, TRUE);
} else {
g_debug ("GsmXSMPClient: ignoring");
}
}
static void
save_yourself_phase2_request_callback (SmsConn conn,
SmPointer manager_data)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfPhase2Request",
client->priv->description);
client->priv->current_save_yourself = -1;
/* this is a valid response to SaveYourself and therefore
may be a response to a QES or ES */
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, TRUE, FALSE,
NULL);
}
static void
interact_request_callback (SmsConn conn,
SmPointer manager_data,
int dialog_type)
{
GsmXSMPClient *client = manager_data;
#if 0
gboolean res;
GError *error;
#endif
g_debug ("GsmXSMPClient: Client '%s' received InteractRequest(%s)",
client->priv->description,
dialog_type == SmDialogNormal ? "Dialog" : "Errors");
gsm_client_end_session_response (GSM_CLIENT (client),
FALSE, FALSE, FALSE,
_("This program is blocking log out."));
#if 0
/* Can't just call back with Interact because session client
grabs the keyboard! So, we try to get it to release
grabs by telling it we've cancelled the shutdown.
This grabbing is clearly bullshit and is not supported by
the client spec or protocol spec.
*/
res = xsmp_cancel_end_session (GSM_CLIENT (client), &error);
if (! res) {
g_warning ("Unable to cancel end session: %s", error->message);
g_error_free (error);
}
#endif
xsmp_interact (GSM_CLIENT (client));
}
static void
interact_done_callback (SmsConn conn,
SmPointer manager_data,
Bool cancel_shutdown)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received InteractDone(cancel_shutdown = %s)",
client->priv->description,
cancel_shutdown ? "True" : "False");
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, FALSE, cancel_shutdown,
NULL);
}
static void
save_yourself_done_callback (SmsConn conn,
SmPointer manager_data,
Bool success)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfDone(success = %s)",
client->priv->description,
success ? "True" : "False");
if (client->priv->current_save_yourself != -1) {
SmsSaveComplete (client->priv->conn);
client->priv->current_save_yourself = -1;
}
/* If success is false then the application couldn't save data. Nothing
* the session manager can do about, though. FIXME: we could display a
* dialog about this, I guess. */
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, FALSE, FALSE,
NULL);
if (client->priv->next_save_yourself) {
int save_type = client->priv->next_save_yourself;
gboolean allow_interact = client->priv->next_save_yourself_allow_interact;
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = -1;
do_save_yourself (client, save_type, allow_interact);
}
}
static void
close_connection_callback (SmsConn conn,
SmPointer manager_data,
int count,
char **reason_msgs)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Client '%s' received CloseConnection", client->priv->description);
for (i = 0; i < count; i++) {
g_debug ("GsmXSMPClient: close reason: '%s'", reason_msgs[i]);
}
SmFreeReasons (count, reason_msgs);
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FINISHED);
gsm_client_disconnected (GSM_CLIENT (client));
}
void
gsm_xsmp_client_connect (GsmXSMPClient *client,
SmsConn conn,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret)
{
client->priv->conn = conn;
g_debug ("GsmXSMPClient: Initializing client %s", client->priv->description);
*mask_ret = 0;
*mask_ret |= SmsRegisterClientProcMask;
callbacks_ret->register_client.callback = register_client_callback;
callbacks_ret->register_client.manager_data = client;
*mask_ret |= SmsInteractRequestProcMask;
callbacks_ret->interact_request.callback = interact_request_callback;
callbacks_ret->interact_request.manager_data = client;
*mask_ret |= SmsInteractDoneProcMask;
callbacks_ret->interact_done.callback = interact_done_callback;
callbacks_ret->interact_done.manager_data = client;
*mask_ret |= SmsSaveYourselfRequestProcMask;
callbacks_ret->save_yourself_request.callback = save_yourself_request_callback;
callbacks_ret->save_yourself_request.manager_data = client;
*mask_ret |= SmsSaveYourselfP2RequestProcMask;
callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback;
callbacks_ret->save_yourself_phase2_request.manager_data = client;
*mask_ret |= SmsSaveYourselfDoneProcMask;
callbacks_ret->save_yourself_done.callback = save_yourself_done_callback;
callbacks_ret->save_yourself_done.manager_data = client;
*mask_ret |= SmsCloseConnectionProcMask;
callbacks_ret->close_connection.callback = close_connection_callback;
callbacks_ret->close_connection.manager_data = client;
*mask_ret |= SmsSetPropertiesProcMask;
callbacks_ret->set_properties.callback = set_properties_callback;
callbacks_ret->set_properties.manager_data = client;
*mask_ret |= SmsDeletePropertiesProcMask;
callbacks_ret->delete_properties.callback = delete_properties_callback;
callbacks_ret->delete_properties.manager_data = client;
*mask_ret |= SmsGetPropertiesProcMask;
callbacks_ret->get_properties.callback = get_properties_callback;
callbacks_ret->get_properties.manager_data = client;
}
void
gsm_xsmp_client_save_state (GsmXSMPClient *client)
{
g_return_if_fail (GSM_IS_XSMP_CLIENT (client));
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2564_0 |
crossvul-cpp_data_bad_2585_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.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/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/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MaxTextExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p,
text[MaxTextExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++) ;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("SPARSE-COLOR");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Sparse Color");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TEXT");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Text");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TXT");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->description=ConstantString("Text");
entry->magick=(IsImageFormatHandler *) IsTXT;
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
colorspace[MaxTextExtent],
tuple[MaxTextExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
/*
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,WriteBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MaxTextExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->matte != MagickFalse)
(void) ConcatenateMagickString(colorspace,"a",MaxTextExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MaxTextExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetMagickPixelPacket(image,&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);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelOpacity(p) == (Quantum) OpaqueOpacity)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g,",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p++;
continue;
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g: ",(double)
x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MaxTextExtent);
ConcatenateColorComponent(&pixel,RedChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,GreenChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,BlueChannel,compliance,tuple);
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,IndexChannel,compliance,tuple);
}
if (pixel.matte != MagickFalse)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,AlphaChannel,compliance,tuple);
}
(void) ConcatenateMagickString(tuple,")",MaxTextExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MaxTextExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p++;
}
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-835/c/bad_2585_0 |
crossvul-cpp_data_bad_2668_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Domain Name System (DNS) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "nameser.h"
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "extract.h"
static const char *ns_ops[] = {
"", " inv_q", " stat", " op3", " notify", " update", " op6", " op7",
" op8", " updateA", " updateD", " updateDA",
" updateM", " updateMA", " zoneInit", " zoneRef",
};
static const char *ns_resp[] = {
"", " FormErr", " ServFail", " NXDomain",
" NotImp", " Refused", " YXDomain", " YXRRSet",
" NXRRSet", " NotAuth", " NotZone", " Resp11",
" Resp12", " Resp13", " Resp14", " NoChange",
};
/* skip over a domain name */
static const u_char *
ns_nskip(netdissect_options *ndo,
register const u_char *cp)
{
register u_char i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
while (i) {
if ((i & INDIR_MASK) == INDIR_MASK)
return (cp + 1);
if ((i & INDIR_MASK) == EDNS0_MASK) {
int bitlen, bytelen;
if ((i & ~INDIR_MASK) != EDNS0_ELT_BITLABEL)
return(NULL); /* unknown ELT */
if (!ND_TTEST2(*cp, 1))
return (NULL);
if ((bitlen = *cp++) == 0)
bitlen = 256;
bytelen = (bitlen + 7) / 8;
cp += bytelen;
} else
cp += i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
}
return (cp);
}
/* print a <domain-name> */
static const u_char *
blabel_print(netdissect_options *ndo,
const u_char *cp)
{
int bitlen, slen, b;
const u_char *bitp, *lim;
char tc;
if (!ND_TTEST2(*cp, 1))
return(NULL);
if ((bitlen = *cp) == 0)
bitlen = 256;
slen = (bitlen + 3) / 4;
lim = cp + 1 + slen;
/* print the bit string as a hex string */
ND_PRINT((ndo, "\\[x"));
for (bitp = cp + 1, b = bitlen; bitp < lim && b > 7; b -= 8, bitp++) {
ND_TCHECK(*bitp);
ND_PRINT((ndo, "%02x", *bitp));
}
if (b > 4) {
ND_TCHECK(*bitp);
tc = *bitp++;
ND_PRINT((ndo, "%02x", tc & (0xff << (8 - b))));
} else if (b > 0) {
ND_TCHECK(*bitp);
tc = *bitp++;
ND_PRINT((ndo, "%1x", ((tc >> 4) & 0x0f) & (0x0f << (4 - b))));
}
ND_PRINT((ndo, "/%d]", bitlen));
return lim;
trunc:
ND_PRINT((ndo, ".../%d]", bitlen));
return NULL;
}
static int
labellen(netdissect_options *ndo,
const u_char *cp)
{
register u_int i;
if (!ND_TTEST2(*cp, 1))
return(-1);
i = *cp;
if ((i & INDIR_MASK) == EDNS0_MASK) {
int bitlen, elt;
if ((elt = (i & ~INDIR_MASK)) != EDNS0_ELT_BITLABEL) {
ND_PRINT((ndo, "<ELT %d>", elt));
return(-1);
}
if (!ND_TTEST2(*(cp + 1), 1))
return(-1);
if ((bitlen = *(cp + 1)) == 0)
bitlen = 256;
return(((bitlen + 7) / 8) + 1);
} else
return(i);
}
const u_char *
ns_nprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp)
{
register u_int i, l;
register const u_char *rp = NULL;
register int compress = 0;
int chars_processed;
int elt;
int data_size = ndo->ndo_snapend - bp;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
chars_processed = 1;
if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) {
compress = 0;
rp = cp + l;
}
if (i != 0)
while (i && cp < ndo->ndo_snapend) {
if ((i & INDIR_MASK) == INDIR_MASK) {
if (!compress) {
rp = cp + 1;
compress = 1;
}
if (!ND_TTEST2(*cp, 1))
return(NULL);
cp = bp + (((i << 8) | *cp) & 0x3fff);
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
/*
* If we've looked at every character in
* the message, this pointer will make
* us look at some character again,
* which means we're looping.
*/
if (chars_processed >= data_size) {
ND_PRINT((ndo, "<LOOP>"));
return (NULL);
}
continue;
}
if ((i & INDIR_MASK) == EDNS0_MASK) {
elt = (i & ~INDIR_MASK);
switch(elt) {
case EDNS0_ELT_BITLABEL:
if (blabel_print(ndo, cp) == NULL)
return (NULL);
break;
default:
/* unknown ELT */
ND_PRINT((ndo, "<ELT %d>", elt));
return(NULL);
}
} else {
if (fn_printn(ndo, cp, l, ndo->ndo_snapend))
return(NULL);
}
cp += l;
chars_processed += l;
ND_PRINT((ndo, "."));
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
if (!compress)
rp += l + 1;
}
else
ND_PRINT((ndo, "."));
return (rp);
}
/* print a <character-string> */
static const u_char *
ns_cprint(netdissect_options *ndo,
register const u_char *cp)
{
register u_int i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
if (fn_printn(ndo, cp, i, ndo->ndo_snapend))
return (NULL);
return (cp + i);
}
/* http://www.iana.org/assignments/dns-parameters */
const struct tok ns_type2str[] = {
{ T_A, "A" }, /* RFC 1035 */
{ T_NS, "NS" }, /* RFC 1035 */
{ T_MD, "MD" }, /* RFC 1035 */
{ T_MF, "MF" }, /* RFC 1035 */
{ T_CNAME, "CNAME" }, /* RFC 1035 */
{ T_SOA, "SOA" }, /* RFC 1035 */
{ T_MB, "MB" }, /* RFC 1035 */
{ T_MG, "MG" }, /* RFC 1035 */
{ T_MR, "MR" }, /* RFC 1035 */
{ T_NULL, "NULL" }, /* RFC 1035 */
{ T_WKS, "WKS" }, /* RFC 1035 */
{ T_PTR, "PTR" }, /* RFC 1035 */
{ T_HINFO, "HINFO" }, /* RFC 1035 */
{ T_MINFO, "MINFO" }, /* RFC 1035 */
{ T_MX, "MX" }, /* RFC 1035 */
{ T_TXT, "TXT" }, /* RFC 1035 */
{ T_RP, "RP" }, /* RFC 1183 */
{ T_AFSDB, "AFSDB" }, /* RFC 1183 */
{ T_X25, "X25" }, /* RFC 1183 */
{ T_ISDN, "ISDN" }, /* RFC 1183 */
{ T_RT, "RT" }, /* RFC 1183 */
{ T_NSAP, "NSAP" }, /* RFC 1706 */
{ T_NSAP_PTR, "NSAP_PTR" },
{ T_SIG, "SIG" }, /* RFC 2535 */
{ T_KEY, "KEY" }, /* RFC 2535 */
{ T_PX, "PX" }, /* RFC 2163 */
{ T_GPOS, "GPOS" }, /* RFC 1712 */
{ T_AAAA, "AAAA" }, /* RFC 1886 */
{ T_LOC, "LOC" }, /* RFC 1876 */
{ T_NXT, "NXT" }, /* RFC 2535 */
{ T_EID, "EID" }, /* Nimrod */
{ T_NIMLOC, "NIMLOC" }, /* Nimrod */
{ T_SRV, "SRV" }, /* RFC 2782 */
{ T_ATMA, "ATMA" }, /* ATM Forum */
{ T_NAPTR, "NAPTR" }, /* RFC 2168, RFC 2915 */
{ T_KX, "KX" }, /* RFC 2230 */
{ T_CERT, "CERT" }, /* RFC 2538 */
{ T_A6, "A6" }, /* RFC 2874 */
{ T_DNAME, "DNAME" }, /* RFC 2672 */
{ T_SINK, "SINK" },
{ T_OPT, "OPT" }, /* RFC 2671 */
{ T_APL, "APL" }, /* RFC 3123 */
{ T_DS, "DS" }, /* RFC 4034 */
{ T_SSHFP, "SSHFP" }, /* RFC 4255 */
{ T_IPSECKEY, "IPSECKEY" }, /* RFC 4025 */
{ T_RRSIG, "RRSIG" }, /* RFC 4034 */
{ T_NSEC, "NSEC" }, /* RFC 4034 */
{ T_DNSKEY, "DNSKEY" }, /* RFC 4034 */
{ T_SPF, "SPF" }, /* RFC-schlitt-spf-classic-02.txt */
{ T_UINFO, "UINFO" },
{ T_UID, "UID" },
{ T_GID, "GID" },
{ T_UNSPEC, "UNSPEC" },
{ T_UNSPECA, "UNSPECA" },
{ T_TKEY, "TKEY" }, /* RFC 2930 */
{ T_TSIG, "TSIG" }, /* RFC 2845 */
{ T_IXFR, "IXFR" }, /* RFC 1995 */
{ T_AXFR, "AXFR" }, /* RFC 1035 */
{ T_MAILB, "MAILB" }, /* RFC 1035 */
{ T_MAILA, "MAILA" }, /* RFC 1035 */
{ T_ANY, "ANY" },
{ 0, NULL }
};
const struct tok ns_class2str[] = {
{ C_IN, "IN" }, /* Not used */
{ C_CHAOS, "CHAOS" },
{ C_HS, "HS" },
{ C_ANY, "ANY" },
{ 0, NULL }
};
/* print a query */
static const u_char *
ns_qprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp, int is_mdns)
{
register const u_char *np = cp;
register u_int i, class;
cp = ns_nskip(ndo, cp);
if (cp == NULL || !ND_TTEST2(*cp, 4))
return(NULL);
/* print the qtype */
i = EXTRACT_16BITS(cp);
cp += 2;
ND_PRINT((ndo, " %s", tok2str(ns_type2str, "Type%d", i)));
/* print the qclass (if it's not IN) */
i = EXTRACT_16BITS(cp);
cp += 2;
if (is_mdns)
class = (i & ~C_QU);
else
class = i;
if (class != C_IN)
ND_PRINT((ndo, " %s", tok2str(ns_class2str, "(Class %d)", class)));
if (is_mdns) {
ND_PRINT((ndo, i & C_QU ? " (QU)" : " (QM)"));
}
ND_PRINT((ndo, "? "));
cp = ns_nprint(ndo, np, bp);
return(cp ? cp + 4 : NULL);
}
/* print a reply */
static const u_char *
ns_rprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp, int is_mdns)
{
register u_int i, class, opt_flags = 0;
register u_short typ, len;
register const u_char *rp;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return NULL;
} else
cp = ns_nskip(ndo, cp);
if (cp == NULL || !ND_TTEST2(*cp, 10))
return (ndo->ndo_snapend);
/* print the type/qtype */
typ = EXTRACT_16BITS(cp);
cp += 2;
/* print the class (if it's not IN and the type isn't OPT) */
i = EXTRACT_16BITS(cp);
cp += 2;
if (is_mdns)
class = (i & ~C_CACHE_FLUSH);
else
class = i;
if (class != C_IN && typ != T_OPT)
ND_PRINT((ndo, " %s", tok2str(ns_class2str, "(Class %d)", class)));
if (is_mdns) {
if (i & C_CACHE_FLUSH)
ND_PRINT((ndo, " (Cache flush)"));
}
if (typ == T_OPT) {
/* get opt flags */
cp += 2;
opt_flags = EXTRACT_16BITS(cp);
/* ignore rest of ttl field */
cp += 2;
} else if (ndo->ndo_vflag > 2) {
/* print ttl */
ND_PRINT((ndo, " ["));
unsigned_relts_print(ndo, EXTRACT_32BITS(cp));
ND_PRINT((ndo, "]"));
cp += 4;
} else {
/* ignore ttl */
cp += 4;
}
len = EXTRACT_16BITS(cp);
cp += 2;
rp = cp + len;
ND_PRINT((ndo, " %s", tok2str(ns_type2str, "Type%d", typ)));
if (rp > ndo->ndo_snapend)
return(NULL);
switch (typ) {
case T_A:
if (!ND_TTEST2(*cp, sizeof(struct in_addr)))
return(NULL);
ND_PRINT((ndo, " %s", intoa(htonl(EXTRACT_32BITS(cp)))));
break;
case T_NS:
case T_CNAME:
case T_PTR:
#ifdef T_DNAME
case T_DNAME:
#endif
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, cp, bp) == NULL)
return(NULL);
break;
case T_SOA:
if (!ndo->ndo_vflag)
break;
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
if (!ND_TTEST2(*cp, 5 * 4))
return(NULL);
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
break;
case T_MX:
ND_PRINT((ndo, " "));
if (!ND_TTEST2(*cp, 2))
return(NULL);
if (ns_nprint(ndo, cp + 2, bp) == NULL)
return(NULL);
ND_PRINT((ndo, " %d", EXTRACT_16BITS(cp)));
break;
case T_TXT:
while (cp < rp) {
ND_PRINT((ndo, " \""));
cp = ns_cprint(ndo, cp);
if (cp == NULL)
return(NULL);
ND_PRINT((ndo, "\""));
}
break;
case T_SRV:
ND_PRINT((ndo, " "));
if (!ND_TTEST2(*cp, 6))
return(NULL);
if (ns_nprint(ndo, cp + 6, bp) == NULL)
return(NULL);
ND_PRINT((ndo, ":%d %d %d", EXTRACT_16BITS(cp + 4),
EXTRACT_16BITS(cp), EXTRACT_16BITS(cp + 2)));
break;
case T_AAAA:
{
char ntop_buf[INET6_ADDRSTRLEN];
if (!ND_TTEST2(*cp, sizeof(struct in6_addr)))
return(NULL);
ND_PRINT((ndo, " %s",
addrtostr6(cp, ntop_buf, sizeof(ntop_buf))));
break;
}
case T_A6:
{
struct in6_addr a;
int pbit, pbyte;
char ntop_buf[INET6_ADDRSTRLEN];
if (!ND_TTEST2(*cp, 1))
return(NULL);
pbit = *cp;
pbyte = (pbit & ~7) / 8;
if (pbit > 128) {
ND_PRINT((ndo, " %u(bad plen)", pbit));
break;
} else if (pbit < 128) {
if (!ND_TTEST2(*(cp + 1), sizeof(a) - pbyte))
return(NULL);
memset(&a, 0, sizeof(a));
memcpy(&a.s6_addr[pbyte], cp + 1, sizeof(a) - pbyte);
ND_PRINT((ndo, " %u %s", pbit,
addrtostr6(&a, ntop_buf, sizeof(ntop_buf))));
}
if (pbit > 0) {
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, cp + 1 + sizeof(a) - pbyte, bp) == NULL)
return(NULL);
}
break;
}
case T_OPT:
ND_PRINT((ndo, " UDPsize=%u", class));
if (opt_flags & 0x8000)
ND_PRINT((ndo, " DO"));
break;
case T_UNSPECA: /* One long string */
if (!ND_TTEST2(*cp, len))
return(NULL);
if (fn_printn(ndo, cp, len, ndo->ndo_snapend))
return(NULL);
break;
case T_TSIG:
{
if (cp + len > ndo->ndo_snapend)
return(NULL);
if (!ndo->ndo_vflag)
break;
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
cp += 6;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " fudge=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " maclen=%u", EXTRACT_16BITS(cp)));
cp += 2 + EXTRACT_16BITS(cp);
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " origid=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " error=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " otherlen=%u", EXTRACT_16BITS(cp)));
cp += 2;
}
}
return (rp); /* XXX This isn't always right */
}
void
ns_print(netdissect_options *ndo,
register const u_char *bp, u_int length, int is_mdns)
{
register const HEADER *np;
register int qdcount, ancount, nscount, arcount;
register const u_char *cp;
uint16_t b2;
np = (const HEADER *)bp;
ND_TCHECK(*np);
/* get the byte-order right */
qdcount = EXTRACT_16BITS(&np->qdcount);
ancount = EXTRACT_16BITS(&np->ancount);
nscount = EXTRACT_16BITS(&np->nscount);
arcount = EXTRACT_16BITS(&np->arcount);
if (DNS_QR(np)) {
/* this is a response */
ND_PRINT((ndo, "%d%s%s%s%s%s%s",
EXTRACT_16BITS(&np->id),
ns_ops[DNS_OPCODE(np)],
ns_resp[DNS_RCODE(np)],
DNS_AA(np)? "*" : "",
DNS_RA(np)? "" : "-",
DNS_TC(np)? "|" : "",
DNS_AD(np)? "$" : ""));
if (qdcount != 1)
ND_PRINT((ndo, " [%dq]", qdcount));
/* Print QUESTION section on -vv */
cp = (const u_char *)(np + 1);
while (qdcount--) {
if (qdcount < EXTRACT_16BITS(&np->qdcount) - 1)
ND_PRINT((ndo, ","));
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " q:"));
if ((cp = ns_qprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
} else {
if ((cp = ns_nskip(ndo, cp)) == NULL)
goto trunc;
cp += 4; /* skip QTYPE and QCLASS */
}
}
ND_PRINT((ndo, " %d/%d/%d", ancount, nscount, arcount));
if (ancount--) {
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && ancount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (ancount > 0)
goto trunc;
/* Print NS and AR sections on -vv */
if (ndo->ndo_vflag > 1) {
if (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, " ns:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (nscount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, " ar:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (arcount > 0)
goto trunc;
}
}
else {
/* this is a request */
ND_PRINT((ndo, "%d%s%s%s", EXTRACT_16BITS(&np->id), ns_ops[DNS_OPCODE(np)],
DNS_RD(np) ? "+" : "",
DNS_CD(np) ? "%" : ""));
/* any weirdness? */
b2 = EXTRACT_16BITS(((const u_short *)np)+1);
if (b2 & 0x6cf)
ND_PRINT((ndo, " [b2&3=0x%x]", b2));
if (DNS_OPCODE(np) == IQUERY) {
if (qdcount)
ND_PRINT((ndo, " [%dq]", qdcount));
if (ancount != 1)
ND_PRINT((ndo, " [%da]", ancount));
}
else {
if (ancount)
ND_PRINT((ndo, " [%da]", ancount));
if (qdcount != 1)
ND_PRINT((ndo, " [%dq]", qdcount));
}
if (nscount)
ND_PRINT((ndo, " [%dn]", nscount));
if (arcount)
ND_PRINT((ndo, " [%dau]", arcount));
cp = (const u_char *)(np + 1);
if (qdcount--) {
cp = ns_qprint(ndo, cp, (const u_char *)np, is_mdns);
if (!cp)
goto trunc;
while (cp < ndo->ndo_snapend && qdcount--) {
cp = ns_qprint(ndo, (const u_char *)cp,
(const u_char *)np,
is_mdns);
if (!cp)
goto trunc;
}
}
if (qdcount > 0)
goto trunc;
/* Print remaining sections on -vv */
if (ndo->ndo_vflag > 1) {
if (ancount--) {
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && ancount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (ancount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, " ns:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (nscount-- && cp < ndo->ndo_snapend) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (nscount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, " ar:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (arcount > 0)
goto trunc;
}
}
ND_PRINT((ndo, " (%d)", length));
return;
trunc:
ND_PRINT((ndo, "[|domain]"));
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2668_0 |
crossvul-cpp_data_bad_2948_0 | /*
* 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 == 0) \
xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \
} 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 == 0) \
xmlParserInputGrow(ctxt->input, INPUT_CHUNK); \
} 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);
}
#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);
}
#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; \
} 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 expandPE = ((ctxt->external != 0) || (ctxt->inputNr != 1));
while (1) {
if (IS_BLANK_CH(CUR)) { /* CHECKED tstblanks.xml */
NEXT;
} else if (CUR == '%') {
/*
* Need to handle support of entities branching here
*/
if ((expandPE == 0) || (IS_BLANK_CH(NXT(1))) || (NXT(1) == 0))
break;
xmlParsePEReference(ctxt);
} else if (CUR == 0) {
if (ctxt->inputNr <= 1)
break;
xmlPopInput(ctxt);
} else {
break;
}
/*
* Also increase the counter when entering or exiting a PERef.
* The spec says: "When a parameter-entity reference is recognized
* in the DTD and included, its replacement text MUST be enlarged
* by the attachment of one leading and one following space (#x20)
* character."
*/
res++;
}
}
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);
if ((ctxt->inputNr > 1) && (ctxt->inSubset == 0) &&
(ctxt->instate != XML_PARSER_EOF))
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"Unfinished entity outside the DTD");
xmlFreeInputStream(inputPop(ctxt));
if (*ctxt->input->cur == 0)
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
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);
}
/**
* 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) {
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;
}
xmlParsePEReference(ctxt);
}
/*
* 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 ((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 - ctxt->input->base < len) {
/*
* There were a couple of bugs where PERefs lead to to a change
* of the buffer. Check the buffer size to avoid passing an invalid
* pointer to xmlDictLookup.
*/
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"unexpected change of input buffer");
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);
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 ">",
* and must, for compatibility, be escaped using ">" 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 + 1;
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 ((ctxt->input->cur < ctxt->input->end) && (!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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'SYSTEM'\n");
}
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'PUBLIC'\n");
}
*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 (SKIP_BLANKS == 0) {
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. We skip blanks if no
* system literal was found, but this is harmless since we must
* be at the end of a NotationDecl.
*/
if (SKIP_BLANKS == 0) return(NULL);
if ((CUR != '\'') && (CUR != '"')) return(NULL);
}
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) == '?')) {
int inputid = ctxt->input->id;
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 (inputid != ctxt->input->id) {
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;
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
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 (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"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')) {
int inputid = ctxt->input->id;
SHRINK;
SKIP(10);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!NOTATION'\n");
return;
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
return;
}
if (xmlStrchr(name, ':') != NULL) {
xmlNsErr(ctxt, XML_NS_ERR_COLON,
"colons are forbidden from notation names '%s'\n",
name, NULL, NULL);
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the NOTATION name'\n");
return;
}
/*
* Parse the IDs.
*/
Systemid = xmlParseExternalID(ctxt, &Pubid, 0);
SKIP_BLANKS;
if (RAW == '>') {
if (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"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;
/* GROW; done in the caller */
if (CMP8(CUR_PTR, '<', '!', 'E', 'N', 'T', 'I', 'T', 'Y')) {
int inputid = ctxt->input->id;
SHRINK;
SKIP(8);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ENTITY'\n");
}
if (RAW == '%') {
NEXT;
if (SKIP_BLANKS == 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);
}
if (SKIP_BLANKS == 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 != '>') && (SKIP_BLANKS == 0)) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required before 'NDATA'\n");
}
if (CMP5(CUR_PTR, 'N', 'D', 'A', 'T', 'A')) {
SKIP(5);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NDATA'\n");
}
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)
goto done;
SKIP_BLANKS;
if (RAW != '>') {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED,
"xmlParseEntityDecl: entity %s not terminated\n", name);
xmlHaltParser(ctxt);
} else {
if (inputid != ctxt->input->id) {
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) && (cur->orig == NULL)) {
cur->orig = orig;
orig = NULL;
}
}
done:
if (value != NULL) xmlFree(value);
if (URI != NULL) xmlFree(URI);
if (literal != NULL) xmlFree(literal);
if (orig != NULL) xmlFree(orig);
}
}
/**
* 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '#FIXED'\n");
}
}
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'NOTATION'\n");
return(0);
}
*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')) {
int inputid = ctxt->input->id;
SKIP(9);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after '<!ATTLIST'\n");
}
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)) {
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute name\n");
break;
}
type = xmlParseAttributeType(ctxt, &tree);
if (type <= 0) {
break;
}
GROW;
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the attribute type\n");
if (tree != NULL)
xmlFreeEnumeration(tree);
break;
}
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 (SKIP_BLANKS == 0) {
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;
}
}
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 (inputid != ctxt->input->id) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Attribute list declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and"
" stop in the same entity\n");
}
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->input->id != inputchk) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"Element content declaration doesn't start and stop in"
" the same entity\n");
}
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')) {
int inputid = ctxt->input->id;
SKIP(9);
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after 'ELEMENT'\n");
return(-1);
}
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseElementDecl: no name for Element\n");
return(-1);
}
if (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space required after the element name\n");
}
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;
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL);
if (content != NULL) {
xmlFreeDocElementContent(ctxt->myDoc, content);
}
} else {
if (inputid != ctxt->input->id) {
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not"
" in the same entity\n");
}
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");
}
SKIP_BLANKS;
GROW;
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
xmlParseMarkupDecl(ctxt);
SKIP_BLANKS;
GROW;
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not"
" in the same entity\n");
}
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) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"All markup of the conditional section is not in"
" the same entity\n");
}
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;
/*
* 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"Space needed after '<?xml'\n");
}
/*
* We may have the VersionInfo here.
*/
version = xmlParseVersionInfo(ctxt);
if (version == NULL)
version = xmlCharStrdup(XML_DEFAULT_VERSION);
else {
if (SKIP_BLANKS == 0) {
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;
SKIP_BLANKS;
while (((RAW == '<') && (NXT(1) == '?')) ||
((RAW == '<') && (NXT(1) == '!')) ||
(RAW == '%')) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
GROW;
if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
xmlParseConditionalSections(ctxt);
} else
xmlParseMarkupDecl(ctxt);
SKIP_BLANKS;
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;
/* Prevent entity from being parsed and expanded twice (Bug 760367). */
was_checked = 0;
} 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 "<") 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 "<") 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_PEREF_NO_NAME, "PEReference: no name\n");
return;
}
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (RAW != ';') {
xmlFatalErr(ctxt, XML_ERR_PEREF_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...
*/
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 {
/*
* 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 {
xmlChar start[4];
xmlCharEncoding enc;
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;
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) {
/*
* 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 ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
}
}
}
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);
*str = ptr;
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->inputNr > 1)) &&
(ctxt->instate != XML_PARSER_EOF)) {
const xmlChar *check = CUR_PTR;
unsigned int cons = ctxt->input->consumed;
SKIP_BLANKS;
xmlParseMarkupDecl(ctxt);
xmlParsePEReference(ctxt);
if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"xmlParseInternalSubset: error detected in Markup declaration\n");
if (ctxt->inputNr > 1)
xmlPopInput(ctxt);
else
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 "<") 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 mandates 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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
}
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 mandates 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, inputid;
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;
inputid = ctxt->input->id;
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 (SKIP_BLANKS == 0) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"attributes construct error\n");
break;
}
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;
}
if (ctxt->input->id != inputid) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
"Unexpected change of input\n");
localname = NULL;
goto done;
}
/* 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);
}
done:
/*
* 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;
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 occurred 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);
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);
}
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;
while (ctxt->inputNr > 1)
xmlFreeInputStream(inputPop(ctxt));
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;
ctxt->input->end = 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 ((oldctxt != NULL) && (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_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-835/c/bad_2948_0 |
crossvul-cpp_data_bad_2564_1 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2007 Novell, Inc.
* Copyright (C) 2008 Red Hat, Inc.
* Copyright (C) 2008 William Jon McCann <jmccann@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <glib-object.h>
#include <X11/ICE/ICElib.h>
#include <X11/ICE/ICEutil.h>
#include <X11/ICE/ICEconn.h>
#include <X11/SM/SMlib.h>
#ifdef HAVE_X11_XTRANS_XTRANS_H
/* Get the proto for _IceTransNoListen */
#define ICE_t
#define TRANS_SERVER
#include <X11/Xtrans/Xtrans.h>
#undef ICE_t
#undef TRANS_SERVER
#endif /* HAVE_X11_XTRANS_XTRANS_H */
#include "gsm-xsmp-server.h"
#include "gsm-xsmp-client.h"
#include "gsm-util.h"
/* ICEauthority stuff */
/* Various magic numbers stolen from iceauth.c */
#define GSM_ICE_AUTH_RETRIES 10
#define GSM_ICE_AUTH_INTERVAL 2 /* 2 seconds */
#define GSM_ICE_AUTH_LOCK_TIMEOUT 600 /* 10 minutes */
#define GSM_ICE_MAGIC_COOKIE_AUTH_NAME "MIT-MAGIC-COOKIE-1"
#define GSM_ICE_MAGIC_COOKIE_LEN 16
#define GSM_XSMP_SERVER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSM_TYPE_XSMP_SERVER, GsmXsmpServerPrivate))
struct GsmXsmpServerPrivate
{
GsmStore *client_store;
IceListenObj *xsmp_sockets;
int num_xsmp_sockets;
int num_local_xsmp_sockets;
};
enum {
PROP_0,
PROP_CLIENT_STORE
};
static void gsm_xsmp_server_class_init (GsmXsmpServerClass *klass);
static void gsm_xsmp_server_init (GsmXsmpServer *xsmp_server);
static void gsm_xsmp_server_finalize (GObject *object);
static gpointer xsmp_server_object = NULL;
G_DEFINE_TYPE (GsmXsmpServer, gsm_xsmp_server, G_TYPE_OBJECT)
typedef struct {
GsmXsmpServer *server;
IceListenObj listener;
} GsmIceConnectionData;
/* This is called (by glib via xsmp->ice_connection_watch) when a
* connection is first received on the ICE listening socket. (We
* expect that the client will then initiate XSMP on the connection;
* if it does not, GsmXSMPClient will eventually time out and close
* the connection.)
*
* FIXME: it would probably make more sense to not create a
* GsmXSMPClient object until accept_xsmp_connection, below (and to do
* the timing-out here in xsmp.c).
*/
static gboolean
accept_ice_connection (GIOChannel *source,
GIOCondition condition,
GsmIceConnectionData *data)
{
IceListenObj listener;
IceConn ice_conn;
IceAcceptStatus status;
GsmClient *client;
GsmXsmpServer *server;
listener = data->listener;
server = data->server;
g_debug ("GsmXsmpServer: accept_ice_connection()");
ice_conn = IceAcceptConnection (listener, &status);
if (status != IceAcceptSuccess) {
g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status);
return TRUE;
}
client = gsm_xsmp_client_new (ice_conn);
ice_conn->context = client;
gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client));
/* the store will own the ref */
g_object_unref (client);
return TRUE;
}
void
gsm_xsmp_server_start (GsmXsmpServer *server)
{
GIOChannel *channel;
int i;
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
GsmIceConnectionData *data;
data = g_new0 (GsmIceConnectionData, 1);
data->server = server;
data->listener = server->priv->xsmp_sockets[i];
channel = g_io_channel_unix_new (IceGetListenConnectionNumber (server->priv->xsmp_sockets[i]));
g_io_add_watch_full (channel,
G_PRIORITY_DEFAULT,
G_IO_IN | G_IO_HUP | G_IO_ERR,
(GIOFunc)accept_ice_connection,
data,
(GDestroyNotify)g_free);
g_io_channel_unref (channel);
}
}
static void
gsm_xsmp_server_set_client_store (GsmXsmpServer *xsmp_server,
GsmStore *store)
{
g_return_if_fail (GSM_IS_XSMP_SERVER (xsmp_server));
if (store != NULL) {
g_object_ref (store);
}
if (xsmp_server->priv->client_store != NULL) {
g_object_unref (xsmp_server->priv->client_store);
}
xsmp_server->priv->client_store = store;
}
static void
gsm_xsmp_server_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsmXsmpServer *self;
self = GSM_XSMP_SERVER (object);
switch (prop_id) {
case PROP_CLIENT_STORE:
gsm_xsmp_server_set_client_store (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_server_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GsmXsmpServer *self;
self = GSM_XSMP_SERVER (object);
switch (prop_id) {
case PROP_CLIENT_STORE:
g_value_set_object (value, self->priv->client_store);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* This is called (by libSM) when XSMP is initiated on an ICE
* connection that was already accepted by accept_ice_connection.
*/
static Status
accept_xsmp_connection (SmsConn sms_conn,
GsmXsmpServer *server,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret,
char **failure_reason_ret)
{
IceConn ice_conn;
GsmXSMPClient *client;
/* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */
if (server->priv->xsmp_sockets == NULL) {
g_debug ("GsmXsmpServer: In shutdown, rejecting new client");
*failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n"));
return FALSE;
}
ice_conn = SmsGetIceConnection (sms_conn);
client = ice_conn->context;
g_return_val_if_fail (client != NULL, TRUE);
gsm_xsmp_client_connect (client, sms_conn, mask_ret, callbacks_ret);
return TRUE;
}
static void
ice_error_handler (IceConn conn,
Bool swap,
int offending_minor_opcode,
unsigned long offending_sequence,
int error_class,
int severity,
IcePointer values)
{
g_debug ("GsmXsmpServer: ice_error_handler (%p, %s, %d, %lx, %d, %d)",
conn, swap ? "TRUE" : "FALSE", offending_minor_opcode,
offending_sequence, error_class, severity);
if (severity == IceCanContinue) {
return;
}
/* FIXME: the ICElib docs are completely vague about what we're
* supposed to do in this case. Need to verify that calling
* IceCloseConnection() here is guaranteed to cause neither
* free-memory-reads nor leaks.
*/
IceCloseConnection (conn);
}
static void
ice_io_error_handler (IceConn conn)
{
g_debug ("GsmXsmpServer: ice_io_error_handler (%p)", conn);
/* We don't need to do anything here; the next call to
* IceProcessMessages() for this connection will receive
* IceProcessMessagesIOError and we can handle the error there.
*/
}
static void
sms_error_handler (SmsConn conn,
Bool swap,
int offending_minor_opcode,
unsigned long offending_sequence_num,
int error_class,
int severity,
IcePointer values)
{
g_debug ("GsmXsmpServer: sms_error_handler (%p, %s, %d, %lx, %d, %d)",
conn, swap ? "TRUE" : "FALSE", offending_minor_opcode,
offending_sequence_num, error_class, severity);
/* We don't need to do anything here; if the connection needs to be
* closed, libSM will do that itself.
*/
}
static IceAuthFileEntry *
auth_entry_new (const char *protocol,
const char *network_id)
{
IceAuthFileEntry *file_entry;
IceAuthDataEntry data_entry;
file_entry = malloc (sizeof (IceAuthFileEntry));
file_entry->protocol_name = strdup (protocol);
file_entry->protocol_data = NULL;
file_entry->protocol_data_length = 0;
file_entry->network_id = strdup (network_id);
file_entry->auth_name = strdup (GSM_ICE_MAGIC_COOKIE_AUTH_NAME);
file_entry->auth_data = IceGenerateMagicCookie (GSM_ICE_MAGIC_COOKIE_LEN);
file_entry->auth_data_length = GSM_ICE_MAGIC_COOKIE_LEN;
/* Also create an in-memory copy, which is what the server will
* actually use for checking client auth.
*/
data_entry.protocol_name = file_entry->protocol_name;
data_entry.network_id = file_entry->network_id;
data_entry.auth_name = file_entry->auth_name;
data_entry.auth_data = file_entry->auth_data;
data_entry.auth_data_length = file_entry->auth_data_length;
IceSetPaAuthData (1, &data_entry);
return file_entry;
}
static gboolean
update_iceauthority (GsmXsmpServer *server,
gboolean adding)
{
char *filename;
char **our_network_ids;
FILE *fp;
IceAuthFileEntry *auth_entry;
GSList *entries;
GSList *e;
int i;
gboolean ok = FALSE;
filename = IceAuthFileName ();
if (IceLockAuthFile (filename,
GSM_ICE_AUTH_RETRIES,
GSM_ICE_AUTH_INTERVAL,
GSM_ICE_AUTH_LOCK_TIMEOUT) != IceAuthLockSuccess) {
return FALSE;
}
our_network_ids = g_malloc (server->priv->num_local_xsmp_sockets * sizeof (char *));
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
our_network_ids[i] = IceGetListenConnectionString (server->priv->xsmp_sockets[i]);
}
entries = NULL;
fp = fopen (filename, "r+");
if (fp != NULL) {
while ((auth_entry = IceReadAuthFileEntry (fp)) != NULL) {
/* Skip/delete entries with no network ID (invalid), or with
* our network ID; if we're starting up, an entry with our
* ID must be a stale entry left behind by an old process,
* and if we're shutting down, it won't be valid in the
* future, so either way we want to remove it from the list.
*/
if (!auth_entry->network_id) {
IceFreeAuthFileEntry (auth_entry);
continue;
}
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
if (!strcmp (auth_entry->network_id, our_network_ids[i])) {
IceFreeAuthFileEntry (auth_entry);
break;
}
}
if (i != server->priv->num_local_xsmp_sockets) {
continue;
}
entries = g_slist_prepend (entries, auth_entry);
}
rewind (fp);
} else {
int fd;
if (g_file_test (filename, G_FILE_TEST_EXISTS)) {
g_warning ("Unable to read ICE authority file: %s", filename);
goto cleanup;
}
fd = open (filename, O_CREAT | O_WRONLY, 0600);
fp = fdopen (fd, "w");
if (!fp) {
g_warning ("Unable to write to ICE authority file: %s", filename);
if (fd != -1) {
close (fd);
}
goto cleanup;
}
}
if (adding) {
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
entries = g_slist_append (entries,
auth_entry_new ("ICE", our_network_ids[i]));
entries = g_slist_prepend (entries,
auth_entry_new ("XSMP", our_network_ids[i]));
}
}
for (e = entries; e; e = e->next) {
IceAuthFileEntry *auth_entry = e->data;
IceWriteAuthFileEntry (fp, auth_entry);
IceFreeAuthFileEntry (auth_entry);
}
g_slist_free (entries);
fclose (fp);
ok = TRUE;
cleanup:
IceUnlockAuthFile (filename);
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
free (our_network_ids[i]);
}
g_free (our_network_ids);
return ok;
}
static void
setup_listener (GsmXsmpServer *server)
{
char error[256];
mode_t saved_umask;
char *network_id_list;
int i;
int res;
/* Set up sane error handlers */
IceSetErrorHandler (ice_error_handler);
IceSetIOErrorHandler (ice_io_error_handler);
SmsSetErrorHandler (sms_error_handler);
/* Initialize libSM; we pass NULL for hostBasedAuthProc to disable
* host-based authentication.
*/
res = SmsInitialize (PACKAGE,
VERSION,
(SmsNewClientProc)accept_xsmp_connection,
server,
NULL,
sizeof (error),
error);
if (! res) {
gsm_util_init_error (TRUE, "Could not initialize libSM: %s", error);
}
#ifdef HAVE_X11_XTRANS_XTRANS_H
/* By default, IceListenForConnections will open one socket for each
* transport type known to X. We don't want connections from remote
* hosts, so for security reasons it would be best if ICE didn't
* even open any non-local sockets. So we use an internal ICElib
* method to disable them here. Unfortunately, there is no way to
* ask X what transport types it knows about, so we're forced to
* guess.
*/
_IceTransNoListen ("tcp");
#endif
/* Create the XSMP socket. Older versions of IceListenForConnections
* have a bug which causes the umask to be set to 0 on certain types
* of failures. Probably not an issue on any modern systems, but
* we'll play it safe.
*/
saved_umask = umask (0);
umask (saved_umask);
res = IceListenForConnections (&server->priv->num_xsmp_sockets,
&server->priv->xsmp_sockets,
sizeof (error),
error);
if (! res) {
gsm_util_init_error (TRUE, _("Could not create ICE listening socket: %s"), error);
}
umask (saved_umask);
/* Find the local sockets in the returned socket list and move them
* to the start of the list.
*/
for (i = server->priv->num_local_xsmp_sockets = 0; i < server->priv->num_xsmp_sockets; i++) {
char *id = IceGetListenConnectionString (server->priv->xsmp_sockets[i]);
if (!strncmp (id, "local/", sizeof ("local/") - 1) ||
!strncmp (id, "unix/", sizeof ("unix/") - 1)) {
if (i > server->priv->num_local_xsmp_sockets) {
IceListenObj tmp;
tmp = server->priv->xsmp_sockets[i];
server->priv->xsmp_sockets[i] = server->priv->xsmp_sockets[server->priv->num_local_xsmp_sockets];
server->priv->xsmp_sockets[server->priv->num_local_xsmp_sockets] = tmp;
}
server->priv->num_local_xsmp_sockets++;
}
free (id);
}
if (server->priv->num_local_xsmp_sockets == 0) {
gsm_util_init_error (TRUE, "IceListenForConnections did not return a local listener!");
}
#ifdef HAVE_X11_XTRANS_XTRANS_H
if (server->priv->num_local_xsmp_sockets != server->priv->num_xsmp_sockets) {
/* Xtrans was apparently compiled with support for some
* non-local transport besides TCP (which we disabled above); we
* won't create IO watches on those extra sockets, so
* connections to them will never be noticed, but they're still
* there, which is inelegant.
*
* If the g_warning below is triggering for you and you want to
* stop it, the fix is to add additional _IceTransNoListen()
* calls above.
*/
network_id_list = IceComposeNetworkIdList (server->priv->num_xsmp_sockets - server->priv->num_local_xsmp_sockets,
server->priv->xsmp_sockets + server->priv->num_local_xsmp_sockets);
g_warning ("IceListenForConnections returned %d non-local listeners: %s",
server->priv->num_xsmp_sockets - server->priv->num_local_xsmp_sockets,
network_id_list);
free (network_id_list);
}
#endif
/* Update .ICEauthority with new auth entries for our socket */
if (!update_iceauthority (server, TRUE)) {
/* FIXME: is this really fatal? Hm... */
gsm_util_init_error (TRUE,
"Could not update ICEauthority file %s",
IceAuthFileName ());
}
network_id_list = IceComposeNetworkIdList (server->priv->num_local_xsmp_sockets,
server->priv->xsmp_sockets);
gsm_util_setenv ("SESSION_MANAGER", network_id_list);
g_debug ("GsmXsmpServer: SESSION_MANAGER=%s\n", network_id_list);
free (network_id_list);
}
static GObject *
gsm_xsmp_server_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_properties)
{
GsmXsmpServer *xsmp_server;
xsmp_server = GSM_XSMP_SERVER (G_OBJECT_CLASS (gsm_xsmp_server_parent_class)->constructor (type,
n_construct_properties,
construct_properties));
setup_listener (xsmp_server);
return G_OBJECT (xsmp_server);
}
static void
gsm_xsmp_server_class_init (GsmXsmpServerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->get_property = gsm_xsmp_server_get_property;
object_class->set_property = gsm_xsmp_server_set_property;
object_class->constructor = gsm_xsmp_server_constructor;
object_class->finalize = gsm_xsmp_server_finalize;
g_object_class_install_property (object_class,
PROP_CLIENT_STORE,
g_param_spec_object ("client-store",
NULL,
NULL,
GSM_TYPE_STORE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GsmXsmpServerPrivate));
}
static void
gsm_xsmp_server_init (GsmXsmpServer *xsmp_server)
{
xsmp_server->priv = GSM_XSMP_SERVER_GET_PRIVATE (xsmp_server);
}
static void
gsm_xsmp_server_finalize (GObject *object)
{
GsmXsmpServer *xsmp_server;
g_return_if_fail (object != NULL);
g_return_if_fail (GSM_IS_XSMP_SERVER (object));
xsmp_server = GSM_XSMP_SERVER (object);
g_return_if_fail (xsmp_server->priv != NULL);
IceFreeListenObjs (xsmp_server->priv->num_xsmp_sockets,
xsmp_server->priv->xsmp_sockets);
if (xsmp_server->priv->client_store != NULL) {
g_object_unref (xsmp_server->priv->client_store);
}
G_OBJECT_CLASS (gsm_xsmp_server_parent_class)->finalize (object);
}
GsmXsmpServer *
gsm_xsmp_server_new (GsmStore *client_store)
{
if (xsmp_server_object != NULL) {
g_object_ref (xsmp_server_object);
} else {
xsmp_server_object = g_object_new (GSM_TYPE_XSMP_SERVER,
"client-store", client_store,
NULL);
g_object_add_weak_pointer (xsmp_server_object,
(gpointer *) &xsmp_server_object);
}
return GSM_XSMP_SERVER (xsmp_server_object);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2564_1 |
crossvul-cpp_data_bad_319_0 | /*
* Copyright © 2013 Ran Benita <ran234@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*/
/******************************************************************
Copyright 1992 by Oki Technosystems Laboratory, Inc.
Copyright 1992 by Fuji Xerox Co., Ltd.
Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation, and that the name of Oki Technosystems
Laboratory and Fuji Xerox not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.
Oki Technosystems Laboratory and Fuji Xerox make no representations
about the suitability of this software for any purpose. It is provided
"as is" without express or implied warranty.
OKI TECHNOSYSTEMS LABORATORY AND FUJI XEROX DISCLAIM ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL OKI TECHNOSYSTEMS
LABORATORY AND FUJI XEROX BE LIABLE FOR 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.
Author: Yasuhiro Kawai Oki Technosystems Laboratory
Author: Kazunori Nishihara Fuji Xerox
******************************************************************/
#include <errno.h>
#include "utils.h"
#include "scanner-utils.h"
#include "table.h"
#include "paths.h"
#include "utf8.h"
#include "parser.h"
#define MAX_LHS_LEN 10
#define MAX_INCLUDE_DEPTH 5
/*
* Grammar adapted from libX11/modules/im/ximcp/imLcPrs.c.
* See also the XCompose(5) manpage.
*
* FILE ::= { [PRODUCTION] [COMMENT] "\n" | INCLUDE }
* INCLUDE ::= "include" '"' INCLUDE_STRING '"'
* PRODUCTION ::= LHS ":" RHS [ COMMENT ]
* COMMENT ::= "#" {<any character except null or newline>}
* LHS ::= EVENT { EVENT }
* EVENT ::= [MODIFIER_LIST] "<" keysym ">"
* MODIFIER_LIST ::= (["!"] {MODIFIER} ) | "None"
* MODIFIER ::= ["~"] MODIFIER_NAME
* MODIFIER_NAME ::= ("Ctrl"|"Lock"|"Caps"|"Shift"|"Alt"|"Meta")
* RHS ::= ( STRING | keysym | STRING keysym )
* STRING ::= '"' { CHAR } '"'
* CHAR ::= GRAPHIC_CHAR | ESCAPED_CHAR
* GRAPHIC_CHAR ::= locale (codeset) dependent code
* ESCAPED_CHAR ::= ('\\' | '\"' | OCTAL | HEX )
* OCTAL ::= '\' OCTAL_CHAR [OCTAL_CHAR [OCTAL_CHAR]]
* OCTAL_CHAR ::= (0|1|2|3|4|5|6|7)
* HEX ::= '\' (x|X) HEX_CHAR [HEX_CHAR]]
* HEX_CHAR ::= (0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|a|b|c|d|e|f)
*
* INCLUDE_STRING is a filesystem path, with the following %-expansions:
* %% - '%'.
* %H - The user's home directory (the $HOME environment variable).
* %L - The name of the locale specific Compose file (e.g.,
* "/usr/share/X11/locale/<localename>/Compose").
* %S - The name of the system directory for Compose files (e.g.,
* "/usr/share/X11/locale").
*/
enum rules_token {
TOK_END_OF_FILE = 0,
TOK_END_OF_LINE,
TOK_INCLUDE,
TOK_INCLUDE_STRING,
TOK_LHS_KEYSYM,
TOK_COLON,
TOK_BANG,
TOK_TILDE,
TOK_STRING,
TOK_IDENT,
TOK_ERROR
};
/* Values returned with some tokens, like yylval. */
union lvalue {
struct {
/* Still \0-terminated. */
const char *str;
size_t len;
} string;
};
static enum rules_token
lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
static enum rules_token
lex_include_string(struct scanner *s, struct xkb_compose_table *table,
union lvalue *val_out)
{
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
if (!chr(s, '\"')) {
scanner_err(s, "include statement must be followed by a path");
return TOK_ERROR;
}
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '%')) {
if (chr(s, '%')) {
buf_append(s, '%');
}
else if (chr(s, 'H')) {
const char *home = secure_getenv("HOME");
if (!home) {
scanner_err(s, "%%H was used in an include statement, but the HOME environment variable is not set");
return TOK_ERROR;
}
if (!buf_appends(s, home)) {
scanner_err(s, "include path after expanding %%H is too long");
return TOK_ERROR;
}
}
else if (chr(s, 'L')) {
char *path = get_locale_compose_file_path(table->locale);
if (!path) {
scanner_err(s, "failed to expand %%L to the locale Compose file");
return TOK_ERROR;
}
if (!buf_appends(s, path)) {
free(path);
scanner_err(s, "include path after expanding %%L is too long");
return TOK_ERROR;
}
free(path);
}
else if (chr(s, 'S')) {
const char *xlocaledir = get_xlocaledir_path();
if (!buf_appends(s, xlocaledir)) {
scanner_err(s, "include path after expanding %%S is too long");
return TOK_ERROR;
}
}
else {
scanner_err(s, "unknown %% format (%c) in include statement", peek(s));
return TOK_ERROR;
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated include statement");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "include path is too long");
return TOK_ERROR;
}
val_out->string.str = s->buf;
val_out->string.len = s->buf_pos;
return TOK_INCLUDE_STRING;
}
struct production {
xkb_keysym_t lhs[MAX_LHS_LEN];
unsigned int len;
xkb_keysym_t keysym;
char string[256];
/* At least one of these is true. */
bool has_keysym;
bool has_string;
/* The matching is as follows: (active_mods & modmask) == mods. */
xkb_mod_mask_t modmask;
xkb_mod_mask_t mods;
};
static uint32_t
add_node(struct xkb_compose_table *table, xkb_keysym_t keysym)
{
struct compose_node new = {
.keysym = keysym,
.next = 0,
.is_leaf = true,
};
darray_append(table->nodes, new);
return darray_size(table->nodes) - 1;
}
static void
add_production(struct xkb_compose_table *table, struct scanner *s,
const struct production *production)
{
unsigned lhs_pos;
uint32_t curr;
struct compose_node *node;
curr = 0;
node = &darray_item(table->nodes, curr);
/*
* Insert the sequence to the trie, creating new nodes as needed.
*
* TODO: This can be sped up a bit by first trying the path that the
* previous production took, and only then doing the linear search
* through the trie levels. This will work because sequences in the
* Compose files are often clustered by a common prefix; especially
* in the 1st and 2nd keysyms, which is where the largest variation
* (thus, longest search) is.
*/
for (lhs_pos = 0; lhs_pos < production->len; lhs_pos++) {
while (production->lhs[lhs_pos] != node->keysym) {
if (node->next == 0) {
uint32_t next = add_node(table, production->lhs[lhs_pos]);
/* Refetch since add_node could have realloc()ed. */
node = &darray_item(table->nodes, curr);
node->next = next;
}
curr = node->next;
node = &darray_item(table->nodes, curr);
}
if (lhs_pos + 1 == production->len)
break;
if (node->is_leaf) {
if (node->u.leaf.utf8 != 0 ||
node->u.leaf.keysym != XKB_KEY_NoSymbol) {
scanner_warn(s, "a sequence already exists which is a prefix of this sequence; overriding");
node->u.leaf.utf8 = 0;
node->u.leaf.keysym = XKB_KEY_NoSymbol;
}
{
uint32_t successor = add_node(table, production->lhs[lhs_pos + 1]);
/* Refetch since add_node could have realloc()ed. */
node = &darray_item(table->nodes, curr);
node->is_leaf = false;
node->u.successor = successor;
}
}
curr = node->u.successor;
node = &darray_item(table->nodes, curr);
}
if (!node->is_leaf) {
scanner_warn(s, "this compose sequence is a prefix of another; skipping line");
return;
}
if (node->u.leaf.utf8 != 0 || node->u.leaf.keysym != XKB_KEY_NoSymbol) {
bool same_string =
(node->u.leaf.utf8 == 0 && !production->has_string) ||
(
node->u.leaf.utf8 != 0 && production->has_string &&
streq(&darray_item(table->utf8, node->u.leaf.utf8),
production->string)
);
bool same_keysym =
(node->u.leaf.keysym == XKB_KEY_NoSymbol && !production->has_keysym) ||
(
node->u.leaf.keysym != XKB_KEY_NoSymbol && production->has_keysym &&
node->u.leaf.keysym == production->keysym
);
if (same_string && same_keysym) {
scanner_warn(s, "this compose sequence is a duplicate of another; skipping line");
return;
}
scanner_warn(s, "this compose sequence already exists; overriding");
}
if (production->has_string) {
node->u.leaf.utf8 = darray_size(table->utf8);
darray_append_items(table->utf8, production->string,
strlen(production->string) + 1);
}
if (production->has_keysym) {
node->u.leaf.keysym = production->keysym;
}
}
/* Should match resolve_modifier(). */
#define ALL_MODS_MASK ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3))
static xkb_mod_index_t
resolve_modifier(const char *name)
{
static const struct {
const char *name;
xkb_mod_index_t mod;
} mods[] = {
{ "Shift", 0 },
{ "Ctrl", 2 },
{ "Alt", 3 },
{ "Meta", 3 },
{ "Lock", 1 },
{ "Caps", 1 },
};
for (unsigned i = 0; i < ARRAY_SIZE(mods); i++)
if (streq(name, mods[i].name))
return mods[i].mod;
return XKB_MOD_INVALID;
}
static bool
parse(struct xkb_compose_table *table, struct scanner *s,
unsigned include_depth);
static bool
do_include(struct xkb_compose_table *table, struct scanner *s,
const char *path, unsigned include_depth)
{
FILE *file;
bool ok;
char *string;
size_t size;
struct scanner new_s;
if (include_depth >= MAX_INCLUDE_DEPTH) {
scanner_err(s, "maximum include depth (%d) exceeded; maybe there is an include loop?",
MAX_INCLUDE_DEPTH);
return false;
}
file = fopen(path, "r");
if (!file) {
scanner_err(s, "failed to open included Compose file \"%s\": %s",
path, strerror(errno));
return false;
}
ok = map_file(file, &string, &size);
if (!ok) {
scanner_err(s, "failed to read included Compose file \"%s\": %s",
path, strerror(errno));
goto err_file;
}
scanner_init(&new_s, table->ctx, string, size, path, s->priv);
ok = parse(table, &new_s, include_depth + 1);
if (!ok)
goto err_unmap;
err_unmap:
unmap_file(string, size);
err_file:
fclose(file);
return ok;
}
static bool
parse(struct xkb_compose_table *table, struct scanner *s,
unsigned include_depth)
{
enum rules_token tok;
union lvalue val;
xkb_keysym_t keysym;
struct production production;
enum { MAX_ERRORS = 10 };
int num_errors = 0;
initial:
production.len = 0;
production.has_keysym = false;
production.has_string = false;
production.mods = 0;
production.modmask = 0;
/* fallthrough */
initial_eol:
switch (tok = lex(s, &val)) {
case TOK_END_OF_LINE:
goto initial_eol;
case TOK_END_OF_FILE:
goto finished;
case TOK_INCLUDE:
goto include;
default:
goto lhs_tok;
}
include:
switch (tok = lex_include_string(s, table, &val)) {
case TOK_INCLUDE_STRING:
goto include_eol;
default:
goto unexpected;
}
include_eol:
switch (tok = lex(s, &val)) {
case TOK_END_OF_LINE:
if (!do_include(table, s, val.string.str, include_depth))
goto fail;
goto initial;
default:
goto unexpected;
}
lhs:
tok = lex(s, &val);
lhs_tok:
switch (tok) {
case TOK_COLON:
if (production.len <= 0) {
scanner_warn(s, "expected at least one keysym on left-hand side; skipping line");
goto skip;
}
goto rhs;
case TOK_IDENT:
if (streq(val.string.str, "None")) {
production.mods = 0;
production.modmask = ALL_MODS_MASK;
goto lhs_keysym;
}
goto lhs_mod_list_tok;
case TOK_TILDE:
goto lhs_mod_list_tok;
case TOK_BANG:
production.modmask = ALL_MODS_MASK;
goto lhs_mod_list;
default:
goto lhs_keysym_tok;
}
lhs_keysym:
tok = lex(s, &val);
lhs_keysym_tok:
switch (tok) {
case TOK_LHS_KEYSYM:
keysym = xkb_keysym_from_name(val.string.str, XKB_KEYSYM_NO_FLAGS);
if (keysym == XKB_KEY_NoSymbol) {
scanner_err(s, "unrecognized keysym \"%s\" on left-hand side",
val.string.str);
goto error;
}
if (production.len + 1 > MAX_LHS_LEN) {
scanner_warn(s, "too many keysyms (%d) on left-hand side; skipping line",
MAX_LHS_LEN + 1);
goto skip;
}
production.lhs[production.len++] = keysym;
production.mods = 0;
production.modmask = 0;
goto lhs;
default:
goto unexpected;
}
lhs_mod_list:
tok = lex(s, &val);
lhs_mod_list_tok: {
bool tilde = false;
xkb_mod_index_t mod;
if (tok != TOK_TILDE && tok != TOK_IDENT)
goto lhs_keysym_tok;
if (tok == TOK_TILDE) {
tilde = true;
tok = lex(s, &val);
}
if (tok != TOK_IDENT)
goto unexpected;
mod = resolve_modifier(val.string.str);
if (mod == XKB_MOD_INVALID) {
scanner_err(s, "unrecognized modifier \"%s\"",
val.string.str);
goto error;
}
production.modmask |= 1 << mod;
if (tilde)
production.mods &= ~(1 << mod);
else
production.mods |= 1 << mod;
goto lhs_mod_list;
}
rhs:
switch (tok = lex(s, &val)) {
case TOK_STRING:
if (production.has_string) {
scanner_warn(s, "right-hand side can have at most one string; skipping line");
goto skip;
}
if (val.string.len <= 0) {
scanner_warn(s, "right-hand side string must not be empty; skipping line");
goto skip;
}
if (val.string.len >= sizeof(production.string)) {
scanner_warn(s, "right-hand side string is too long; skipping line");
goto skip;
}
strcpy(production.string, val.string.str);
production.has_string = true;
goto rhs;
case TOK_IDENT:
keysym = xkb_keysym_from_name(val.string.str, XKB_KEYSYM_NO_FLAGS);
if (keysym == XKB_KEY_NoSymbol) {
scanner_err(s, "unrecognized keysym \"%s\" on right-hand side",
val.string.str);
goto error;
}
if (production.has_keysym) {
scanner_warn(s, "right-hand side can have at most one keysym; skipping line");
goto skip;
}
production.keysym = keysym;
production.has_keysym = true;
/* fallthrough */
case TOK_END_OF_LINE:
if (!production.has_string && !production.has_keysym) {
scanner_warn(s, "right-hand side must have at least one of string or keysym; skipping line");
goto skip;
}
add_production(table, s, &production);
goto initial;
default:
goto unexpected;
}
unexpected:
if (tok != TOK_ERROR)
scanner_err(s, "unexpected token");
error:
num_errors++;
if (num_errors <= MAX_ERRORS)
goto skip;
scanner_err(s, "too many errors");
goto fail;
fail:
scanner_err(s, "failed to parse file");
return false;
skip:
while (tok != TOK_END_OF_LINE && tok != TOK_END_OF_FILE)
tok = lex(s, &val);
goto initial;
finished:
return true;
}
bool
parse_string(struct xkb_compose_table *table, const char *string, size_t len,
const char *file_name)
{
struct scanner s;
scanner_init(&s, table->ctx, string, len, file_name, NULL);
if (!parse(table, &s, 0))
return false;
/* Maybe the allocator can use the excess space. */
darray_shrink(table->nodes);
darray_shrink(table->utf8);
return true;
}
bool
parse_file(struct xkb_compose_table *table, FILE *file, const char *file_name)
{
bool ok;
char *string;
size_t size;
ok = map_file(file, &string, &size);
if (!ok) {
log_err(table->ctx, "Couldn't read Compose file %s: %s\n",
file_name, strerror(errno));
return false;
}
ok = parse_string(table, string, size, file_name);
unmap_file(string, size);
return ok;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_319_0 |
crossvul-cpp_data_good_581_0 | #ifndef IGNOREALL
/*
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net
This is a command-line ANSI C program to convert raw photos from
any digital camera on any computer running any operating system.
No license is required to download and use dcraw.c. However,
to lawfully redistribute dcraw, you must either (a) offer, at
no extra charge, full source code* for all executable files
containing RESTRICTED functions, (b) distribute this code under
the GPL Version 2 or later, (c) remove all RESTRICTED functions,
re-implement them, or copy them from an earlier, unrestricted
Revision of dcraw.c, or (d) purchase a license from the author.
The functions that process Foveon images have been RESTRICTED
since Revision 1.237. All other code remains free for all uses.
*If you have not modified dcraw.c in any way, a link to my
homepage qualifies as "full source code".
$Revision: 1.476 $
$Date: 2015/05/25 02:29:14 $
*/
/*@out DEFINES
#ifndef USE_JPEG
#define NO_JPEG
#endif
#ifndef USE_JASPER
#define NO_JASPER
#endif
@end DEFINES */
#define NO_LCMS
#define DCRAW_VERBOSE
//@out DEFINES
#define DCRAW_VERSION "9.26"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _USE_MATH_DEFINES
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
//@end DEFINES
#if defined(DJGPP) || defined(__MINGW32__)
#define fseeko fseek
#define ftello ftell
#else
#define fgetc getc_unlocked
#endif
//@out DEFINES
#ifdef __CYGWIN__
#include <io.h>
#endif
#if defined WIN32 || defined(__MINGW32__)
#include <sys/utime.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
//@end DEFINES
typedef __int64 INT64;
typedef unsigned __int64 UINT64;
//@out DEFINES
#else
#include <unistd.h>
#include <utime.h>
#include <netinet/in.h>
typedef long long INT64;
typedef unsigned long long UINT64;
#endif
#ifdef NODEPS
#define NO_JASPER
#define NO_JPEG
#define NO_LCMS
#endif
#ifndef NO_JASPER
#include <jasper/jasper.h> /* Decode Red camera movies */
#endif
#ifndef NO_JPEG
#include <jpeglib.h> /* Decode compressed Kodak DC120 photos */
#endif /* and Adobe Lossy DNGs */
#ifndef NO_LCMS
#ifdef USE_LCMS
#include <lcms.h> /* Support color profiles */
#else
#include <lcms2.h> /* Support color profiles */
#endif
#endif
#ifdef LOCALEDIR
#include <libintl.h>
#define _(String) gettext(String)
#else
#define _(String) (String)
#endif
#ifdef LJPEG_DECODE
#error Please compile dcraw.c by itself.
#error Do not link it with ljpeg_decode.
#endif
#ifndef LONG_BIT
#define LONG_BIT (8 * sizeof(long))
#endif
//@end DEFINES
#if !defined(uchar)
#define uchar unsigned char
#endif
#if !defined(ushort)
#define ushort unsigned short
#endif
/*
All global variables are defined here, and all functions that
access them are prefixed with "CLASS". Note that a thread-safe
C++ class cannot have non-const static local variables.
*/
FILE *ifp, *ofp;
short order;
const char *ifname;
char *meta_data, xtrans[6][6], xtrans_abs[6][6];
char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64], software[64];
float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
time_t timestamp;
off_t strip_offset, data_offset;
off_t thumb_offset, meta_offset, profile_offset;
unsigned shot_order, kodak_cbpp, exif_cfa, unique_id;
unsigned thumb_length, meta_length, profile_length;
unsigned thumb_misc, *oprof, fuji_layout, shot_select = 0, multi_out = 0;
unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
unsigned black, maximum, mix_green, raw_color, zero_is_bad;
unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
unsigned tile_width, tile_length, gpsdata[32], load_flags;
unsigned flip, tiff_flip, filters, colors;
ushort raw_height, raw_width, height, width, top_margin, left_margin;
ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
ushort *raw_image, (*image)[4], cblack[4102];
ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
double pixel_aspect, aber[4] = {1, 1, 1, 1}, gamm[6] = {0.45, 4.5, 0, 0, 0, 0};
float bright = 1, user_mul[4] = {0, 0, 0, 0}, threshold = 0;
int mask[8][4];
int half_size = 0, four_color_rgb = 0, document_mode = 0, highlight = 0;
int verbose = 0, use_auto_wb = 0, use_camera_wb = 0, use_camera_matrix = 1;
int output_color = 1, output_bps = 8, output_tiff = 0, med_passes = 0;
int no_auto_bright = 0;
unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX};
float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
const double xyz_rgb[3][3] = {/* XYZ from RGB */
{0.412453, 0.357580, 0.180423},
{0.212671, 0.715160, 0.072169},
{0.019334, 0.119193, 0.950227}};
const float d65_white[3] = {0.950456, 1, 1.088754};
int histogram[4][0x2000];
void (*write_thumb)(), (*write_fun)();
void (*load_raw)(), (*thumb_load_raw)();
jmp_buf failure;
struct decode
{
struct decode *branch[2];
int leaf;
} first_decode[2048], *second_decode, *free_decode;
struct tiff_ifd
{
int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes;
int t_tile_width, t_tile_length, sample_format, predictor;
float t_shutter;
} tiff_ifd[10];
struct ph1
{
int format, key_off, tag_21a;
int t_black, split_col, black_col, split_row, black_row;
float tag_210;
} ph1;
#define CLASS
//@out DEFINES
#define FORC(cnt) for (c = 0; c < cnt; c++)
#define FORC3 FORC(3)
#define FORC4 FORC(4)
#define FORCC for (c = 0; c < colors && c < 4; c++)
#define SQR(x) ((x) * (x))
#define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define LIM(x, min, max) MAX(min, MIN(x, max))
#define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y))
#define CLIP(x) LIM((int)(x), 0, 65535)
#define CLIP15(x) LIM((int)(x), 0, 32767)
#define SWAP(a, b) \
{ \
a = a + b; \
b = a - b; \
a = a - b; \
}
#define my_swap(type, i, j) \
{ \
type t = i; \
i = j; \
j = t; \
}
static float fMAX(float a, float b) { return MAX(a, b); }
/*
In order to inline this calculation, I make the risky
assumption that all filter patterns can be described
by a repeating pattern of eight rows and two columns
Do not use the FC or BAYER macros with the Leaf CatchLight,
because its pattern is 16x16, not 2x8.
Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1
0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M
1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C
2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y
3 C Y C Y C Y 3 G M G M G M 3 G M G M G M
4 C Y C Y C Y 4 Y C Y C Y C
PowerShot A5 5 G M G M G M 5 G M G M G M
0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y
7 M G M G M G 7 M G M G M G
0 1 2 3 4 5
0 C Y C Y C Y
1 G M G M G M
2 C Y C Y C Y
3 M G M G M G
All RGB cameras use one of these Bayer grids:
0x16161616: 0x61616161: 0x49494949: 0x94949494:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G
1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B
2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G
3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B
*/
#define RAWINDEX(row, col) ((row)*raw_width + (col))
#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, unsigned count)
{
if (fread(pixel, 2, count, ifp) < count)
derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab((char *)pixel, (char *)pixel, count * 2);
}
void CLASS cubic_spline(const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len);
if (!A)
return;
A[0] = (float *)(A + 2 * len);
for (i = 1; i < 2 * len; i++)
A[i] = A[0] + 2 * len * i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i))));
for (i = 0; i < len; i++)
{
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len - 1; i > 0; i--)
{
b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]);
d[i - 1] = x[i] - x[i - 1];
}
for (i = 1; i < len - 1; i++)
{
A[i][i] = 2 * (d[i - 1] + d[i]);
if (i > 1)
{
A[i][i - 1] = d[i - 1];
A[i - 1][i] = d[i - 1];
}
A[i][len - 1] = 6 * (b[i + 1] - b[i]);
}
for (i = 1; i < len - 2; i++)
{
float v = A[i + 1][i] / A[i][i];
for (j = 1; j <= len - 1; j++)
A[i + 1][j] -= v * A[i][j];
}
for (i = len - 2; i > 0; i--)
{
float acc = 0;
for (j = i; j <= len - 2; j++)
acc += A[i][j] * c[j];
c[i] = (A[i][len - 1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++)
{
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len - 1; j++)
{
if (x[j] <= x_out && x_out <= x[j + 1])
{
float v = x_out - x[j];
y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v +
((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5));
}
free(A);
}
void CLASS canon_600_fixed_wb(int temp)
{
static const short mul[4][5] = {
{667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}};
int lo, hi, i;
float frac = 0;
for (lo = 4; --lo;)
if (*mul[lo] <= temp)
break;
for (hi = 0; hi < 3; hi++)
if (*mul[hi] >= temp)
break;
if (lo != hi)
frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i = 1; i < 5; i++)
pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color(int ratio[2], int mar)
{
int clipped = 0, target, miss;
if (flash_used)
{
if (ratio[1] < -104)
{
ratio[1] = -104;
clipped = 1;
}
if (ratio[1] > 12)
{
ratio[1] = 12;
clipped = 1;
}
}
else
{
if (ratio[1] < -264 || ratio[1] > 461)
return 2;
if (ratio[1] < -50)
{
ratio[1] = -50;
clipped = 1;
}
if (ratio[1] > 307)
{
ratio[1] = 307;
clipped = 1;
}
}
target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped)
return 0;
miss = target - ratio[0];
if (abs(miss) >= mar * 4)
return 2;
if (miss < -20)
miss = -20;
if (miss > mar)
miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = {0, 0};
int test[8], total[2][8], ratio[2][2], stat[2];
memset(&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10)
mar = 150;
else if (i > 12)
mar = 20;
else
mar = 280 - 20 * i;
if (flash_used)
mar = 80;
for (row = 14; row < height - 14; row += 4)
for (col = 10; col < width; col += 2)
{
for (i = 0; i < 8; i++)
test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1));
for (i = 0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500)
goto next;
for (i = 0; i < 4; i++)
if (abs(test[i] - test[i + 4]) > 50)
goto next;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 4; j += 2)
ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j];
stat[i] = canon_600_color(ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1)
goto next;
for (i = 0; i < 2; i++)
if (stat[i])
for (j = 0; j < 2; j++)
test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10;
for (i = 0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next:;
}
if (count[0] | count[1])
{
st = count[0] * 200 < count[1];
for (i = 0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409},
{-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007},
{-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528},
{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}};
int t = 0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789)
t = 1;
if (mc > 1.28 && mc <= 2)
{
if (yc < 0.8789)
t = 3;
else if (yc <= 2)
t = 4;
}
if (flash_used)
t = 5;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow = row = 0; irow < height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data, 1, 1120, ifp) < 1120)
derror();
pix = raw_image + row * raw_width;
for (dp = data; dp < data + 1120; dp += 10, pix += 8)
{
pix[0] = (dp[0] << 2) + (dp[1] >> 6);
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6);
}
if ((row += 2) > height)
row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}};
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
{
if ((val = BAYER(row, col) - black) < 0)
val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row, col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row = 0; row < 100; row++)
{
fseek(ifp, row * 3340 + 3284, SEEK_SET);
if (getc(ifp) > 15)
return 1;
}
return 0;
}
unsigned CLASS getbithuff(int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf = 0;
static int vbits = 0, reset = 0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25)
return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0)
return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp)))
{
bitbuf = (bitbuf << 8) + (uchar)c;
vbits += 8;
}
c = bitbuf << (32 - vbits) >> (32 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
c = (uchar)huff[c];
}
else
vbits -= nbits;
if (vbits < 0)
derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n, 0)
#define gethuff(h) getbithuff(*h, h + 1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort *CLASS make_decoder_ref(const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max = 16; max && !count[max]; max--)
;
huff = (ushort *)calloc(1 + (1 << max), sizeof *huff);
merror(huff, "make_decoder()");
huff[0] = max;
for (h = len = 1; len <= max; len++)
for (i = 0; i < count[len]; i++, ++*source)
for (j = 0; j < 1 << (max - len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); }
void CLASS crw_init_tables(unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff},
{0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0,
0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff},
{0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff},
};
static const uchar second_tree[3][180] = {
{0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04,
0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0,
0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29,
0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9,
0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91,
0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4,
0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7,
0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64,
0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3,
0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff},
{0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03,
0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32,
0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61,
0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59,
0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56,
0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85,
0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82,
0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9,
0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64,
0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff},
{0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05,
0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22,
0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58,
0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48,
0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88,
0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94,
0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a,
0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62,
0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1,
0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}};
if (table > 2)
table = 2;
huff[0] = make_decoder(first_tree[table]);
huff[1] = make_decoder(second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret = 1, i;
fseek(ifp, 0, SEEK_SET);
fread(test, 1, sizeof test, ifp);
for (i = 540; i < sizeof test - 1; i++)
if (test[i] == 0xff)
{
if (test[i + 1])
return 1;
ret = 0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2];
crw_init_tables(tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits)
maximum = 0x3ff;
fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
nblocks = MIN(8, raw_height - row) * raw_width >> 6;
for (block = 0; block < nblocks; block++)
{
memset(diffbuf, 0, sizeof diffbuf);
for (i = 0; i < 64; i++)
{
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i)
break;
if (leaf == 0xff)
continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0)
continue;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
if (i < 64)
diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i = 0; i < 64; i++)
{
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits)
{
save = ftell(ifp);
fseek(ifp, 26 + row * raw_width / 4, SEEK_SET);
for (prow = pixel, i = 0; i < raw_width * 2; i++)
{
c = fgetc(ifp);
for (r = 0; r < 8; r += 2, prow++)
{
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512)
val += 2;
*prow = val;
}
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
FORC(2) free(huff[c]);
throw;
}
#endif
FORC(2) free(huff[c]);
}
//@end COMMON
struct jhead
{
int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6];
ushort quant[64], idct[64], *huff[20], *free[20], *row;
};
//@out COMMON
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
if (row < raw_height && col < raw_width)
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,
47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
int bypp = tiff_bps <= 8 ? 1 : 2;
int bufsize = width * 3 * bypp;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width > 32767 || raw_height > 32767)
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixel = raw_width*(raw_height+7);
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)
if(todo[i] < maxpixel)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
else
derror();
}
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)
{
#ifdef LIBRAW_LIBRARY_BUILD
if(!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
int row, col;
#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);
}
}
if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF;
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[0x4002];
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(width>640 || height > 480)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
// All kodak radc images are 768x512
if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if (!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
if(col>=0)
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[272]; /* 264 looks enough */
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
{
int idx = ret ? buf[i] : (pred[i & 1] += buf[i]);
if (idx >= 0 && idx < 0xffff)
{
if ((RAW(row, col + i) = curve[idx]) >> 12)
derror();
}
else
derror();
}
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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];
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung
throw LIBRAW_EXCEPTION_IO_BADFILE;
#endif
unsigned maxpixels = raw_width*(raw_height+7);
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)];
unsigned idest = RAWINDEX(row, col + c);
unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0);
if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion
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);
else
derror();
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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()
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!image)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
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++)
if(fabs(num)>0.00001f)
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 & 0x55555555U) << 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)
{
#ifdef LIBRAW_IOSPACE_CHECK
INT64 pos = ftell(ifp);
INT64 fsize = ifp->size();
if(fsize < 12 || (fsize-pos) < 12)
throw LIBRAW_EXCEPTION_IO_EOF;
#endif
*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 libraw_powf64l(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 libraw_powf64l(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
unsigned CLASS setCanonBodyFeatures(unsigned id)
{
if (id == 0x03740000) // EOS M3
id = 0x80000374;
else if (id == 0x03840000) // EOS M10
id = 0x80000384;
else if (id == 0x03940000) // EOS M5
id = 0x80000394;
else if (id == 0x04070000) // EOS M6
id = 0x80000407;
else if (id == 0x03980000) // EOS M100
id = 0x80000398;
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) || // M6
(id == 0x80000398) // M100
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return id;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
if (maxlen < 16)
return; // too short
CameraInfo[0] = 0;
CameraInfo[1] = 0;
if (type == 4)
{
if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) ||
(maxlen == 171) || (maxlen == 264) || (maxlen > 400))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2));
else if (maxlen == 72)
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2));
else if ((maxlen == 85) || (maxlen == 93))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2));
else if ((maxlen == 96) || (maxlen == 104))
imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2));
}
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
imgdata.other.CameraTemperature = 0.0f;
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x80000398) || // M100
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000))) // G1 X Mark III
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if (id == 0x5330303638ULL)
{
strcpy(model, "E-M10MarkIII");
}
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 24, SEEK_CUR);
tempAp = get2();
if (tempAp != 0)
imgdata.other.CameraTemperature = (float)(tempAp - 128);
tempAp = get2();
if (tempAp != -1)
imgdata.other.FlashGN = ((float)tempAp) / 32;
get2();
// fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x000c)
{
unsigned tS = get4();
sprintf (imgdata.shootinginfo.BodySerial, "%d", tS);
}
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 == 0x009a)
{
get4();
imgdata.sizes.raw_crop.cwidth = get4();
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cleft = get4();
imgdata.sizes.raw_crop.ctop = get4();
}
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 == 0x4013)
{
get4();
imgdata.makernotes.canon.AFMicroAdjMode = get4();
imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4());
}
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 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2cf << 1), SEEK_SET); // offset 719 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x04180000) || // G1 X Mark III
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000398) || // EOS M100
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x1fc << 1), SEEK_SET); // offset 508 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x2dc << 1), SEEK_SET); // offset 732 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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 + (0x230 << 1), SEEK_SET); // offset 560 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts
imgdata.makernotes.canon.NormalWhiteLevel = get2();
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) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
libraw_powf64l(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 =
libraw_powf64l(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 =
libraw_powf64l(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)
{
ushort idx;
static const struct
{
ushort scf[8];
/*
scf[0] camera id
scf[1] camera format
scf[2] camera mount: Minolta A, Sony E, fixed,
scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC
scf[4] lens mount
scf[5] tag 0x2010 group (0 if not used)
scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid
scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid
*/
} SonyCamFeatures[] = {
{256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{267, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{268, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{271, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{272, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{276, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{277, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff},
{284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff},
{285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff},
{286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd},
{288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd},
{289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd},
{291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd},
{293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd},
{294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa},
{295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff},
{298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{301, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa},
{303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa},
{304, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa},
{306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa},
{308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff},
{309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff},
{311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa},
{314, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{315, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{316, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff},
{318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{320, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{321, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{322, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{323, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{324, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{325, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{326, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{327, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{328, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{329, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{330, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{331, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{332, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{333, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{334, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{335, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{336, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{337, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{338, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff},
{341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{343, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{345, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0},
{347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{348, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{349, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb},
{351, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{352, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0},
{354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd},
{355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{359, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd},
{361, 0, 0, 0, 0, 0, 0xffff, 0xffff},
{362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f},
{363, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 0, 0x0320, 0x019f},
{364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff},
{365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff},
};
imgdata.lens.makernotes.CamID = id;
if (id == 2)
{
imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
imgdata.makernotes.sony.group2010 = 0;
imgdata.makernotes.sony.real_iso_offset = 0xffff;
imgdata.makernotes.sony.ImageCount3_offset = 0xffff;
return;
}
else
idx = id - 256;
if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures))
{
if (!SonyCamFeatures[idx].scf[2])
return;
imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1];
imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2];
imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3];
if (SonyCamFeatures[idx].scf[4])
imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4];
imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5];
imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6];
imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7];
}
char *sbstr = strstr(software, " v");
if (sbstr != NULL)
{
sbstr += 2;
imgdata.makernotes.sony.firmware = atof(sbstr);
if ((id == 306) || (id == 311))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if (id == 312)
{
if (imgdata.makernotes.sony.firmware < 2.0f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01aa;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01c0;
}
else if ((id == 318) || (id == 340))
{
if (imgdata.makernotes.sony.firmware < 1.2f)
imgdata.makernotes.sony.ImageCount3_offset = 0x01a0;
else
imgdata.makernotes.sony.ImageCount3_offset = 0x01b6;
}
}
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id)
{
short bufx;
if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2))
bufx = buf[1];
else if ((id >= 273) && (len >= 3))
bufx = buf[2];
else
return;
imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f;
}
void CLASS process_Sony_0x2010(uchar *buf, ushort len)
{
if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) ||
(len < (imgdata.makernotes.sony.real_iso_offset + 2)))
return;
if (imgdata.other.real_ISO < 0.1f)
{
uchar s[2];
s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]];
s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id)
{
ushort lid;
uchar s[4];
int c;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (len < 2)
return;
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(libraw_powf64l(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(libraw_powf64l(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 (len <= 0x106)
return;
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = libraw_powf64l(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)
{
if (len <= 0x108)
return;
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if (len <= 0x10a)
return;
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))
{
if (len <= 0x116)
return;
// "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)
{
if (len <= 0x117)
return;
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
}
if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362) || (id == 363))
{
if (len <= 0x8d)
return;
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)
{
if (len <= 0xf4)
return;
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))
{
if (len <= 0x7f)
return;
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);
}
if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) &&
(len >= (imgdata.makernotes.sony.ImageCount3_offset + 4)))
{
FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]];
imgdata.makernotes.sony.ImageCount3 = sget4(s);
}
if (id == 362)
{
for (c = 0; c < 6; c++)
{
imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]];
}
}
return;
}
void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id)
{
uchar s[4];
int c;
short bufx = buf[0];
if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f))
{ // 0x9400 'c' version
if ((id == 358) || (id == 362) || (id == 363) || (id == 365))
{
imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]];
}
else
{
FORC4 s[c] = SonySubstitution[buf[0x0a + c]];
imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s);
}
imgdata.makernotes.sony.Sony0x9400_version = 0xc;
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]];
FORC4 s[c] = SonySubstitution[buf[0x12 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots
FORC4 s[c] = SonySubstitution[buf[0x1a + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files
}
else if ((bufx == 0x0c) && (len >= 0x1f))
{ // 0x9400 'b' version
imgdata.makernotes.sony.Sony0x9400_version = 0xb;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]];
}
else if ((bufx == 0x0a) && (len >= 0x23))
{ // 0x9400 'a' version
imgdata.makernotes.sony.Sony0x9400_version = 0xa;
FORC4 s[c] = SonySubstitution[buf[0x08 + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s);
FORC4 s[c] = SonySubstitution[buf[0x0c + c]];
imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s);
imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]];
imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]];
}
else
return;
}
void CLASS process_Sony_0x9402(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) ||
(imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA))
return;
if (len < 5)
return;
short bufx = buf[0x00];
if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff))
return;
imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]);
return;
}
void CLASS process_Sony_0x9403(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = SonySubstitution[buf[4]];
if ((bufx == 0x00) || (bufx == 0x94))
return;
imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]);
return;
}
void CLASS process_Sony_0x9406(uchar *buf, ushort len)
{
if (len < 6)
return;
short bufx = buf[0];
if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b))
return;
bufx = buf[2];
if ((bufx != 0x08) && (bufx != 0x1b))
return;
imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f;
return;
}
void CLASS process_Sony_0x940c(uchar *buf, ushort len)
{
if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) &&
(imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX))
return;
if (len <= 0x000a)
return;
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_0x940e(uchar *buf, ushort len, unsigned id)
{
if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]];
}
else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051))
{
imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]];
}
else
return;
if (imgdata.makernotes.sony.AFMicroAdjValue != 0)
imgdata.makernotes.sony.AFMicroAdjOn = 1;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116,
ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len,
uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400,
ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len,
uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406,
ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len,
uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x0116_len)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
if (table_buf_0x2010_len)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
if (table_buf_0x9050_len)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
if (table_buf_0x9400_len)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
if (table_buf_0x9402_len)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
if (table_buf_0x9403_len)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
if (table_buf_0x9406_len)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
if (table_buf_0x940c_len)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
if (table_buf_0x940e_len)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id);
free(table_buf_0x940e);
table_buf_0x940e_len = 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]);
if (len == 5478)
{
imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20;
imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0);
imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f;
}
}
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 = libraw_powf64l(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 == 0x3000) && (len < 256000))
{
uchar *table_buf_0x3000;
table_buf_0x3000 = (uchar *)malloc(len);
fread(table_buf_0x3000, len, 1, ifp);
for (int i = 0; i < 20; i++)
imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i];
}
else if (tag == 0x0116 && len < 256000)
{
table_buf_0x0116 = (uchar *)malloc(len);
table_buf_0x0116_len = len;
fread(table_buf_0x0116, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x0116);
table_buf_0x0116_len = 0;
}
}
else if (tag == 0x2010 && len < 256000)
{
table_buf_0x2010 = (uchar *)malloc(len);
table_buf_0x2010_len = len;
fread(table_buf_0x2010, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len);
free(table_buf_0x2010);
table_buf_0x2010_len = 0;
}
}
else if (tag == 0x201a)
{
imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4();
}
else if (tag == 0x201b)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.shootinginfo.FocusMode = (short)uc;
}
else if (tag == 0x202c)
{
imgdata.makernotes.sony.MeteringMode2 = get2();
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_len = len;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_len = 0;
}
}
else if (tag == 0x9400 && len < 256000)
{
table_buf_0x9400 = (uchar *)malloc(len);
table_buf_0x9400_len = len;
fread(table_buf_0x9400, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id);
free(table_buf_0x9400);
table_buf_0x9400_len = 0;
}
}
else if (tag == 0x9402 && len < 256000)
{
table_buf_0x9402 = (uchar *)malloc(len);
table_buf_0x9402_len = len;
fread(table_buf_0x9402, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len);
free(table_buf_0x9402);
table_buf_0x9402_len = 0;
}
}
else if (tag == 0x9403 && len < 256000)
{
table_buf_0x9403 = (uchar *)malloc(len);
table_buf_0x9403_len = len;
fread(table_buf_0x9403, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len);
free(table_buf_0x9403);
table_buf_0x9403_len = 0;
}
}
else if ((tag == 0x9405) && (len < 256000) && (len > 0x64))
{
uchar *table_buf_0x9405;
table_buf_0x9405 = (uchar *)malloc(len);
fread(table_buf_0x9405, len, 1, ifp);
uchar bufx = table_buf_0x9405[0x0];
if (imgdata.other.real_ISO < 0.1f)
{
if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) ||
(bufx == 0xb3) || (bufx == 0xe1))
{
uchar s[2];
s[0] = SonySubstitution[table_buf_0x9405[0x04]];
s[1] = SonySubstitution[table_buf_0x9405[0x05]];
imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f));
}
}
free(table_buf_0x9405);
}
else if (tag == 0x9406 && len < 256000)
{
table_buf_0x9406 = (uchar *)malloc(len);
table_buf_0x9406_len = len;
fread(table_buf_0x9406, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len);
free(table_buf_0x9406);
table_buf_0x9406_len = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_len = len;
fread(table_buf_0x940c, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len);
free(table_buf_0x940c);
table_buf_0x940c_len = 0;
}
}
else if (tag == 0x940e && len < 256000)
{
table_buf_0x940e = (uchar *)malloc(len);
table_buf_0x940e_len = len;
fread(table_buf_0x940e, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID);
free(table_buf_0x940e);
table_buf_0x940e_len = 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);
}
else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2))
{
imgdata.sizes.raw_crop.cheight = get4();
imgdata.sizes.raw_crop.cwidth = get4();
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
short nWB, tWB;
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) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) ||
(tag == 0x2050) || (tag == 0x3000))
{
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;
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
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;
}
}
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];
}
}
}
else 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;
}
else 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;
}
else 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();
}
}
else 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;
}
}
else 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();
}
else
{
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(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 0x20200306:
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
break;
case 0x20200307:
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{ /*placeholder */
}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
unsigned typeCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x0116;
ushort table_buf_0x0116_len = 0;
uchar *table_buf_0x2010;
ushort table_buf_0x2010_len = 0;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_len = 0;
uchar *table_buf_0x9400;
ushort table_buf_0x9400_len = 0;
uchar *table_buf_0x9402;
ushort table_buf_0x9402_len = 0;
uchar *table_buf_0x9403;
ushort table_buf_0x9403_len = 0;
uchar *table_buf_0x9406;
ushort table_buf_0x9406_len = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_len = 0;
uchar *table_buf_0x940e;
ushort table_buf_0x940e_len = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
/*
printf("===>>buf: 0x");
for (int i = 0; i < sizeof buf; i ++) {
printf("%02x", buf[i]);
}
putchar('\n');
*/
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) ||
!strncasecmp(model, "KODAK P712", 10))
{
if (tag == 0xf90b)
{
imgdata.makernotes.kodak.clipBlack = get2();
}
else if (tag == 0xf90c)
{
imgdata.makernotes.kodak.clipWhite = get2();
}
}
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
if (type != 4)
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len));
fread(CanonCameraInfo, len, 1, ifp);
}
else
{
CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4));
fread(CanonCameraInfo, len, 4, ifp);
}
lenCanonCameraInfo = len;
typeCanonCameraInfo = type;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
unique_id = setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) ||
!strncasecmp(model, "Hasselblad A6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if (tag == 0x34003402)
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) &&
!strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x003b) // all 1s for regular exposures
{
imgdata.makernotes.nikon.ME_WB[0] = getreal(type);
imgdata.makernotes.nikon.ME_WB[2] = getreal(type);
imgdata.makernotes.nikon.ME_WB[1] = getreal(type);
imgdata.makernotes.nikon.ME_WB[3] = getreal(type);
}
else if (tag == 0x0045)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 0x00b0)
{
get4(); // ME tag version, 4 symbols
imgdata.makernotes.nikon.ExposureMode = get4();
imgdata.makernotes.nikon.nMEshots = get4();
imgdata.makernotes.nikon.MEgainOn = get4();
}
else if (tag == 0x00b9)
{
uchar uc;
int8_t sc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTune = uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneIndex = uc;
fread(&sc, 1, 1, ifp);
imgdata.makernotes.nikon.AFFineTuneAdj = sc;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2);
break;
case 0x20400612:
case 0x30000612:
imgdata.sizes.raw_crop.cleft = get2();
break;
case 0x20400613:
case 0x30000613:
imgdata.sizes.raw_crop.ctop = get2();
break;
case 0x20400614:
case 0x30000614:
imgdata.sizes.raw_crop.cwidth = get2();
break;
case 0x20400615:
case 0x30000615:
imgdata.sizes.raw_crop.cheight = get2();
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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(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 = libraw_powf64l(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x1007:
imgdata.other.SensorTemperature = (float)get2();
break;
case 0x1008:
imgdata.other.LensTemperature = (float)get2();
break;
case 0x20401306:
{
int temp = get2();
if ((temp != 0) && (temp != 100))
{
if (temp < 61)
imgdata.other.CameraTemperature = (float)temp;
else
imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f;
if ((OlyID == 0x4434353933ULL) && // TG-5
(imgdata.other.exifAmbientTemperature > -273.15f))
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
}
}
break;
case 0x20501500:
if (OlyID != 0x0ULL)
{
short temp = get2();
if ((OlyID == 0x4434303430ULL) || // E-1
(OlyID == 0x5330303336ULL) || // E-M5
(len != 1))
imgdata.other.SensorTemperature = (float)temp;
else if ((temp != -32768) && (temp != 0))
{
if (temp > 199)
imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp;
else
imgdata.other.SensorTemperature = (float)temp;
}
}
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x000d)
{
imgdata.makernotes.pentax.FocusMode = get2();
}
else if (tag == 0x000e)
{
imgdata.makernotes.pentax.AFPointSelected = get2();
}
else if (tag == 0x000f)
{
imgdata.makernotes.pentax.AFPointsInFocus = getint(type);
}
else if (tag == 0x0010)
{
imgdata.makernotes.pentax.FocusPosition = get2();
}
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 == 0x0034)
{
uchar uc;
FORC4
{
fread(&uc, 1, 1, ifp);
imgdata.makernotes.pentax.DriveMode[c] = uc;
}
}
else if (tag == 0x0038)
{
imgdata.sizes.raw_crop.cleft = get2();
imgdata.sizes.raw_crop.ctop = get2();
}
else if (tag == 0x0039)
{
imgdata.sizes.raw_crop.cwidth = get2();
imgdata.sizes.raw_crop.cheight = get2();
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x0047)
{
imgdata.other.CameraTemperature = (float)fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x0072)
{
imgdata.makernotes.pentax.AFAdjustment = get2();
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0x0043)
{
int temp = get4();
if (temp)
{
imgdata.other.CameraTemperature = (float)temp;
if (get4() == 10)
imgdata.other.CameraTemperature /= 10.0f;
}
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010,
table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400,
table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403,
table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c,
table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len);
}
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 * libraw_powf64l(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 * libraw_powf64l(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = libraw_powf64l(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = libraw_powf64l(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 == 0x20200306)
{
uchar uc;
fread(&uc, 1, 1, ifp);
imgdata.makernotes.olympus.AFFineTune = uc;
}
if (tag == 0x20200307)
{
FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2();
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) &&
((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(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 = libraw_powf64l(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = libraw_powf64l(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, MIN(len,511), ifp);
mn_text[511] = 0;
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=");
if(pos)
{
pos +=4;
char *pos2 = strstr(pos, " ");
if(pos2)
{
l = pos2 - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
#if defined WIN32 || defined(__MINGW32__)
// Win32 strtok is already thread-safe
pos = strtok(ccms, ",");
#else
char *last=0;
pos = strtok_r(ccms, ",",&last);
#endif
if(pos)
{
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];
#if defined WIN32 || defined(__MINGW32__)
pos = strtok(NULL, ",");
#else
pos = strtok_r(NULL, ",",&last);
#endif
if(!pos) goto end; // broken
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
}
}
end:;
}
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) * 0x01010101U << 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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
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) * 0x01010101U * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
else if(len < 1)
return;
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 j, c, wbi = -2, romm_camTemp[9], romm_camScale[3];
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)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1003)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 1004)
imgdata.sizes.raw_crop.ctop = get2();
if (tag == 1005)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 1006)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 1007)
imgdata.makernotes.kodak.BlackLevelTop = get2();
if (tag == 1008)
imgdata.makernotes.kodak.BlackLevelBottom = get2();
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 1030) && (len == 1))
imgdata.other.CameraTemperature = getreal(type);
if ((tag == 1043) && (len == 1))
imgdata.other.SensorTemperature = getreal(type);
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9))
{
short validM = 0;
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type);
}
validM = 1;
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
validM = 1;
}
}
if (validM)
{
romm_coeff(imgdata.makernotes.kodak.romm_camDaylight);
}
}
if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9))
{
if (type == 10)
{
for (j = 0; j < 9; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type);
}
}
else if (type == 9)
{
FORC3
{
romm_camScale[c] = 0;
for (j = 0; j < 3; j++)
{
romm_camTemp[c * 3 + j] = get4();
romm_camScale[c] += romm_camTemp[c * 3 + j];
}
}
if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff))
{
FORC3 for (j = 0; j < 3; j++)
{
((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] =
((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]);
}
}
}
}
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 == 0xfa13)
width = getint(type);
if (tag == 0xfa14)
height = (getint(type) + 1) & -2;
/*
height = getint(type);
if (tag == 0xfa16)
raw_width = get2();
if (tag == 0xfa17)
raw_height = get2();
*/
if (tag == 0xfa18)
{
imgdata.makernotes.kodak.offset_left = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_left += 1;
}
if (tag == 0xfa19)
{
imgdata.makernotes.kodak.offset_top = getint(8);
if (type != 8)
imgdata.makernotes.kodak.offset_top += 1;
}
if (tag == 0xfa31)
imgdata.sizes.raw_crop.cwidth = get2();
if (tag == 0xfa32)
imgdata.sizes.raw_crop.cheight = get2();
if (tag == 0xfa3e)
imgdata.sizes.raw_crop.cleft = get2();
if (tag == 0xfa3f)
imgdata.sizes.raw_crop.ctop = get2();
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 && savepos + len > 2 * fsize)
{
fseek(ifp, save, SEEK_SET); // Recover tiff-read position!!
continue;
}
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), 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:
if (len == 3)
{
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
else if (len == 1)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here??
}
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;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 10:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_bpp = get2();
}
break;
#endif
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;
case 0x0120:
if (pana_raw)
{
unsigned sorder = order;
unsigned long sbase = base;
base = ftell(ifp);
order = get2();
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, get4()-8, SEEK_CUR);
parse_tiff_ifd (base);
base = sbase;
order = sorder;
}
break;
case 0x2009:
if ((libraw_internal_data.unpacker_data.pana_encoding == 4) ||
(libraw_internal_data.unpacker_data.pana_encoding == 5))
{
int n = MIN (8, len);
int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4};
imgdata.makernotes.panasonic.BlackLevelDim = len;
for (int i=0; i < n; i++)
{
imgdata.makernotes.panasonic.BlackLevel[permut[i]] =
(float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp));
}
}
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;
#ifdef LIBRAW_LIBRARY_BUILD
case 45:
if (pana_raw && len == 1 && type == 3)
{
libraw_internal_data.unpacker_data.pana_encoding = get2();
}
break;
#endif
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 */
if ((pana_raw) && (tag == 11) && (type == 3))
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.makernotes.panasonic.Compression = get2();
#endif
break;
}
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++)
{
if(cfa_pat[i] > 31) continue; // Skip wrong data
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0x9400:
imgdata.other.exifAmbientTemperature = getreal(type);
if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5
imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature;
break;
case 0x9401:
imgdata.other.exifHumidity = getreal(type);
break;
case 0x9402:
imgdata.other.exifPressure = getreal(type);
break;
case 0x9403:
imgdata.other.exifWaterDepth = getreal(type);
break;
case 0x9404:
imgdata.other.exifAcceleration = getreal(type);
break;
case 0x9405:
imgdata.other.exifCameraElevationAngle = getreal(type);
break;
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4
{
int q = get2();
if(q > 0) cam_mul[c ^ 1] = 4096.0 / q;
}
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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") &&
strcmp(model, "X-A5") &&
strcmp(model, "X-A20"))
{
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);
if(len>0)
{
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 */
{
float q1 = getreal(type);
float q2 = getreal(type);
if(q1 > 0.00001f && q2 > 0.00001f)
{
pixel_aspect = q1/q2;
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0];
imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1];
}
}
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);
if (!strncasecmp(make, "SONY", 4))
{
imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2];
imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3];
}
}
break;
case 0x74c7:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cleft = get4();
imgdata.makernotes.sony.raw_crop.ctop = get4();
}
break;
case 0x74c8:
if ((len == 2) && !strncasecmp(make, "SONY", 4))
{
imgdata.makernotes.sony.raw_crop.cwidth = get4();
imgdata.makernotes.sony.raw_crop.cheight = get4();
}
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;
INT64 save_pos = ifp->tell();
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
curr_pos = save_pos + MakN_length - 6;
fseek(ifp, curr_pos, SEEK_SET);
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "SR2 ", 4))
{
order = 0x4d4d;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
unsigned *buf_SR2;
uchar *cbuf_SR2;
unsigned icbuf_SR2;
unsigned entries, tag, type, len, save;
int ival;
unsigned SR2SubIFDOffset = 0;
unsigned SR2SubIFDLength = 0;
unsigned SR2SubIFDKey = 0;
int base = curr_pos + 6 - pos_in_original_raw;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 0x7200)
{
SR2SubIFDOffset = get4();
}
else if (tag == 0x7201)
{
SR2SubIFDLength = get4();
}
else if (tag == 0x7221)
{
SR2SubIFDKey = get4();
}
fseek(ifp, save, SEEK_SET);
}
if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety
{
fseek(ifp, SR2SubIFDOffset + base, SEEK_SET);
fread(buf_SR2, SR2SubIFDLength, 1, ifp);
sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey);
cbuf_SR2 = (uchar *)buf_SR2;
entries = sget2(cbuf_SR2);
icbuf_SR2 = 2;
while (entries--)
{
tag = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
type = sget2(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 2;
len = sget4(cbuf_SR2 + icbuf_SR2);
icbuf_SR2 += 4;
if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4)
{
ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset;
}
else
{
ival = icbuf_SR2;
}
if(ival > SR2SubIFDLength) // points out of orig. buffer size
break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter
icbuf_SR2 += 4;
switch (tag)
{
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c);
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
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] =
sget2(cbuf_SR2 + ival + 2 * c);
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] = sget2(cbuf_SR2 + ival + 2 * c);
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
}
}
free(buf_SR2);
}
} /* SR2 processed */
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
if(fabs(asn[c])>0.0001)
cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC if(fabs(cc[c][c])>0.0001) 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( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535
|| tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535)
continue; /* wrong image dimensions */
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:
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height))
#else
if (tiff_ifd[raw].bytes == raw_width * raw_height)
#endif
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
#else
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
#endif
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps))
#else
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
#endif
{
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) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 &&
INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ
{
tiff_bps = 14;
tiff_samples = 4;
load_raw = &CLASS sony_arq_load_raw;
filters = 0;
strcpy(cdesc, "RGBG");
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL)
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
#endif
load_flags = 24;
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL)
#else
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
#endif
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height))
#else
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
#endif
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:
#ifdef LIBRAW_LIBRARY_BUILD
if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes))
#else
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
#endif
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes))
#else
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
#endif
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL)
{
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 (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL)
{
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;
#ifdef LIBRAW_LIBRARY_BUILD
if(offset>ifp->size()-8) // At least 8 bytes for tag/len
offset = ifp->size()-8;
#endif
while ((save = ftell(ifp)) < offset)
{
for (tag = i = 0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
if(len < 0)
return; // just ignore wrong len?? or raise bad file exception?
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 = libraw_powf64l(2.0f, -int_to_float((get4(), get4())));
aperture = libraw_powf64l(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 = libraw_powf64l(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 = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = libraw_powf64l(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
{
ushort q = get2();
cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024;
}
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
unique_id = setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0211:
imgdata.other.SensorTemperature2 = int_to_float(data);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = libraw_powf64l(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 = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.SensorTemperature = ph1.tag_210;
#endif
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED;
#endif
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/
}
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x110)
{
imgdata.sizes.raw_crop.ctop = get2();
imgdata.sizes.raw_crop.cleft = get2();
}
else if (tag == 0x111)
{
imgdata.sizes.raw_crop.cheight = get2();
imgdata.sizes.raw_crop.cwidth = get2();
}
else if ((tag == 0x122) && !strcmp(model, "DBP for GX680"))
{
int k = get2();
int l = get2(); /* margins? */
int m = get2(); /* margins? */
int n = get2();
// printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n);
}
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") ||
!strcmp(model, "X-A5") ||
!strcmp(model, "X-A20"))
{
int wb[4];
int nWB, tWB, pWB;
int iCCT = 0;
int cnt;
fseek(ifp, save + 0x200, SEEK_SET);
for (int wb_ind = 0; wb_ind < 42; wb_ind++)
{
nWB = get4();
tWB = get4();
wb[0] = get4() << 1;
wb[1] = get4();
wb[3] = get4();
wb[2] = get4() << 1;
if (tWB && (iCCT < 255))
{
imgdata.color.WBCT_Coeffs[iCCT][0] = tWB;
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt];
iCCT++;
}
if (nWB != 70)
{
for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2)
{
if (Fuji_wb_list2[pWB] == nWB)
{
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt];
break;
}
}
}
}
}
else
{
libraw_internal_data.unpacker_data.posRAFData = save;
libraw_internal_data.unpacker_data.lenRAFData = (len >> 1);
}
#endif
order = c;
}
fseek(ifp, save + len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg(int offset)
{
int len, save, hlen, mark;
fseek(ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)
{
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)
{
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150
#ifdef LIBRAW_LIBRARY_BUILD
&& (save + hlen) >= 0 && (save + hlen) <= ifp->size()
#endif
) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(save + hlen, len - hlen, 0);
}
if (parse_tiff(save + 6))
apply_tiff();
fseek(ifp, save + len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
struct tm t;
order = 0x4949;
fread(tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4))
{
int maxloop = 1000;
get4();
while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--)
parse_riff();
}
else if (!memcmp(tag, "nctg", 4))
{
while (ftell(ifp) + 7 < end)
{
i = get2();
size = get2();
if ((i + 1) >> 1 == 10 && size == 20)
get_timestamp(0);
else
fseek(ifp, size, SEEK_CUR);
}
}
else if (!memcmp(tag, "IDIT", 4) && size < 64)
{
fread(date, 64, 1, ifp);
date[size] = 0;
memset(&t, 0, sizeof t);
if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6)
{
for (i = 0; i < 12 && strcasecmp(mon[i], month); i++)
;
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
}
else
fseek(ifp, size, SEEK_CUR);
}
void CLASS parse_qt(int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp) + 7 < end)
{
save = ftell(ifp);
if ((size = get4()) < 8)
return;
fread(tag, 4, 1, ifp);
if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4))
parse_qt(save + size);
if (!memcmp(tag, "CNDA", 4))
parse_jpeg(ftell(ifp));
fseek(ifp, save + size, SEEK_SET);
}
}
void CLASS parse_smal(int offset, int fsize)
{
int ver;
fseek(ifp, offset + 2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek(ifp, 5, SEEK_CUR);
if (get4() != fsize)
return;
if (ver > 6)
data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy(make, "SMaL");
sprintf(model, "v%d %dx%d", ver, width, height);
if (ver == 6)
load_raw = &CLASS smal_v6_load_raw;
if (ver == 9)
load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek(ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4()))
timestamp = i;
fseek(ifp, off_head + 4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(), get2())
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 16:
load_raw = &CLASS unpacked_load_raw;
}
fseek(ifp, off_setup + 792, SEEK_SET);
strcpy(make, "CINE");
sprintf(model, "%d", get4());
fseek(ifp, 12, SEEK_CUR);
switch ((i = get4()) & 0xffffff)
{
case 3:
filters = 0x94949494;
break;
case 4:
filters = 0x49494949;
break;
default:
is_raw = 0;
}
fseek(ifp, 72, SEEK_CUR);
switch ((get4() + 3600) % 360)
{
case 270:
flip = 4;
break;
case 180:
flip = 1;
break;
case 90:
flip = 7;
break;
case 0:
flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek(ifp, 668, SEEK_CUR);
shutter = get4() / 1000000000.0;
fseek(ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek(ifp, shot_select * 8, SEEK_CUR);
data_offset = (INT64)get4() + 8;
data_offset += (INT64)get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek(ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek(ifp, 0, SEEK_END);
fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek(ifp, 0, SEEK_SET);
while ((len = get4()) != EOF)
{
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek(ifp, len - 8, SEEK_CUR);
}
}
else
{
rdvo = get4();
fseek(ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET);
data_offset = get4();
}
}
//@end COMMON
char *CLASS foveon_gets(int offset, char *str, int len)
{
int i;
fseek(ifp, offset, SEEK_SET);
for (i = 0; i < len - 1; i++)
if ((str[i] = get2()) == 0)
break;
str[i] = 0;
return str;
}
void CLASS parse_foveon()
{
int entries, img = 0, off, len, tag, save, i, wide, high, pent, poff[256][2];
char name[64], value[64];
order = 0x4949; /* Little-endian */
fseek(ifp, 36, SEEK_SET);
flip = get4();
fseek(ifp, -4, SEEK_END);
fseek(ifp, get4(), SEEK_SET);
if (get4() != 0x64434553)
return; /* SECd */
entries = (get4(), get4());
while (entries--)
{
off = get4();
len = get4();
tag = get4();
save = ftell(ifp);
fseek(ifp, off, SEEK_SET);
if (get4() != (0x20434553 | (tag << 24)))
return;
switch (tag)
{
case 0x47414d49: /* IMAG */
case 0x32414d49: /* IMA2 */
fseek(ifp, 8, SEEK_CUR);
pent = get4();
wide = get4();
high = get4();
if (wide > raw_width && high > raw_height)
{
switch (pent)
{
case 5:
load_flags = 1;
case 6:
load_raw = &CLASS foveon_sd_load_raw;
break;
case 30:
load_raw = &CLASS foveon_dp_load_raw;
break;
default:
load_raw = 0;
}
raw_width = wide;
raw_height = high;
data_offset = off + 28;
is_foveon = 1;
}
fseek(ifp, off + 28, SEEK_SET);
if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len - 28)
{
thumb_offset = off + 28;
thumb_length = len - 28;
write_thumb = &CLASS jpeg_thumb;
}
if (++img == 2 && !thumb_length)
{
thumb_offset = off + 24;
thumb_width = wide;
thumb_height = high;
write_thumb = &CLASS foveon_thumb;
}
break;
case 0x464d4143: /* CAMF */
meta_offset = off + 8;
meta_length = len - 28;
break;
case 0x504f5250: /* PROP */
pent = (get4(), get4());
fseek(ifp, 12, SEEK_CUR);
off += pent * 8 + 24;
if ((unsigned)pent > 256)
pent = 256;
for (i = 0; i < pent * 2; i++)
((int *)poff)[i] = off + get4() * 2;
for (i = 0; i < pent; i++)
{
foveon_gets(poff[i][0], name, 64);
foveon_gets(poff[i][1], value, 64);
if (!strcmp(name, "ISO"))
iso_speed = atoi(value);
if (!strcmp(name, "CAMMANUF"))
strcpy(make, value);
if (!strcmp(name, "CAMMODEL"))
strcpy(model, value);
if (!strcmp(name, "WB_DESC"))
strcpy(model2, value);
if (!strcmp(name, "TIME"))
timestamp = atoi(value);
if (!strcmp(name, "EXPTIME"))
shutter = atoi(value) / 1000000.0;
if (!strcmp(name, "APERTURE"))
aperture = atof(value);
if (!strcmp(name, "FLENGTH"))
focal_len = atof(value);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(name, "CAMSERIAL"))
strcpy(imgdata.shootinginfo.BodySerial, value);
if (!strcmp(name, "FLEQ35MM"))
imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value);
if (!strcmp(name, "IMAGERTEMP"))
imgdata.other.SensorTemperature = atof(value);
if (!strcmp(name, "LENSARANGE"))
{
char *sp;
imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MinAp4CurFocal = atof(sp);
if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal)
my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal);
}
}
if (!strcmp(name, "LENSFRANGE"))
{
char *sp;
imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value);
sp = strrchr(value, ' ');
if (sp)
{
imgdata.lens.makernotes.MaxFocal = atof(sp);
if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal)
my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal);
}
}
if (!strcmp(name, "LENSMODEL"))
{
char *sp;
imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value);
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = Sigma_X3F;
}
}
#endif
}
#ifdef LOCALTIME
timestamp = mktime(gmtime(×tamp));
#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,
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82,
{7034, -804, -1014, -4420, 12564, 2058, -851, 1994, 5758 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M100", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark III", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A20", 0, 0, /* temp */
{ 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-A5", 0, 0, /* temp */
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-E3", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-H1", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D850", 0, 0,
{ 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL9", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-G9", -15, 0,
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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-GH5s", -15, 0,
{ 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } },
{ "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-GF10", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "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 DC-GX9", -15, 0, /* temp */
{ 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } },
{ "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 } },
{ "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// {3984,0,0,0,10000,0,0,0,7666}},
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
// {2423,0,0,0,9901,0,0,0,7989}},
{ 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
// { 3984,0,0,0,10000,0,0,0,7666 } },
{10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{"Sony DSC-RX10M4", -800, 0,
{ 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{"Sony DSC-RX0", -800, 0, /* temp */
{ 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 16596,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 16596,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A550", 0, 16596,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */
{ 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-7M3", 0, 0,
{ 7374,-2389,-551,-5435,13162,2519,-1006,1795,6552 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM3", 0, 0,
{ 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } },
{ "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};
if(width > 2064) return 0.f; // too wide
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((unsigned char)string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x398, "EOS M100"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16b, "ILCE-7M3"}, {0x16c, "DSC-RX0"},
{0x16d, "DSC-RX10M4"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 =
imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature =
imgdata.other.exifAmbientTemperature = -1000.0f;
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT;
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 = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = libraw_powf64l(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 = libraw_powf64l(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
strncpy(model, head + 0x1c,0x20);
model[0x20]=0;
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4(); // bytes count
width = get2();
height = get2();
#ifdef LIBRAW_LIBRARY_BUILD
// Data integrity check
if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height))
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
/* no foveon support for dcraw build from libraw source */
parse_x3f();
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
break;
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
memmove(model, model + 8,strlen(model)-7);
if (!strncmp(model, "Digital Camera ", 15))
memmove(model, model + 15,strlen(model)-14);
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] * 0x01010101U;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c, A6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
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 = 0x01010101U * (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
/* alloc in unpack() may be fooled by size adjust */
|| ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535))
{
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 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 &&
tiff_ifd[sidx].dng_levels.default_crop[3] > 0)
{
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 libraw_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 libraw_tiff_tag tag[23];
int nextifd;
ushort pad2, nexif;
struct libraw_tiff_tag exif[4];
ushort pad3, ngps;
struct libraw_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 libraw_tiff_tag *tt;
int c;
tt = (struct libraw_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(×tamp);
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(×tamp));
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-835/c/good_581_0 |
crossvul-cpp_data_bad_2782_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT X X TTTTT %
% T X X T %
% T X T %
% T X X T %
% T X X T %
% %
% %
% Render Text Onto A Canvas Image. %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.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/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/pixel-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteTXTImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T X T %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTXT() returns MagickTrue if the image format type, identified by the magick
% string, is TXT.
%
% The format of the IsTXT method is:
%
% MagickBooleanType IsTXT(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 IsTXT(const unsigned char *magick,const size_t length)
{
#define MagickID "# ImageMagick pixel enumeration:"
char
colorspace[MaxTextExtent];
ssize_t
count;
unsigned long
columns,
depth,
rows;
if (length < 40)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,MagickID,strlen(MagickID)) != 0)
return(MagickFalse);
count=(ssize_t) sscanf((const char *) magick+32,"%lu,%lu,%lu,%s",&columns,
&rows,&depth,colorspace);
if (count != 4)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T E X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTEXTImage() reads a text file and returns it as an image. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadTEXTImage method is:
%
% Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
% char *text,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o text: the text storage buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadTEXTImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p,
text[MaxTextExtent];
DrawInfo
*draw_info;
Image
*image,
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+g%+g",(double)
image->columns,(double) image->rows,(double) page.x,(double) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset,
image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTXTImage() reads a text file and returns it as an image. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadTXTImage method is:
%
% Image *ReadTXTImage(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 *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MaxTextExtent],
text[MaxTextExtent];
Image
*image;
IndexPacket
*indexes;
long
x_offset,
y_offset;
MagickBooleanType
status;
MagickPixelPacket
pixel;
QuantumAny
range;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
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);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++)
if (depth >= 64)
break;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->matte=MagickFalse;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->matte=MagickTrue;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->colorspace=(ColorspaceType) type;
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
(void) SetImageBackgroundColor(image);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
blue,
green,
index,
opacity,
red;
red=0.0;
green=0.0;
blue=0.0;
index=0.0;
opacity=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&opacity);
green=red;
blue=red;
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&index,&opacity);
break;
}
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&index);
break;
}
default:
{
if (image->matte != MagickFalse)
{
(void) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&opacity);
break;
}
(void) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
index*=0.01*range;
opacity*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.index=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (index+0.5),
range);
pixel.opacity=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (opacity+
0.5),range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (PixelPacket *) NULL)
continue;
SetPixelRed(q,pixel.red);
SetPixelGreen(q,pixel.green);
SetPixelBlue(q,pixel.blue);
if (image->colorspace == CMYKColorspace)
{
indexes=GetAuthenticIndexQueue(image);
SetPixelIndex(indexes,pixel.index);
}
if (image->matte != MagickFalse)
SetPixelAlpha(q,pixel.opacity);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
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,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTXTImage() adds attributes for the TXT 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 RegisterTXTImage method is:
%
% size_t RegisterTXTImage(void)
%
*/
ModuleExport size_t RegisterTXTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("SPARSE-COLOR");
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Sparse Color");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TEXT");
entry->decoder=(DecodeImageHandler *) ReadTEXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Text");
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TXT");
entry->decoder=(DecodeImageHandler *) ReadTXTImage;
entry->encoder=(EncodeImageHandler *) WriteTXTImage;
entry->description=ConstantString("Text");
entry->magick=(IsImageFormatHandler *) IsTXT;
entry->module=ConstantString("TXT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTXTImage() removes format registrations made by the
% TXT module from the list of supported format.
%
% The format of the UnregisterTXTImage method is:
%
% UnregisterTXTImage(void)
%
*/
ModuleExport void UnregisterTXTImage(void)
{
(void) UnregisterMagickInfo("TEXT");
(void) UnregisterMagickInfo("TXT");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e T X T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTXTImage writes the pixel values as text numbers.
%
% The format of the WriteTXTImage method is:
%
% MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
colorspace[MaxTextExtent],
tuple[MaxTextExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
/*
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,WriteBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
ComplianceType
compliance;
const char
*value;
(void) CopyMagickString(colorspace,CommandOptionToMnemonic(
MagickColorspaceOptions,(ssize_t) image->colorspace),MaxTextExtent);
LocaleLower(colorspace);
image->depth=GetImageQuantumDepth(image,MagickTrue);
if (image->matte != MagickFalse)
(void) ConcatenateMagickString(colorspace,"a",MaxTextExtent);
compliance=NoCompliance;
value=GetImageOption(image_info,"txt:compliance");
if (value != (char *) NULL)
compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions,
MagickFalse,value);
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") != 0)
{
size_t
depth;
depth=compliance == SVGCompliance ? image->depth :
MAGICKCORE_QUANTUM_DEPTH;
(void) FormatLocaleString(buffer,MaxTextExtent,
"# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n",(double)
image->columns,(double) image->rows,(double) ((MagickOffsetType)
GetQuantumRange(depth)),colorspace);
(void) WriteBlobString(image,buffer);
}
GetMagickPixelPacket(image,&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);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if (pixel.colorspace == LabColorspace)
{
pixel.green-=(QuantumRange+1)/2.0;
pixel.blue-=(QuantumRange+1)/2.0;
}
if (LocaleCompare(image_info->magick,"SPARSE-COLOR") == 0)
{
/*
Sparse-color format.
*/
if (GetPixelOpacity(p) == (Quantum) OpaqueOpacity)
{
GetColorTuple(&pixel,MagickFalse,tuple);
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g,",
(double) x,(double) y);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
}
p++;
continue;
}
(void) FormatLocaleString(buffer,MaxTextExtent,"%.20g,%.20g: ",(double)
x,(double) y);
(void) WriteBlobString(image,buffer);
(void) CopyMagickString(tuple,"(",MaxTextExtent);
ConcatenateColorComponent(&pixel,RedChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,GreenChannel,compliance,tuple);
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,BlueChannel,compliance,tuple);
if (pixel.colorspace == CMYKColorspace)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,IndexChannel,compliance,tuple);
}
if (pixel.matte != MagickFalse)
{
(void) ConcatenateMagickString(tuple,",",MaxTextExtent);
ConcatenateColorComponent(&pixel,AlphaChannel,compliance,tuple);
}
(void) ConcatenateMagickString(tuple,")",MaxTextExtent);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image," ");
GetColorTuple(&pixel,MagickTrue,tuple);
(void) FormatLocaleString(buffer,MaxTextExtent,"%s",tuple);
(void) WriteBlobString(image,buffer);
(void) WriteBlobString(image," ");
(void) QueryMagickColorname(image,&pixel,SVGCompliance,tuple,
&image->exception);
(void) WriteBlobString(image,tuple);
(void) WriteBlobString(image,"\n");
p++;
}
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-835/c/bad_2782_0 |
crossvul-cpp_data_bad_2765_1 | /*
* Apple HTTP Live Streaming demuxer
* Copyright (c) 2010 Martin Storsjo
* Copyright (c) 2013 Anssi Hannula
*
* 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
* Apple HTTP Live Streaming demuxer
* http://tools.ietf.org/html/draft-pantos-http-live-streaming
*/
#include "libavutil/avstring.h"
#include "libavutil/avassert.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/time.h"
#include "avformat.h"
#include "internal.h"
#include "avio_internal.h"
#include "id3v2.h"
#define INITIAL_BUFFER_SIZE 32768
#define MAX_FIELD_LEN 64
#define MAX_CHARACTERISTICS_LEN 512
#define MPEG_TIME_BASE 90000
#define MPEG_TIME_BASE_Q (AVRational){1, MPEG_TIME_BASE}
/*
* An apple http stream consists of a playlist with media segment files,
* played sequentially. There may be several playlists with the same
* video content, in different bandwidth variants, that are played in
* parallel (preferably only one bandwidth variant at a time). In this case,
* the user supplied the url to a main playlist that only lists the variant
* playlists.
*
* If the main playlist doesn't point at any variants, we still create
* one anonymous toplevel variant for this, to maintain the structure.
*/
enum KeyType {
KEY_NONE,
KEY_AES_128,
KEY_SAMPLE_AES
};
struct segment {
int64_t duration;
int64_t url_offset;
int64_t size;
char *url;
char *key;
enum KeyType key_type;
uint8_t iv[16];
/* associated Media Initialization Section, treated as a segment */
struct segment *init_section;
};
struct rendition;
enum PlaylistType {
PLS_TYPE_UNSPECIFIED,
PLS_TYPE_EVENT,
PLS_TYPE_VOD
};
/*
* Each playlist has its own demuxer. If it currently is active,
* it has an open AVIOContext too, and potentially an AVPacket
* containing the next packet from this stream.
*/
struct playlist {
char url[MAX_URL_SIZE];
AVIOContext pb;
uint8_t* read_buffer;
AVIOContext *input;
AVFormatContext *parent;
int index;
AVFormatContext *ctx;
AVPacket pkt;
int has_noheader_flag;
/* main demuxer streams associated with this playlist
* indexed by the subdemuxer stream indexes */
AVStream **main_streams;
int n_main_streams;
int finished;
enum PlaylistType type;
int64_t target_duration;
int start_seq_no;
int n_segments;
struct segment **segments;
int needed, cur_needed;
int cur_seq_no;
int64_t cur_seg_offset;
int64_t last_load_time;
/* Currently active Media Initialization Section */
struct segment *cur_init_section;
uint8_t *init_sec_buf;
unsigned int init_sec_buf_size;
unsigned int init_sec_data_len;
unsigned int init_sec_buf_read_offset;
char key_url[MAX_URL_SIZE];
uint8_t key[16];
/* ID3 timestamp handling (elementary audio streams have ID3 timestamps
* (and possibly other ID3 tags) in the beginning of each segment) */
int is_id3_timestamped; /* -1: not yet known */
int64_t id3_mpegts_timestamp; /* in mpegts tb */
int64_t id3_offset; /* in stream original tb */
uint8_t* id3_buf; /* temp buffer for id3 parsing */
unsigned int id3_buf_size;
AVDictionary *id3_initial; /* data from first id3 tag */
int id3_found; /* ID3 tag found at some point */
int id3_changed; /* ID3 tag data has changed at some point */
ID3v2ExtraMeta *id3_deferred_extra; /* stored here until subdemuxer is opened */
int64_t seek_timestamp;
int seek_flags;
int seek_stream_index; /* into subdemuxer stream array */
/* Renditions associated with this playlist, if any.
* Alternative rendition playlists have a single rendition associated
* with them, and variant main Media Playlists may have
* multiple (playlist-less) renditions associated with them. */
int n_renditions;
struct rendition **renditions;
/* Media Initialization Sections (EXT-X-MAP) associated with this
* playlist, if any. */
int n_init_sections;
struct segment **init_sections;
};
/*
* Renditions are e.g. alternative subtitle or audio streams.
* The rendition may either be an external playlist or it may be
* contained in the main Media Playlist of the variant (in which case
* playlist is NULL).
*/
struct rendition {
enum AVMediaType type;
struct playlist *playlist;
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
int disposition;
};
struct variant {
int bandwidth;
/* every variant contains at least the main Media Playlist in index 0 */
int n_playlists;
struct playlist **playlists;
char audio_group[MAX_FIELD_LEN];
char video_group[MAX_FIELD_LEN];
char subtitles_group[MAX_FIELD_LEN];
};
typedef struct HLSContext {
AVClass *class;
AVFormatContext *ctx;
int n_variants;
struct variant **variants;
int n_playlists;
struct playlist **playlists;
int n_renditions;
struct rendition **renditions;
int cur_seq_no;
int live_start_index;
int first_packet;
int64_t first_timestamp;
int64_t cur_timestamp;
AVIOInterruptCB *interrupt_callback;
char *user_agent; ///< holds HTTP user agent set as an AVOption to the HTTP protocol context
char *cookies; ///< holds HTTP cookie values set in either the initial response or as an AVOption to the HTTP protocol context
char *headers; ///< holds HTTP headers set as an AVOption to the HTTP protocol context
char *http_proxy; ///< holds the address of the HTTP proxy server
AVDictionary *avio_opts;
int strict_std_compliance;
char *allowed_extensions;
} HLSContext;
static int read_chomp_line(AVIOContext *s, char *buf, int maxlen)
{
int len = ff_get_line(s, buf, maxlen);
while (len > 0 && av_isspace(buf[len - 1]))
buf[--len] = '\0';
return len;
}
static void free_segment_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_segments; i++) {
av_freep(&pls->segments[i]->key);
av_freep(&pls->segments[i]->url);
av_freep(&pls->segments[i]);
}
av_freep(&pls->segments);
pls->n_segments = 0;
}
static void free_init_section_list(struct playlist *pls)
{
int i;
for (i = 0; i < pls->n_init_sections; i++) {
av_freep(&pls->init_sections[i]->url);
av_freep(&pls->init_sections[i]);
}
av_freep(&pls->init_sections);
pls->n_init_sections = 0;
}
static void free_playlist_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
free_segment_list(pls);
free_init_section_list(pls);
av_freep(&pls->main_streams);
av_freep(&pls->renditions);
av_freep(&pls->id3_buf);
av_dict_free(&pls->id3_initial);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
av_freep(&pls->init_sec_buf);
av_packet_unref(&pls->pkt);
av_freep(&pls->pb.buffer);
if (pls->input)
ff_format_io_close(c->ctx, &pls->input);
if (pls->ctx) {
pls->ctx->pb = NULL;
avformat_close_input(&pls->ctx);
}
av_free(pls);
}
av_freep(&c->playlists);
av_freep(&c->cookies);
av_freep(&c->user_agent);
av_freep(&c->headers);
av_freep(&c->http_proxy);
c->n_playlists = 0;
}
static void free_variant_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
av_freep(&var->playlists);
av_free(var);
}
av_freep(&c->variants);
c->n_variants = 0;
}
static void free_rendition_list(HLSContext *c)
{
int i;
for (i = 0; i < c->n_renditions; i++)
av_freep(&c->renditions[i]);
av_freep(&c->renditions);
c->n_renditions = 0;
}
/*
* Used to reset a statically allocated AVPacket to a clean slate,
* containing no data.
*/
static void reset_packet(AVPacket *pkt)
{
av_init_packet(pkt);
pkt->data = NULL;
}
static struct playlist *new_playlist(HLSContext *c, const char *url,
const char *base)
{
struct playlist *pls = av_mallocz(sizeof(struct playlist));
if (!pls)
return NULL;
reset_packet(&pls->pkt);
ff_make_absolute_url(pls->url, sizeof(pls->url), base, url);
pls->seek_timestamp = AV_NOPTS_VALUE;
pls->is_id3_timestamped = -1;
pls->id3_mpegts_timestamp = AV_NOPTS_VALUE;
dynarray_add(&c->playlists, &c->n_playlists, pls);
return pls;
}
struct variant_info {
char bandwidth[20];
/* variant group ids: */
char audio[MAX_FIELD_LEN];
char video[MAX_FIELD_LEN];
char subtitles[MAX_FIELD_LEN];
};
static struct variant *new_variant(HLSContext *c, struct variant_info *info,
const char *url, const char *base)
{
struct variant *var;
struct playlist *pls;
pls = new_playlist(c, url, base);
if (!pls)
return NULL;
var = av_mallocz(sizeof(struct variant));
if (!var)
return NULL;
if (info) {
var->bandwidth = atoi(info->bandwidth);
strcpy(var->audio_group, info->audio);
strcpy(var->video_group, info->video);
strcpy(var->subtitles_group, info->subtitles);
}
dynarray_add(&c->variants, &c->n_variants, var);
dynarray_add(&var->playlists, &var->n_playlists, pls);
return var;
}
static void handle_variant_args(struct variant_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "BANDWIDTH=", key_len)) {
*dest = info->bandwidth;
*dest_len = sizeof(info->bandwidth);
} else if (!strncmp(key, "AUDIO=", key_len)) {
*dest = info->audio;
*dest_len = sizeof(info->audio);
} else if (!strncmp(key, "VIDEO=", key_len)) {
*dest = info->video;
*dest_len = sizeof(info->video);
} else if (!strncmp(key, "SUBTITLES=", key_len)) {
*dest = info->subtitles;
*dest_len = sizeof(info->subtitles);
}
}
struct key_info {
char uri[MAX_URL_SIZE];
char method[11];
char iv[35];
};
static void handle_key_args(struct key_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "METHOD=", key_len)) {
*dest = info->method;
*dest_len = sizeof(info->method);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "IV=", key_len)) {
*dest = info->iv;
*dest_len = sizeof(info->iv);
}
}
struct init_section_info {
char uri[MAX_URL_SIZE];
char byterange[32];
};
static struct segment *new_init_section(struct playlist *pls,
struct init_section_info *info,
const char *url_base)
{
struct segment *sec;
char *ptr;
char tmp_str[MAX_URL_SIZE];
if (!info->uri[0])
return NULL;
sec = av_mallocz(sizeof(*sec));
if (!sec)
return NULL;
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url_base, info->uri);
sec->url = av_strdup(tmp_str);
if (!sec->url) {
av_free(sec);
return NULL;
}
if (info->byterange[0]) {
sec->size = strtoll(info->byterange, NULL, 10);
ptr = strchr(info->byterange, '@');
if (ptr)
sec->url_offset = strtoll(ptr+1, NULL, 10);
} else {
/* the entire file is the init section */
sec->size = -1;
}
dynarray_add(&pls->init_sections, &pls->n_init_sections, sec);
return sec;
}
static void handle_init_section_args(struct init_section_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "BYTERANGE=", key_len)) {
*dest = info->byterange;
*dest_len = sizeof(info->byterange);
}
}
struct rendition_info {
char type[16];
char uri[MAX_URL_SIZE];
char group_id[MAX_FIELD_LEN];
char language[MAX_FIELD_LEN];
char assoc_language[MAX_FIELD_LEN];
char name[MAX_FIELD_LEN];
char defaultr[4];
char forced[4];
char characteristics[MAX_CHARACTERISTICS_LEN];
};
static struct rendition *new_rendition(HLSContext *c, struct rendition_info *info,
const char *url_base)
{
struct rendition *rend;
enum AVMediaType type = AVMEDIA_TYPE_UNKNOWN;
char *characteristic;
char *chr_ptr;
char *saveptr;
if (!strcmp(info->type, "AUDIO"))
type = AVMEDIA_TYPE_AUDIO;
else if (!strcmp(info->type, "VIDEO"))
type = AVMEDIA_TYPE_VIDEO;
else if (!strcmp(info->type, "SUBTITLES"))
type = AVMEDIA_TYPE_SUBTITLE;
else if (!strcmp(info->type, "CLOSED-CAPTIONS"))
/* CLOSED-CAPTIONS is ignored since we do not support CEA-608 CC in
* AVC SEI RBSP anyway */
return NULL;
if (type == AVMEDIA_TYPE_UNKNOWN)
return NULL;
/* URI is mandatory for subtitles as per spec */
if (type == AVMEDIA_TYPE_SUBTITLE && !info->uri[0])
return NULL;
/* TODO: handle subtitles (each segment has to parsed separately) */
if (c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL)
if (type == AVMEDIA_TYPE_SUBTITLE)
return NULL;
rend = av_mallocz(sizeof(struct rendition));
if (!rend)
return NULL;
dynarray_add(&c->renditions, &c->n_renditions, rend);
rend->type = type;
strcpy(rend->group_id, info->group_id);
strcpy(rend->language, info->language);
strcpy(rend->name, info->name);
/* add the playlist if this is an external rendition */
if (info->uri[0]) {
rend->playlist = new_playlist(c, info->uri, url_base);
if (rend->playlist)
dynarray_add(&rend->playlist->renditions,
&rend->playlist->n_renditions, rend);
}
if (info->assoc_language[0]) {
int langlen = strlen(rend->language);
if (langlen < sizeof(rend->language) - 3) {
rend->language[langlen] = ',';
strncpy(rend->language + langlen + 1, info->assoc_language,
sizeof(rend->language) - langlen - 2);
}
}
if (!strcmp(info->defaultr, "YES"))
rend->disposition |= AV_DISPOSITION_DEFAULT;
if (!strcmp(info->forced, "YES"))
rend->disposition |= AV_DISPOSITION_FORCED;
chr_ptr = info->characteristics;
while ((characteristic = av_strtok(chr_ptr, ",", &saveptr))) {
if (!strcmp(characteristic, "public.accessibility.describes-music-and-sound"))
rend->disposition |= AV_DISPOSITION_HEARING_IMPAIRED;
else if (!strcmp(characteristic, "public.accessibility.describes-video"))
rend->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED;
chr_ptr = NULL;
}
return rend;
}
static void handle_rendition_args(struct rendition_info *info, const char *key,
int key_len, char **dest, int *dest_len)
{
if (!strncmp(key, "TYPE=", key_len)) {
*dest = info->type;
*dest_len = sizeof(info->type);
} else if (!strncmp(key, "URI=", key_len)) {
*dest = info->uri;
*dest_len = sizeof(info->uri);
} else if (!strncmp(key, "GROUP-ID=", key_len)) {
*dest = info->group_id;
*dest_len = sizeof(info->group_id);
} else if (!strncmp(key, "LANGUAGE=", key_len)) {
*dest = info->language;
*dest_len = sizeof(info->language);
} else if (!strncmp(key, "ASSOC-LANGUAGE=", key_len)) {
*dest = info->assoc_language;
*dest_len = sizeof(info->assoc_language);
} else if (!strncmp(key, "NAME=", key_len)) {
*dest = info->name;
*dest_len = sizeof(info->name);
} else if (!strncmp(key, "DEFAULT=", key_len)) {
*dest = info->defaultr;
*dest_len = sizeof(info->defaultr);
} else if (!strncmp(key, "FORCED=", key_len)) {
*dest = info->forced;
*dest_len = sizeof(info->forced);
} else if (!strncmp(key, "CHARACTERISTICS=", key_len)) {
*dest = info->characteristics;
*dest_len = sizeof(info->characteristics);
}
/*
* ignored:
* - AUTOSELECT: client may autoselect based on e.g. system language
* - INSTREAM-ID: EIA-608 closed caption number ("CC1".."CC4")
*/
}
/* used by parse_playlist to allocate a new variant+playlist when the
* playlist is detected to be a Media Playlist (not Master Playlist)
* and we have no parent Master Playlist (parsing of which would have
* allocated the variant and playlist already)
* *pls == NULL => Master Playlist or parentless Media Playlist
* *pls != NULL => parented Media Playlist, playlist+variant allocated */
static int ensure_playlist(HLSContext *c, struct playlist **pls, const char *url)
{
if (*pls)
return 0;
if (!new_variant(c, NULL, url, NULL))
return AVERROR(ENOMEM);
*pls = c->playlists[c->n_playlists - 1];
return 0;
}
static void update_options(char **dest, const char *name, void *src)
{
av_freep(dest);
av_opt_get(src, name, AV_OPT_SEARCH_CHILDREN, (uint8_t**)dest);
if (*dest && !strlen(*dest))
av_freep(dest);
}
static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,
AVDictionary *opts, AVDictionary *opts2, int *is_http)
{
HLSContext *c = s->priv_data;
AVDictionary *tmp = NULL;
const char *proto_name = NULL;
int ret;
av_dict_copy(&tmp, opts, 0);
av_dict_copy(&tmp, opts2, 0);
if (av_strstart(url, "crypto", NULL)) {
if (url[6] == '+' || url[6] == ':')
proto_name = avio_find_protocol_name(url + 7);
}
if (!proto_name)
proto_name = avio_find_protocol_name(url);
if (!proto_name)
return AVERROR_INVALIDDATA;
// only http(s) & file are allowed
if (av_strstart(proto_name, "file", NULL)) {
if (strcmp(c->allowed_extensions, "ALL") && !av_match_ext(url, c->allowed_extensions)) {
av_log(s, AV_LOG_ERROR,
"Filename extension of \'%s\' is not a common multimedia extension, blocked for security reasons.\n"
"If you wish to override this adjust allowed_extensions, you can set it to \'ALL\' to allow all\n",
url);
return AVERROR_INVALIDDATA;
}
} else if (av_strstart(proto_name, "http", NULL)) {
;
} else
return AVERROR_INVALIDDATA;
if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')
;
else if (av_strstart(url, "crypto", NULL) && !strncmp(proto_name, url + 7, strlen(proto_name)) && url[7 + strlen(proto_name)] == ':')
;
else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))
return AVERROR_INVALIDDATA;
ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);
if (ret >= 0) {
// update cookies on http response with setcookies.
char *new_cookies = NULL;
if (!(s->flags & AVFMT_FLAG_CUSTOM_IO))
av_opt_get(*pb, "cookies", AV_OPT_SEARCH_CHILDREN, (uint8_t**)&new_cookies);
if (new_cookies) {
av_free(c->cookies);
c->cookies = new_cookies;
}
av_dict_set(&opts, "cookies", c->cookies, 0);
}
av_dict_free(&tmp);
if (is_http)
*is_http = av_strstart(proto_name, "http", NULL);
return ret;
}
static int parse_playlist(HLSContext *c, const char *url,
struct playlist *pls, AVIOContext *in)
{
int ret = 0, is_segment = 0, is_variant = 0;
int64_t duration = 0;
enum KeyType key_type = KEY_NONE;
uint8_t iv[16] = "";
int has_iv = 0;
char key[MAX_URL_SIZE] = "";
char line[MAX_URL_SIZE];
const char *ptr;
int close_in = 0;
int64_t seg_offset = 0;
int64_t seg_size = -1;
uint8_t *new_url = NULL;
struct variant_info variant_info;
char tmp_str[MAX_URL_SIZE];
struct segment *cur_init_section = NULL;
if (!in) {
#if 1
AVDictionary *opts = NULL;
close_in = 1;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&opts, "seekable", "0", 0);
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);
av_dict_free(&opts);
if (ret < 0)
return ret;
#else
ret = open_in(c, &in, url);
if (ret < 0)
return ret;
close_in = 1;
#endif
}
if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)
url = new_url;
read_chomp_line(in, line, sizeof(line));
if (strcmp(line, "#EXTM3U")) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
if (pls) {
free_segment_list(pls);
pls->finished = 0;
pls->type = PLS_TYPE_UNSPECIFIED;
}
while (!avio_feof(in)) {
read_chomp_line(in, line, sizeof(line));
if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {
is_variant = 1;
memset(&variant_info, 0, sizeof(variant_info));
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,
&variant_info);
} else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {
struct key_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,
&info);
key_type = KEY_NONE;
has_iv = 0;
if (!strcmp(info.method, "AES-128"))
key_type = KEY_AES_128;
if (!strcmp(info.method, "SAMPLE-AES"))
key_type = KEY_SAMPLE_AES;
if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {
ff_hex_to_data(iv, info.iv + 2);
has_iv = 1;
}
av_strlcpy(key, info.uri, sizeof(key));
} else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {
struct rendition_info info = {{0}};
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,
&info);
new_rendition(c, &info, url);
} else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
pls->start_seq_no = atoi(ptr);
} else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
if (!strcmp(ptr, "EVENT"))
pls->type = PLS_TYPE_EVENT;
else if (!strcmp(ptr, "VOD"))
pls->type = PLS_TYPE_VOD;
} else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {
struct init_section_info info = {{0}};
ret = ensure_playlist(c, &pls, url);
if (ret < 0)
goto fail;
ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,
&info);
cur_init_section = new_init_section(pls, &info, url);
} else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {
if (pls)
pls->finished = 1;
} else if (av_strstart(line, "#EXTINF:", &ptr)) {
is_segment = 1;
duration = atof(ptr) * AV_TIME_BASE;
} else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {
seg_size = strtoll(ptr, NULL, 10);
ptr = strchr(ptr, '@');
if (ptr)
seg_offset = strtoll(ptr+1, NULL, 10);
} else if (av_strstart(line, "#", NULL)) {
continue;
} else if (line[0]) {
if (is_variant) {
if (!new_variant(c, &variant_info, line, url)) {
ret = AVERROR(ENOMEM);
goto fail;
}
is_variant = 0;
}
if (is_segment) {
struct segment *seg;
if (!pls) {
if (!new_variant(c, 0, url, NULL)) {
ret = AVERROR(ENOMEM);
goto fail;
}
pls = c->playlists[c->n_playlists - 1];
}
seg = av_malloc(sizeof(struct segment));
if (!seg) {
ret = AVERROR(ENOMEM);
goto fail;
}
seg->duration = duration;
seg->key_type = key_type;
if (has_iv) {
memcpy(seg->iv, iv, sizeof(iv));
} else {
int seq = pls->start_seq_no + pls->n_segments;
memset(seg->iv, 0, sizeof(seg->iv));
AV_WB32(seg->iv + 12, seq);
}
if (key_type != KEY_NONE) {
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);
seg->key = av_strdup(tmp_str);
if (!seg->key) {
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
} else {
seg->key = NULL;
}
ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);
seg->url = av_strdup(tmp_str);
if (!seg->url) {
av_free(seg->key);
av_free(seg);
ret = AVERROR(ENOMEM);
goto fail;
}
dynarray_add(&pls->segments, &pls->n_segments, seg);
is_segment = 0;
seg->size = seg_size;
if (seg_size >= 0) {
seg->url_offset = seg_offset;
seg_offset += seg_size;
seg_size = -1;
} else {
seg->url_offset = 0;
seg_offset = 0;
}
seg->init_section = cur_init_section;
}
}
}
if (pls)
pls->last_load_time = av_gettime_relative();
fail:
av_free(new_url);
if (close_in)
ff_format_io_close(c->ctx, &in);
return ret;
}
static struct segment *current_segment(struct playlist *pls)
{
return pls->segments[pls->cur_seq_no - pls->start_seq_no];
}
enum ReadFromURLMode {
READ_NORMAL,
READ_COMPLETE,
};
static int read_from_url(struct playlist *pls, struct segment *seg,
uint8_t *buf, int buf_size,
enum ReadFromURLMode mode)
{
int ret;
/* limit read if the segment was only a part of a file */
if (seg->size >= 0)
buf_size = FFMIN(buf_size, seg->size - pls->cur_seg_offset);
if (mode == READ_COMPLETE) {
ret = avio_read(pls->input, buf, buf_size);
if (ret != buf_size)
av_log(NULL, AV_LOG_ERROR, "Could not read complete segment.\n");
} else
ret = avio_read(pls->input, buf, buf_size);
if (ret > 0)
pls->cur_seg_offset += ret;
return ret;
}
/* Parse the raw ID3 data and pass contents to caller */
static void parse_id3(AVFormatContext *s, AVIOContext *pb,
AVDictionary **metadata, int64_t *dts,
ID3v2ExtraMetaAPIC **apic, ID3v2ExtraMeta **extra_meta)
{
static const char id3_priv_owner_ts[] = "com.apple.streaming.transportStreamTimestamp";
ID3v2ExtraMeta *meta;
ff_id3v2_read_dict(pb, metadata, ID3v2_DEFAULT_MAGIC, extra_meta);
for (meta = *extra_meta; meta; meta = meta->next) {
if (!strcmp(meta->tag, "PRIV")) {
ID3v2ExtraMetaPRIV *priv = meta->data;
if (priv->datasize == 8 && !strcmp(priv->owner, id3_priv_owner_ts)) {
/* 33-bit MPEG timestamp */
int64_t ts = AV_RB64(priv->data);
av_log(s, AV_LOG_DEBUG, "HLS ID3 audio timestamp %"PRId64"\n", ts);
if ((ts & ~((1ULL << 33) - 1)) == 0)
*dts = ts;
else
av_log(s, AV_LOG_ERROR, "Invalid HLS ID3 audio timestamp %"PRId64"\n", ts);
}
} else if (!strcmp(meta->tag, "APIC") && apic)
*apic = meta->data;
}
}
/* Check if the ID3 metadata contents have changed */
static int id3_has_changed_values(struct playlist *pls, AVDictionary *metadata,
ID3v2ExtraMetaAPIC *apic)
{
AVDictionaryEntry *entry = NULL;
AVDictionaryEntry *oldentry;
/* check that no keys have changed values */
while ((entry = av_dict_get(metadata, "", entry, AV_DICT_IGNORE_SUFFIX))) {
oldentry = av_dict_get(pls->id3_initial, entry->key, NULL, AV_DICT_MATCH_CASE);
if (!oldentry || strcmp(oldentry->value, entry->value) != 0)
return 1;
}
/* check if apic appeared */
if (apic && (pls->ctx->nb_streams != 2 || !pls->ctx->streams[1]->attached_pic.data))
return 1;
if (apic) {
int size = pls->ctx->streams[1]->attached_pic.size;
if (size != apic->buf->size - AV_INPUT_BUFFER_PADDING_SIZE)
return 1;
if (memcmp(apic->buf->data, pls->ctx->streams[1]->attached_pic.data, size) != 0)
return 1;
}
return 0;
}
/* Parse ID3 data and handle the found data */
static void handle_id3(AVIOContext *pb, struct playlist *pls)
{
AVDictionary *metadata = NULL;
ID3v2ExtraMetaAPIC *apic = NULL;
ID3v2ExtraMeta *extra_meta = NULL;
int64_t timestamp = AV_NOPTS_VALUE;
parse_id3(pls->ctx, pb, &metadata, ×tamp, &apic, &extra_meta);
if (timestamp != AV_NOPTS_VALUE) {
pls->id3_mpegts_timestamp = timestamp;
pls->id3_offset = 0;
}
if (!pls->id3_found) {
/* initial ID3 tags */
av_assert0(!pls->id3_deferred_extra);
pls->id3_found = 1;
/* get picture attachment and set text metadata */
if (pls->ctx->nb_streams)
ff_id3v2_parse_apic(pls->ctx, &extra_meta);
else
/* demuxer not yet opened, defer picture attachment */
pls->id3_deferred_extra = extra_meta;
av_dict_copy(&pls->ctx->metadata, metadata, 0);
pls->id3_initial = metadata;
} else {
if (!pls->id3_changed && id3_has_changed_values(pls, metadata, apic)) {
avpriv_report_missing_feature(pls->ctx, "Changing ID3 metadata in HLS audio elementary stream");
pls->id3_changed = 1;
}
av_dict_free(&metadata);
}
if (!pls->id3_deferred_extra)
ff_id3v2_free_extra_meta(&extra_meta);
}
static void intercept_id3(struct playlist *pls, uint8_t *buf,
int buf_size, int *len)
{
/* intercept id3 tags, we do not want to pass them to the raw
* demuxer on all segment switches */
int bytes;
int id3_buf_pos = 0;
int fill_buf = 0;
struct segment *seg = current_segment(pls);
/* gather all the id3 tags */
while (1) {
/* see if we can retrieve enough data for ID3 header */
if (*len < ID3v2_HEADER_SIZE && buf_size >= ID3v2_HEADER_SIZE) {
bytes = read_from_url(pls, seg, buf + *len, ID3v2_HEADER_SIZE - *len, READ_COMPLETE);
if (bytes > 0) {
if (bytes == ID3v2_HEADER_SIZE - *len)
/* no EOF yet, so fill the caller buffer again after
* we have stripped the ID3 tags */
fill_buf = 1;
*len += bytes;
} else if (*len <= 0) {
/* error/EOF */
*len = bytes;
fill_buf = 0;
}
}
if (*len < ID3v2_HEADER_SIZE)
break;
if (ff_id3v2_match(buf, ID3v2_DEFAULT_MAGIC)) {
int64_t maxsize = seg->size >= 0 ? seg->size : 1024*1024;
int taglen = ff_id3v2_tag_len(buf);
int tag_got_bytes = FFMIN(taglen, *len);
int remaining = taglen - tag_got_bytes;
if (taglen > maxsize) {
av_log(pls->ctx, AV_LOG_ERROR, "Too large HLS ID3 tag (%d > %"PRId64" bytes)\n",
taglen, maxsize);
break;
}
/*
* Copy the id3 tag to our temporary id3 buffer.
* We could read a small id3 tag directly without memcpy, but
* we would still need to copy the large tags, and handling
* both of those cases together with the possibility for multiple
* tags would make the handling a bit complex.
*/
pls->id3_buf = av_fast_realloc(pls->id3_buf, &pls->id3_buf_size, id3_buf_pos + taglen);
if (!pls->id3_buf)
break;
memcpy(pls->id3_buf + id3_buf_pos, buf, tag_got_bytes);
id3_buf_pos += tag_got_bytes;
/* strip the intercepted bytes */
*len -= tag_got_bytes;
memmove(buf, buf + tag_got_bytes, *len);
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped %d HLS ID3 bytes\n", tag_got_bytes);
if (remaining > 0) {
/* read the rest of the tag in */
if (read_from_url(pls, seg, pls->id3_buf + id3_buf_pos, remaining, READ_COMPLETE) != remaining)
break;
id3_buf_pos += remaining;
av_log(pls->ctx, AV_LOG_DEBUG, "Stripped additional %d HLS ID3 bytes\n", remaining);
}
} else {
/* no more ID3 tags */
break;
}
}
/* re-fill buffer for the caller unless EOF */
if (*len >= 0 && (fill_buf || *len == 0)) {
bytes = read_from_url(pls, seg, buf + *len, buf_size - *len, READ_NORMAL);
/* ignore error if we already had some data */
if (bytes >= 0)
*len += bytes;
else if (*len == 0)
*len = bytes;
}
if (pls->id3_buf) {
/* Now parse all the ID3 tags */
AVIOContext id3ioctx;
ffio_init_context(&id3ioctx, pls->id3_buf, id3_buf_pos, 0, NULL, NULL, NULL, NULL);
handle_id3(&id3ioctx, pls);
}
if (pls->is_id3_timestamped == -1)
pls->is_id3_timestamped = (pls->id3_mpegts_timestamp != AV_NOPTS_VALUE);
}
static int open_input(HLSContext *c, struct playlist *pls, struct segment *seg)
{
AVDictionary *opts = NULL;
int ret;
int is_http = 0;
// broker prior HTTP options that should be consistent across requests
av_dict_set(&opts, "user_agent", c->user_agent, 0);
av_dict_set(&opts, "cookies", c->cookies, 0);
av_dict_set(&opts, "headers", c->headers, 0);
av_dict_set(&opts, "http_proxy", c->http_proxy, 0);
av_dict_set(&opts, "seekable", "0", 0);
if (seg->size >= 0) {
/* try to restrict the HTTP request to the part we want
* (if this is in fact a HTTP request) */
av_dict_set_int(&opts, "offset", seg->url_offset, 0);
av_dict_set_int(&opts, "end_offset", seg->url_offset + seg->size, 0);
}
av_log(pls->parent, AV_LOG_VERBOSE, "HLS request for url '%s', offset %"PRId64", playlist %d\n",
seg->url, seg->url_offset, pls->index);
if (seg->key_type == KEY_NONE) {
ret = open_url(pls->parent, &pls->input, seg->url, c->avio_opts, opts, &is_http);
} else if (seg->key_type == KEY_AES_128) {
AVDictionary *opts2 = NULL;
char iv[33], key[33], url[MAX_URL_SIZE];
if (strcmp(seg->key, pls->key_url)) {
AVIOContext *pb;
if (open_url(pls->parent, &pb, seg->key, c->avio_opts, opts, NULL) == 0) {
ret = avio_read(pb, pls->key, sizeof(pls->key));
if (ret != sizeof(pls->key)) {
av_log(NULL, AV_LOG_ERROR, "Unable to read key file %s\n",
seg->key);
}
ff_format_io_close(pls->parent, &pb);
} else {
av_log(NULL, AV_LOG_ERROR, "Unable to open key file %s\n",
seg->key);
}
av_strlcpy(pls->key_url, seg->key, sizeof(pls->key_url));
}
ff_data_to_hex(iv, seg->iv, sizeof(seg->iv), 0);
ff_data_to_hex(key, pls->key, sizeof(pls->key), 0);
iv[32] = key[32] = '\0';
if (strstr(seg->url, "://"))
snprintf(url, sizeof(url), "crypto+%s", seg->url);
else
snprintf(url, sizeof(url), "crypto:%s", seg->url);
av_dict_copy(&opts2, c->avio_opts, 0);
av_dict_set(&opts2, "key", key, 0);
av_dict_set(&opts2, "iv", iv, 0);
ret = open_url(pls->parent, &pls->input, url, opts2, opts, &is_http);
av_dict_free(&opts2);
if (ret < 0) {
goto cleanup;
}
ret = 0;
} else if (seg->key_type == KEY_SAMPLE_AES) {
av_log(pls->parent, AV_LOG_ERROR,
"SAMPLE-AES encryption is not supported yet\n");
ret = AVERROR_PATCHWELCOME;
}
else
ret = AVERROR(ENOSYS);
/* Seek to the requested position. If this was a HTTP request, the offset
* should already be where want it to, but this allows e.g. local testing
* without a HTTP server.
*
* This is not done for HTTP at all as avio_seek() does internal bookkeeping
* of file offset which is out-of-sync with the actual offset when "offset"
* AVOption is used with http protocol, causing the seek to not be a no-op
* as would be expected. Wrong offset received from the server will not be
* noticed without the call, though.
*/
if (ret == 0 && !is_http && seg->key_type == KEY_NONE && seg->url_offset) {
int64_t seekret = avio_seek(pls->input, seg->url_offset, SEEK_SET);
if (seekret < 0) {
av_log(pls->parent, AV_LOG_ERROR, "Unable to seek to offset %"PRId64" of HLS segment '%s'\n", seg->url_offset, seg->url);
ret = seekret;
ff_format_io_close(pls->parent, &pls->input);
}
}
cleanup:
av_dict_free(&opts);
pls->cur_seg_offset = 0;
return ret;
}
static int update_init_section(struct playlist *pls, struct segment *seg)
{
static const int max_init_section_size = 1024*1024;
HLSContext *c = pls->parent->priv_data;
int64_t sec_size;
int64_t urlsize;
int ret;
if (seg->init_section == pls->cur_init_section)
return 0;
pls->cur_init_section = NULL;
if (!seg->init_section)
return 0;
ret = open_input(c, pls, seg->init_section);
if (ret < 0) {
av_log(pls->parent, AV_LOG_WARNING,
"Failed to open an initialization section in playlist %d\n",
pls->index);
return ret;
}
if (seg->init_section->size >= 0)
sec_size = seg->init_section->size;
else if ((urlsize = avio_size(pls->input)) >= 0)
sec_size = urlsize;
else
sec_size = max_init_section_size;
av_log(pls->parent, AV_LOG_DEBUG,
"Downloading an initialization section of size %"PRId64"\n",
sec_size);
sec_size = FFMIN(sec_size, max_init_section_size);
av_fast_malloc(&pls->init_sec_buf, &pls->init_sec_buf_size, sec_size);
ret = read_from_url(pls, seg->init_section, pls->init_sec_buf,
pls->init_sec_buf_size, READ_COMPLETE);
ff_format_io_close(pls->parent, &pls->input);
if (ret < 0)
return ret;
pls->cur_init_section = seg->init_section;
pls->init_sec_data_len = ret;
pls->init_sec_buf_read_offset = 0;
/* spec says audio elementary streams do not have media initialization
* sections, so there should be no ID3 timestamps */
pls->is_id3_timestamped = 0;
return 0;
}
static int64_t default_reload_interval(struct playlist *pls)
{
return pls->n_segments > 0 ?
pls->segments[pls->n_segments - 1]->duration :
pls->target_duration;
}
static int read_data(void *opaque, uint8_t *buf, int buf_size)
{
struct playlist *v = opaque;
HLSContext *c = v->parent->priv_data;
int ret, i;
int just_opened = 0;
restart:
if (!v->needed)
return AVERROR_EOF;
if (!v->input) {
int64_t reload_interval;
struct segment *seg;
/* Check that the playlist is still needed before opening a new
* segment. */
if (v->ctx && v->ctx->nb_streams) {
v->needed = 0;
for (i = 0; i < v->n_main_streams; i++) {
if (v->main_streams[i]->discard < AVDISCARD_ALL) {
v->needed = 1;
break;
}
}
}
if (!v->needed) {
av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",
v->index);
return AVERROR_EOF;
}
/* If this is a live stream and the reload interval has elapsed since
* the last playlist reload, reload the playlists now. */
reload_interval = default_reload_interval(v);
reload:
if (!v->finished &&
av_gettime_relative() - v->last_load_time >= reload_interval) {
if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {
av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",
v->index);
return ret;
}
/* If we need to reload the playlist again below (if
* there's still no more segments), switch to a reload
* interval of half the target duration. */
reload_interval = v->target_duration / 2;
}
if (v->cur_seq_no < v->start_seq_no) {
av_log(NULL, AV_LOG_WARNING,
"skipping %d segments ahead, expired from playlists\n",
v->start_seq_no - v->cur_seq_no);
v->cur_seq_no = v->start_seq_no;
}
if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {
if (v->finished)
return AVERROR_EOF;
while (av_gettime_relative() - v->last_load_time < reload_interval) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_usleep(100*1000);
}
/* Enough time has elapsed since the last reload */
goto reload;
}
seg = current_segment(v);
/* load/update Media Initialization Section, if any */
ret = update_init_section(v, seg);
if (ret)
return ret;
ret = open_input(c, v, seg);
if (ret < 0) {
if (ff_check_interrupt(c->interrupt_callback))
return AVERROR_EXIT;
av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",
v->index);
v->cur_seq_no += 1;
goto reload;
}
just_opened = 1;
}
if (v->init_sec_buf_read_offset < v->init_sec_data_len) {
/* Push init section out first before first actual segment */
int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);
memcpy(buf, v->init_sec_buf, copy_size);
v->init_sec_buf_read_offset += copy_size;
return copy_size;
}
ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);
if (ret > 0) {
if (just_opened && v->is_id3_timestamped != 0) {
/* Intercept ID3 tags here, elementary audio streams are required
* to convey timestamps using them in the beginning of each segment. */
intercept_id3(v, buf, buf_size, &ret);
}
return ret;
}
ff_format_io_close(v->parent, &v->input);
v->cur_seq_no++;
c->cur_seq_no = v->cur_seq_no;
goto restart;
}
static void add_renditions_to_variant(HLSContext *c, struct variant *var,
enum AVMediaType type, const char *group_id)
{
int i;
for (i = 0; i < c->n_renditions; i++) {
struct rendition *rend = c->renditions[i];
if (rend->type == type && !strcmp(rend->group_id, group_id)) {
if (rend->playlist)
/* rendition is an external playlist
* => add the playlist to the variant */
dynarray_add(&var->playlists, &var->n_playlists, rend->playlist);
else
/* rendition is part of the variant main Media Playlist
* => add the rendition to the main Media Playlist */
dynarray_add(&var->playlists[0]->renditions,
&var->playlists[0]->n_renditions,
rend);
}
}
}
static void add_metadata_from_renditions(AVFormatContext *s, struct playlist *pls,
enum AVMediaType type)
{
int rend_idx = 0;
int i;
for (i = 0; i < pls->n_main_streams; i++) {
AVStream *st = pls->main_streams[i];
if (st->codecpar->codec_type != type)
continue;
for (; rend_idx < pls->n_renditions; rend_idx++) {
struct rendition *rend = pls->renditions[rend_idx];
if (rend->type != type)
continue;
if (rend->language[0])
av_dict_set(&st->metadata, "language", rend->language, 0);
if (rend->name[0])
av_dict_set(&st->metadata, "comment", rend->name, 0);
st->disposition |= rend->disposition;
}
if (rend_idx >=pls->n_renditions)
break;
}
}
/* if timestamp was in valid range: returns 1 and sets seq_no
* if not: returns 0 and sets seq_no to closest segment */
static int find_timestamp_in_playlist(HLSContext *c, struct playlist *pls,
int64_t timestamp, int *seq_no)
{
int i;
int64_t pos = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
if (timestamp < pos) {
*seq_no = pls->start_seq_no;
return 0;
}
for (i = 0; i < pls->n_segments; i++) {
int64_t diff = pos + pls->segments[i]->duration - timestamp;
if (diff > 0) {
*seq_no = pls->start_seq_no + i;
return 1;
}
pos += pls->segments[i]->duration;
}
*seq_no = pls->start_seq_no + pls->n_segments - 1;
return 0;
}
static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
{
int seq_no;
if (!pls->finished && !c->first_packet &&
av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
/* reload the playlist since it was suspended */
parse_playlist(c, pls->url, pls, NULL);
/* If playback is already in progress (we are just selecting a new
* playlist) and this is a complete file, find the matching segment
* by counting durations. */
if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
return seq_no;
}
if (!pls->finished) {
if (!c->first_packet && /* we are doing a segment selection during playback */
c->cur_seq_no >= pls->start_seq_no &&
c->cur_seq_no < pls->start_seq_no + pls->n_segments)
/* While spec 3.4.3 says that we cannot assume anything about the
* content at the same sequence number on different playlists,
* in practice this seems to work and doing it otherwise would
* require us to download a segment to inspect its timestamps. */
return c->cur_seq_no;
/* If this is a live stream, start live_start_index segments from the
* start or end */
if (c->live_start_index < 0)
return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
else
return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
}
/* Otherwise just start on the first segment. */
return pls->start_seq_no;
}
static int save_avio_options(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
static const char *opts[] = {
"headers", "http_proxy", "user_agent", "user-agent", "cookies", NULL };
const char **opt = opts;
uint8_t *buf;
int ret = 0;
while (*opt) {
if (av_opt_get(s->pb, *opt, AV_OPT_SEARCH_CHILDREN | AV_OPT_ALLOW_NULL, &buf) >= 0) {
ret = av_dict_set(&c->avio_opts, *opt, buf,
AV_DICT_DONT_STRDUP_VAL);
if (ret < 0)
return ret;
}
opt++;
}
return ret;
}
static int nested_io_open(AVFormatContext *s, AVIOContext **pb, const char *url,
int flags, AVDictionary **opts)
{
av_log(s, AV_LOG_ERROR,
"A HLS playlist item '%s' referred to an external file '%s'. "
"Opening this file was forbidden for security reasons\n",
s->filename, url);
return AVERROR(EPERM);
}
static void add_stream_to_programs(AVFormatContext *s, struct playlist *pls, AVStream *stream)
{
HLSContext *c = s->priv_data;
int i, j;
int bandwidth = -1;
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
for (j = 0; j < v->n_playlists; j++) {
if (v->playlists[j] != pls)
continue;
av_program_add_stream_index(s, i, stream->index);
if (bandwidth < 0)
bandwidth = v->bandwidth;
else if (bandwidth != v->bandwidth)
bandwidth = -1; /* stream in multiple variants with different bandwidths */
}
}
if (bandwidth >= 0)
av_dict_set_int(&stream->metadata, "variant_bitrate", bandwidth, 0);
}
static int set_stream_info_from_input_stream(AVStream *st, struct playlist *pls, AVStream *ist)
{
int err;
err = avcodec_parameters_copy(st->codecpar, ist->codecpar);
if (err < 0)
return err;
if (pls->is_id3_timestamped) /* custom timestamps via id3 */
avpriv_set_pts_info(st, 33, 1, MPEG_TIME_BASE);
else
avpriv_set_pts_info(st, ist->pts_wrap_bits, ist->time_base.num, ist->time_base.den);
st->internal->need_context_update = 1;
return 0;
}
/* add new subdemuxer streams to our context, if any */
static int update_streams_from_subdemuxer(AVFormatContext *s, struct playlist *pls)
{
int err;
while (pls->n_main_streams < pls->ctx->nb_streams) {
int ist_idx = pls->n_main_streams;
AVStream *st = avformat_new_stream(s, NULL);
AVStream *ist = pls->ctx->streams[ist_idx];
if (!st)
return AVERROR(ENOMEM);
st->id = pls->index;
dynarray_add(&pls->main_streams, &pls->n_main_streams, st);
add_stream_to_programs(s, pls, st);
err = set_stream_info_from_input_stream(st, pls, ist);
if (err < 0)
return err;
}
return 0;
}
static void update_noheader_flag(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
int flag_needed = 0;
int i;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->has_noheader_flag) {
flag_needed = 1;
break;
}
}
if (flag_needed)
s->ctx_flags |= AVFMTCTX_NOHEADER;
else
s->ctx_flags &= ~AVFMTCTX_NOHEADER;
}
static int hls_close(AVFormatContext *s)
{
HLSContext *c = s->priv_data;
free_playlist_list(c);
free_variant_list(c);
free_rendition_list(c);
av_dict_free(&c->avio_opts);
return 0;
}
static int hls_read_header(AVFormatContext *s)
{
void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;
HLSContext *c = s->priv_data;
int ret = 0, i;
int highest_cur_seq_no = 0;
c->ctx = s;
c->interrupt_callback = &s->interrupt_callback;
c->strict_std_compliance = s->strict_std_compliance;
c->first_packet = 1;
c->first_timestamp = AV_NOPTS_VALUE;
c->cur_timestamp = AV_NOPTS_VALUE;
if (u) {
// get the previous user agent & set back to null if string size is zero
update_options(&c->user_agent, "user_agent", u);
// get the previous cookies & set back to null if string size is zero
update_options(&c->cookies, "cookies", u);
// get the previous headers & set back to null if string size is zero
update_options(&c->headers, "headers", u);
// get the previous http proxt & set back to null if string size is zero
update_options(&c->http_proxy, "http_proxy", u);
}
if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)
goto fail;
if ((ret = save_avio_options(s)) < 0)
goto fail;
/* Some HLS servers don't like being sent the range header */
av_dict_set(&c->avio_opts, "seekable", "0", 0);
if (c->n_variants == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If the playlist only contained playlists (Master Playlist),
* parse each individual playlist. */
if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)
goto fail;
}
}
if (c->variants[0]->playlists[0]->n_segments == 0) {
av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");
ret = AVERROR_EOF;
goto fail;
}
/* If this isn't a live stream, calculate the total duration of the
* stream. */
if (c->variants[0]->playlists[0]->finished) {
int64_t duration = 0;
for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)
duration += c->variants[0]->playlists[0]->segments[i]->duration;
s->duration = duration;
}
/* Associate renditions with variants */
for (i = 0; i < c->n_variants; i++) {
struct variant *var = c->variants[i];
if (var->audio_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);
if (var->video_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);
if (var->subtitles_group[0])
add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);
}
/* Create a program for each variant */
for (i = 0; i < c->n_variants; i++) {
struct variant *v = c->variants[i];
AVProgram *program;
program = av_new_program(s, i);
if (!program)
goto fail;
av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);
}
/* Select the starting segments */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->n_segments == 0)
continue;
pls->cur_seq_no = select_cur_seq_no(c, pls);
highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);
}
/* Open the demuxer for each playlist */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
AVInputFormat *in_fmt = NULL;
if (!(pls->ctx = avformat_alloc_context())) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (pls->n_segments == 0)
continue;
pls->index = i;
pls->needed = 1;
pls->parent = s;
/*
* If this is a live stream and this playlist looks like it is one segment
* behind, try to sync it up so that every substream starts at the same
* time position (so e.g. avformat_find_stream_info() will see packets from
* all active streams within the first few seconds). This is not very generic,
* though, as the sequence numbers are technically independent.
*/
if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&
highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {
pls->cur_seq_no = highest_cur_seq_no;
}
pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);
if (!pls->read_buffer){
ret = AVERROR(ENOMEM);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,
read_data, NULL, NULL);
pls->pb.seekable = 0;
ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,
NULL, 0, 0);
if (ret < 0) {
/* Free the ctx - it isn't initialized properly at this point,
* so avformat_close_input shouldn't be called. If
* avformat_open_input fails below, it frees and zeros the
* context, so it doesn't need any special treatment like this. */
av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);
avformat_free_context(pls->ctx);
pls->ctx = NULL;
goto fail;
}
pls->ctx->pb = &pls->pb;
pls->ctx->io_open = nested_io_open;
pls->ctx->flags |= s->flags & ~AVFMT_FLAG_CUSTOM_IO;
if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)
goto fail;
ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);
if (ret < 0)
goto fail;
if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {
ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);
avformat_queue_attached_pictures(pls->ctx);
ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);
pls->id3_deferred_extra = NULL;
}
if (pls->is_id3_timestamped == -1)
av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");
/*
* For ID3 timestamped raw audio streams we need to detect the packet
* durations to calculate timestamps in fill_timing_for_id3_timestamped_stream(),
* but for other streams we can rely on our user calling avformat_find_stream_info()
* on us if they want to.
*/
if (pls->is_id3_timestamped) {
ret = avformat_find_stream_info(pls->ctx, NULL);
if (ret < 0)
goto fail;
}
pls->has_noheader_flag = !!(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER);
/* Create new AVStreams for each stream in this playlist */
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0)
goto fail;
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);
add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);
}
update_noheader_flag(s);
return 0;
fail:
hls_close(s);
return ret;
}
static int recheck_discard_flags(AVFormatContext *s, int first)
{
HLSContext *c = s->priv_data;
int i, changed = 0;
/* Check if any new streams are needed */
for (i = 0; i < c->n_playlists; i++)
c->playlists[i]->cur_needed = 0;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
struct playlist *pls = c->playlists[s->streams[i]->id];
if (st->discard < AVDISCARD_ALL)
pls->cur_needed = 1;
}
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
if (pls->cur_needed && !pls->needed) {
pls->needed = 1;
changed = 1;
pls->cur_seq_no = select_cur_seq_no(c, pls);
pls->pb.eof_reached = 0;
if (c->cur_timestamp != AV_NOPTS_VALUE) {
/* catch up */
pls->seek_timestamp = c->cur_timestamp;
pls->seek_flags = AVSEEK_FLAG_ANY;
pls->seek_stream_index = -1;
}
av_log(s, AV_LOG_INFO, "Now receiving playlist %d, segment %d\n", i, pls->cur_seq_no);
} else if (first && !pls->cur_needed && pls->needed) {
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
pls->needed = 0;
changed = 1;
av_log(s, AV_LOG_INFO, "No longer receiving playlist %d\n", i);
}
}
return changed;
}
static void fill_timing_for_id3_timestamped_stream(struct playlist *pls)
{
if (pls->id3_offset >= 0) {
pls->pkt.dts = pls->id3_mpegts_timestamp +
av_rescale_q(pls->id3_offset,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
if (pls->pkt.duration)
pls->id3_offset += pls->pkt.duration;
else
pls->id3_offset = -1;
} else {
/* there have been packets with unknown duration
* since the last id3 tag, should not normally happen */
pls->pkt.dts = AV_NOPTS_VALUE;
}
if (pls->pkt.duration)
pls->pkt.duration = av_rescale_q(pls->pkt.duration,
pls->ctx->streams[pls->pkt.stream_index]->time_base,
MPEG_TIME_BASE_Q);
pls->pkt.pts = AV_NOPTS_VALUE;
}
static AVRational get_timebase(struct playlist *pls)
{
if (pls->is_id3_timestamped)
return MPEG_TIME_BASE_Q;
return pls->ctx->streams[pls->pkt.stream_index]->time_base;
}
static int compare_ts_with_wrapdetect(int64_t ts_a, struct playlist *pls_a,
int64_t ts_b, struct playlist *pls_b)
{
int64_t scaled_ts_a = av_rescale_q(ts_a, get_timebase(pls_a), MPEG_TIME_BASE_Q);
int64_t scaled_ts_b = av_rescale_q(ts_b, get_timebase(pls_b), MPEG_TIME_BASE_Q);
return av_compare_mod(scaled_ts_a, scaled_ts_b, 1LL << 33);
}
static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)
{
HLSContext *c = s->priv_data;
int ret, i, minplaylist = -1;
recheck_discard_flags(s, c->first_packet);
c->first_packet = 0;
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
/* Make sure we've got one buffered packet from each open playlist
* stream */
if (pls->needed && !pls->pkt.data) {
while (1) {
int64_t ts_diff;
AVRational tb;
ret = av_read_frame(pls->ctx, &pls->pkt);
if (ret < 0) {
if (!avio_feof(&pls->pb) && ret != AVERROR_EOF)
return ret;
reset_packet(&pls->pkt);
break;
} else {
/* stream_index check prevents matching picture attachments etc. */
if (pls->is_id3_timestamped && pls->pkt.stream_index == 0) {
/* audio elementary streams are id3 timestamped */
fill_timing_for_id3_timestamped_stream(pls);
}
if (c->first_timestamp == AV_NOPTS_VALUE &&
pls->pkt.dts != AV_NOPTS_VALUE)
c->first_timestamp = av_rescale_q(pls->pkt.dts,
get_timebase(pls), AV_TIME_BASE_Q);
}
if (pls->seek_timestamp == AV_NOPTS_VALUE)
break;
if (pls->seek_stream_index < 0 ||
pls->seek_stream_index == pls->pkt.stream_index) {
if (pls->pkt.dts == AV_NOPTS_VALUE) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
tb = get_timebase(pls);
ts_diff = av_rescale_rnd(pls->pkt.dts, AV_TIME_BASE,
tb.den, AV_ROUND_DOWN) -
pls->seek_timestamp;
if (ts_diff >= 0 && (pls->seek_flags & AVSEEK_FLAG_ANY ||
pls->pkt.flags & AV_PKT_FLAG_KEY)) {
pls->seek_timestamp = AV_NOPTS_VALUE;
break;
}
}
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
}
}
/* Check if this stream has the packet with the lowest dts */
if (pls->pkt.data) {
struct playlist *minpls = minplaylist < 0 ?
NULL : c->playlists[minplaylist];
if (minplaylist < 0) {
minplaylist = i;
} else {
int64_t dts = pls->pkt.dts;
int64_t mindts = minpls->pkt.dts;
if (dts == AV_NOPTS_VALUE ||
(mindts != AV_NOPTS_VALUE && compare_ts_with_wrapdetect(dts, pls, mindts, minpls) < 0))
minplaylist = i;
}
}
}
/* If we got a packet, return it */
if (minplaylist >= 0) {
struct playlist *pls = c->playlists[minplaylist];
AVStream *ist;
AVStream *st;
ret = update_streams_from_subdemuxer(s, pls);
if (ret < 0) {
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return ret;
}
/* check if noheader flag has been cleared by the subdemuxer */
if (pls->has_noheader_flag && !(pls->ctx->ctx_flags & AVFMTCTX_NOHEADER)) {
pls->has_noheader_flag = 0;
update_noheader_flag(s);
}
if (pls->pkt.stream_index >= pls->n_main_streams) {
av_log(s, AV_LOG_ERROR, "stream index inconsistency: index %d, %d main streams, %d subdemuxer streams\n",
pls->pkt.stream_index, pls->n_main_streams, pls->ctx->nb_streams);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
return AVERROR_BUG;
}
ist = pls->ctx->streams[pls->pkt.stream_index];
st = pls->main_streams[pls->pkt.stream_index];
*pkt = pls->pkt;
pkt->stream_index = st->index;
reset_packet(&c->playlists[minplaylist]->pkt);
if (pkt->dts != AV_NOPTS_VALUE)
c->cur_timestamp = av_rescale_q(pkt->dts,
ist->time_base,
AV_TIME_BASE_Q);
/* There may be more situations where this would be useful, but this at least
* handles newly probed codecs properly (i.e. request_probe by mpegts). */
if (ist->codecpar->codec_id != st->codecpar->codec_id) {
ret = set_stream_info_from_input_stream(st, pls, ist);
if (ret < 0) {
av_packet_unref(pkt);
return ret;
}
}
return 0;
}
return AVERROR_EOF;
}
static int hls_read_seek(AVFormatContext *s, int stream_index,
int64_t timestamp, int flags)
{
HLSContext *c = s->priv_data;
struct playlist *seek_pls = NULL;
int i, seq_no;
int j;
int stream_subdemuxer_index;
int64_t first_timestamp, seek_timestamp, duration;
if ((flags & AVSEEK_FLAG_BYTE) ||
!(c->variants[0]->playlists[0]->finished || c->variants[0]->playlists[0]->type == PLS_TYPE_EVENT))
return AVERROR(ENOSYS);
first_timestamp = c->first_timestamp == AV_NOPTS_VALUE ?
0 : c->first_timestamp;
seek_timestamp = av_rescale_rnd(timestamp, AV_TIME_BASE,
s->streams[stream_index]->time_base.den,
flags & AVSEEK_FLAG_BACKWARD ?
AV_ROUND_DOWN : AV_ROUND_UP);
duration = s->duration == AV_NOPTS_VALUE ?
0 : s->duration;
if (0 < duration && duration < seek_timestamp - first_timestamp)
return AVERROR(EIO);
/* find the playlist with the specified stream */
for (i = 0; i < c->n_playlists; i++) {
struct playlist *pls = c->playlists[i];
for (j = 0; j < pls->n_main_streams; j++) {
if (pls->main_streams[j] == s->streams[stream_index]) {
seek_pls = pls;
stream_subdemuxer_index = j;
break;
}
}
}
/* check if the timestamp is valid for the playlist with the
* specified stream index */
if (!seek_pls || !find_timestamp_in_playlist(c, seek_pls, seek_timestamp, &seq_no))
return AVERROR(EIO);
/* set segment now so we do not need to search again below */
seek_pls->cur_seq_no = seq_no;
seek_pls->seek_stream_index = stream_subdemuxer_index;
for (i = 0; i < c->n_playlists; i++) {
/* Reset reading */
struct playlist *pls = c->playlists[i];
if (pls->input)
ff_format_io_close(pls->parent, &pls->input);
av_packet_unref(&pls->pkt);
reset_packet(&pls->pkt);
pls->pb.eof_reached = 0;
/* Clear any buffered data */
pls->pb.buf_end = pls->pb.buf_ptr = pls->pb.buffer;
/* Reset the pos, to let the mpegts demuxer know we've seeked. */
pls->pb.pos = 0;
/* Flush the packet queue of the subdemuxer. */
ff_read_frame_flush(pls->ctx);
pls->seek_timestamp = seek_timestamp;
pls->seek_flags = flags;
if (pls != seek_pls) {
/* set closest segment seq_no for playlists not handled above */
find_timestamp_in_playlist(c, pls, seek_timestamp, &pls->cur_seq_no);
/* seek the playlist to the given position without taking
* keyframes into account since this playlist does not have the
* specified stream where we should look for the keyframes */
pls->seek_stream_index = -1;
pls->seek_flags |= AVSEEK_FLAG_ANY;
}
}
c->cur_timestamp = seek_timestamp;
return 0;
}
static int hls_probe(AVProbeData *p)
{
/* Require #EXTM3U at the start, and either one of the ones below
* somewhere for a proper match. */
if (strncmp(p->buf, "#EXTM3U", 7))
return 0;
if (strstr(p->buf, "#EXT-X-STREAM-INF:") ||
strstr(p->buf, "#EXT-X-TARGETDURATION:") ||
strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))
return AVPROBE_SCORE_MAX;
return 0;
}
#define OFFSET(x) offsetof(HLSContext, x)
#define FLAGS AV_OPT_FLAG_DECODING_PARAM
static const AVOption hls_options[] = {
{"live_start_index", "segment index to start live streams at (negative values are from the end)",
OFFSET(live_start_index), AV_OPT_TYPE_INT, {.i64 = -3}, INT_MIN, INT_MAX, FLAGS},
{"allowed_extensions", "List of file extensions that hls is allowed to access",
OFFSET(allowed_extensions), AV_OPT_TYPE_STRING,
{.str = "3gp,aac,avi,flac,mkv,m3u8,m4a,m4s,m4v,mpg,mov,mp2,mp3,mp4,mpeg,mpegts,ogg,ogv,oga,ts,vob,wav"},
INT_MIN, INT_MAX, FLAGS},
{NULL}
};
static const AVClass hls_class = {
.class_name = "hls,applehttp",
.item_name = av_default_item_name,
.option = hls_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVInputFormat ff_hls_demuxer = {
.name = "hls,applehttp",
.long_name = NULL_IF_CONFIG_SMALL("Apple HTTP Live Streaming"),
.priv_class = &hls_class,
.priv_data_size = sizeof(HLSContext),
.read_probe = hls_probe,
.read_header = hls_read_header,
.read_packet = hls_read_packet,
.read_close = hls_close,
.read_seek = hls_read_seek,
};
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2765_1 |
crossvul-cpp_data_good_2670_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
* IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com>
* DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net>
*/
/* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "af.h"
#include "oui.h"
#define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9)
#define LLDP_EXTRACT_LEN(x) ((x)&0x01ff)
/*
* TLV type codes
*/
#define LLDP_END_TLV 0
#define LLDP_CHASSIS_ID_TLV 1
#define LLDP_PORT_ID_TLV 2
#define LLDP_TTL_TLV 3
#define LLDP_PORT_DESCR_TLV 4
#define LLDP_SYSTEM_NAME_TLV 5
#define LLDP_SYSTEM_DESCR_TLV 6
#define LLDP_SYSTEM_CAP_TLV 7
#define LLDP_MGMT_ADDR_TLV 8
#define LLDP_PRIVATE_TLV 127
static const struct tok lldp_tlv_values[] = {
{ LLDP_END_TLV, "End" },
{ LLDP_CHASSIS_ID_TLV, "Chassis ID" },
{ LLDP_PORT_ID_TLV, "Port ID" },
{ LLDP_TTL_TLV, "Time to Live" },
{ LLDP_PORT_DESCR_TLV, "Port Description" },
{ LLDP_SYSTEM_NAME_TLV, "System Name" },
{ LLDP_SYSTEM_DESCR_TLV, "System Description" },
{ LLDP_SYSTEM_CAP_TLV, "System Capabilities" },
{ LLDP_MGMT_ADDR_TLV, "Management Address" },
{ LLDP_PRIVATE_TLV, "Organization specific" },
{ 0, NULL}
};
/*
* Chassis ID subtypes
*/
#define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1
#define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2
#define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3
#define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4
#define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5
#define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6
#define LLDP_CHASSIS_LOCAL_SUBTYPE 7
static const struct tok lldp_chassis_subtype_values[] = {
{ LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"},
{ LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"},
{ LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"},
{ LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* Port ID subtypes
*/
#define LLDP_PORT_INTF_ALIAS_SUBTYPE 1
#define LLDP_PORT_PORT_COMP_SUBTYPE 2
#define LLDP_PORT_MAC_ADDR_SUBTYPE 3
#define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4
#define LLDP_PORT_INTF_NAME_SUBTYPE 5
#define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6
#define LLDP_PORT_LOCAL_SUBTYPE 7
static const struct tok lldp_port_subtype_values[] = {
{ LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"},
{ LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"},
{ LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"},
{ LLDP_PORT_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* System Capabilities
*/
#define LLDP_CAP_OTHER (1 << 0)
#define LLDP_CAP_REPEATER (1 << 1)
#define LLDP_CAP_BRIDGE (1 << 2)
#define LLDP_CAP_WLAN_AP (1 << 3)
#define LLDP_CAP_ROUTER (1 << 4)
#define LLDP_CAP_PHONE (1 << 5)
#define LLDP_CAP_DOCSIS (1 << 6)
#define LLDP_CAP_STATION_ONLY (1 << 7)
static const struct tok lldp_cap_values[] = {
{ LLDP_CAP_OTHER, "Other"},
{ LLDP_CAP_REPEATER, "Repeater"},
{ LLDP_CAP_BRIDGE, "Bridge"},
{ LLDP_CAP_WLAN_AP, "WLAN AP"},
{ LLDP_CAP_ROUTER, "Router"},
{ LLDP_CAP_PHONE, "Telephone"},
{ LLDP_CAP_DOCSIS, "Docsis"},
{ LLDP_CAP_STATION_ONLY, "Station Only"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2
#define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12
#define LLDP_PRIVATE_8021_SUBTYPE_EVB 13
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14
static const struct tok lldp_8021_subtype_values[] = {
{ LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"},
{ LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"},
{ LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"},
{ LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"},
{ LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"},
{ LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"},
{ 0, NULL}
};
#define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1)
#define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2)
static const struct tok lldp_8021_port_protocol_id_values[] = {
{ LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"},
{ LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1
#define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2
#define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3
#define LLDP_PRIVATE_8023_SUBTYPE_MTU 4
static const struct tok lldp_8023_subtype_values[] = {
{ LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"},
{ LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"},
{ LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"},
{ LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"},
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1
#define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2
#define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3
#define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11
static const struct tok lldp_tia_subtype_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" },
{ LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" },
{ LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" },
{ LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" },
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2
static const struct tok lldp_tia_location_altitude_type_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"},
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"},
{ 0, NULL}
};
/* ANSI/TIA-1057 - Annex B */
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6
static const struct tok lldp_tia_location_lci_catype_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"},
{ 0, NULL}
};
static const struct tok lldp_tia_location_lci_what_values[] = {
{ 0, "location of DHCP server"},
{ 1, "location of the network element believed to be closest to the client"},
{ 2, "location of the client"},
{ 0, NULL}
};
/*
* From RFC 3636 - dot3MauType
*/
#define LLDP_MAU_TYPE_UNKNOWN 0
#define LLDP_MAU_TYPE_AUI 1
#define LLDP_MAU_TYPE_10BASE_5 2
#define LLDP_MAU_TYPE_FOIRL 3
#define LLDP_MAU_TYPE_10BASE_2 4
#define LLDP_MAU_TYPE_10BASE_T 5
#define LLDP_MAU_TYPE_10BASE_FP 6
#define LLDP_MAU_TYPE_10BASE_FB 7
#define LLDP_MAU_TYPE_10BASE_FL 8
#define LLDP_MAU_TYPE_10BROAD36 9
#define LLDP_MAU_TYPE_10BASE_T_HD 10
#define LLDP_MAU_TYPE_10BASE_T_FD 11
#define LLDP_MAU_TYPE_10BASE_FL_HD 12
#define LLDP_MAU_TYPE_10BASE_FL_FD 13
#define LLDP_MAU_TYPE_100BASE_T4 14
#define LLDP_MAU_TYPE_100BASE_TX_HD 15
#define LLDP_MAU_TYPE_100BASE_TX_FD 16
#define LLDP_MAU_TYPE_100BASE_FX_HD 17
#define LLDP_MAU_TYPE_100BASE_FX_FD 18
#define LLDP_MAU_TYPE_100BASE_T2_HD 19
#define LLDP_MAU_TYPE_100BASE_T2_FD 20
#define LLDP_MAU_TYPE_1000BASE_X_HD 21
#define LLDP_MAU_TYPE_1000BASE_X_FD 22
#define LLDP_MAU_TYPE_1000BASE_LX_HD 23
#define LLDP_MAU_TYPE_1000BASE_LX_FD 24
#define LLDP_MAU_TYPE_1000BASE_SX_HD 25
#define LLDP_MAU_TYPE_1000BASE_SX_FD 26
#define LLDP_MAU_TYPE_1000BASE_CX_HD 27
#define LLDP_MAU_TYPE_1000BASE_CX_FD 28
#define LLDP_MAU_TYPE_1000BASE_T_HD 29
#define LLDP_MAU_TYPE_1000BASE_T_FD 30
#define LLDP_MAU_TYPE_10GBASE_X 31
#define LLDP_MAU_TYPE_10GBASE_LX4 32
#define LLDP_MAU_TYPE_10GBASE_R 33
#define LLDP_MAU_TYPE_10GBASE_ER 34
#define LLDP_MAU_TYPE_10GBASE_LR 35
#define LLDP_MAU_TYPE_10GBASE_SR 36
#define LLDP_MAU_TYPE_10GBASE_W 37
#define LLDP_MAU_TYPE_10GBASE_EW 38
#define LLDP_MAU_TYPE_10GBASE_LW 39
#define LLDP_MAU_TYPE_10GBASE_SW 40
static const struct tok lldp_mau_types_values[] = {
{ LLDP_MAU_TYPE_UNKNOWN, "Unknown"},
{ LLDP_MAU_TYPE_AUI, "AUI"},
{ LLDP_MAU_TYPE_10BASE_5, "10BASE_5"},
{ LLDP_MAU_TYPE_FOIRL, "FOIRL"},
{ LLDP_MAU_TYPE_10BASE_2, "10BASE2"},
{ LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"},
{ LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"},
{ LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"},
{ LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"},
{ LLDP_MAU_TYPE_10BROAD36, "10BROAD36"},
{ LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"},
{ LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"},
{ LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"},
{ LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"},
{ LLDP_MAU_TYPE_100BASE_T4, "100BASET4"},
{ LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"},
{ LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"},
{ LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"},
{ LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"},
{ LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"},
{ LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"},
{ LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"},
{ LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"},
{ LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"},
{ LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"},
{ LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"},
{ LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"},
{ LLDP_MAU_TYPE_10GBASE_R, "10GBASER"},
{ LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"},
{ LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"},
{ LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"},
{ LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"},
{ LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"},
{ LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"},
{ LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"},
{ 0, NULL}
};
#define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0)
#define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1)
static const struct tok lldp_8023_autonegotiation_values[] = {
{ LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"},
{ LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_TIA_CAPABILITY_MED (1 << 0)
#define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1)
#define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4)
#define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5)
static const struct tok lldp_tia_capabilities_values[] = {
{ LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"},
{ LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"},
{ LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"},
{ LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"},
{ 0, NULL}
};
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3
#define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4
static const struct tok lldp_tia_device_type_values[] = {
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"},
{ LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"},
{ 0, NULL}
};
#define LLDP_TIA_APPLICATION_TYPE_VOICE 1
#define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4
#define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6
#define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8
static const struct tok lldp_tia_application_type_values[] = {
{ LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"},
{ LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"},
{ LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"},
{ 0, NULL}
};
#define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5)
#define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6)
#define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7)
static const struct tok lldp_tia_network_policy_bits_values[] = {
{ LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"},
{ LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"},
{ LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"},
{ 0, NULL}
};
#define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1)
#define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6)
#define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f)
#define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1
#define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2
#define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3
static const struct tok lldp_tia_location_data_format_values[] = {
{ LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"},
{ 0, NULL}
};
#define LLDP_TIA_LOCATION_DATUM_WGS_84 1
#define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2
#define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3
static const struct tok lldp_tia_location_datum_type_values[] = {
{ LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_SOURCE_PSE 1
#define LLDP_TIA_POWER_SOURCE_LOCAL 2
#define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3
static const struct tok lldp_tia_power_source_values[] = {
{ LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"},
{ LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"},
{ LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_PRIORITY_CRITICAL 1
#define LLDP_TIA_POWER_PRIORITY_HIGH 2
#define LLDP_TIA_POWER_PRIORITY_LOW 3
static const struct tok lldp_tia_power_priority_values[] = {
{ LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"},
{ LLDP_TIA_POWER_PRIORITY_HIGH, "high"},
{ LLDP_TIA_POWER_PRIORITY_LOW, "low"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_VAL_MAX 1024
static const struct tok lldp_tia_inventory_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" },
{ 0, NULL}
};
/*
* From RFC 3636 - ifMauAutoNegCapAdvertisedBits
*/
#define LLDP_MAU_PMD_OTHER (1 << 15)
#define LLDP_MAU_PMD_10BASE_T (1 << 14)
#define LLDP_MAU_PMD_10BASE_T_FD (1 << 13)
#define LLDP_MAU_PMD_100BASE_T4 (1 << 12)
#define LLDP_MAU_PMD_100BASE_TX (1 << 11)
#define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10)
#define LLDP_MAU_PMD_100BASE_T2 (1 << 9)
#define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8)
#define LLDP_MAU_PMD_FDXPAUSE (1 << 7)
#define LLDP_MAU_PMD_FDXAPAUSE (1 << 6)
#define LLDP_MAU_PMD_FDXSPAUSE (1 << 5)
#define LLDP_MAU_PMD_FDXBPAUSE (1 << 4)
#define LLDP_MAU_PMD_1000BASE_X (1 << 3)
#define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2)
#define LLDP_MAU_PMD_1000BASE_T (1 << 1)
#define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0)
static const struct tok lldp_pmd_capability_values[] = {
{ LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"},
{ LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"},
{ LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"},
{ LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"},
{ LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"},
{ LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"},
{ LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"},
{ LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"},
{ LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"},
{ LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"},
{ LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"},
{ LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"},
{ 0, NULL}
};
#define LLDP_MDI_PORT_CLASS (1 << 0)
#define LLDP_MDI_POWER_SUPPORT (1 << 1)
#define LLDP_MDI_POWER_STATE (1 << 2)
#define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3)
static const struct tok lldp_mdi_values[] = {
{ LLDP_MDI_PORT_CLASS, "PSE"},
{ LLDP_MDI_POWER_SUPPORT, "supported"},
{ LLDP_MDI_POWER_STATE, "enabled"},
{ LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"},
{ 0, NULL}
};
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2
static const struct tok lldp_mdi_power_pairs_values[] = {
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"},
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"},
{ 0, NULL}
};
#define LLDP_MDI_POWER_CLASS0 1
#define LLDP_MDI_POWER_CLASS1 2
#define LLDP_MDI_POWER_CLASS2 3
#define LLDP_MDI_POWER_CLASS3 4
#define LLDP_MDI_POWER_CLASS4 5
static const struct tok lldp_mdi_power_class_values[] = {
{ LLDP_MDI_POWER_CLASS0, "class0"},
{ LLDP_MDI_POWER_CLASS1, "class1"},
{ LLDP_MDI_POWER_CLASS2, "class2"},
{ LLDP_MDI_POWER_CLASS3, "class3"},
{ LLDP_MDI_POWER_CLASS4, "class4"},
{ 0, NULL}
};
#define LLDP_AGGREGATION_CAPABILTIY (1 << 0)
#define LLDP_AGGREGATION_STATUS (1 << 1)
static const struct tok lldp_aggregation_values[] = {
{ LLDP_AGGREGATION_CAPABILTIY, "supported"},
{ LLDP_AGGREGATION_STATUS, "enabled"},
{ 0, NULL}
};
/*
* DCBX protocol subtypes.
*/
#define LLDP_DCBX_SUBTYPE_1 1
#define LLDP_DCBX_SUBTYPE_2 2
static const struct tok lldp_dcbx_subtype_values[] = {
{ LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" },
{ LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" },
{ 0, NULL}
};
#define LLDP_DCBX_CONTROL_TLV 1
#define LLDP_DCBX_PRIORITY_GROUPS_TLV 2
#define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3
#define LLDP_DCBX_APPLICATION_TLV 4
/*
* Interface numbering subtypes.
*/
#define LLDP_INTF_NUMB_IFX_SUBTYPE 2
#define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3
static const struct tok lldp_intf_numb_subtype_values[] = {
{ LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" },
{ LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" },
{ 0, NULL}
};
#define LLDP_INTF_NUM_LEN 5
#define LLDP_EVB_MODE_NOT_SUPPORTED 0
#define LLDP_EVB_MODE_EVB_BRIDGE 1
#define LLDP_EVB_MODE_EVB_STATION 2
#define LLDP_EVB_MODE_RESERVED 3
static const struct tok lldp_evb_mode_values[]={
{ LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"},
{ LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"},
{ LLDP_EVB_MODE_EVB_STATION, "EVB Staion"},
{ LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"},
{ 0, NULL},
};
#define NO_OF_BITS 8
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5
#define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8
#define LLDP_IANA_SUBTYPE_MUDURL 1
static const struct tok lldp_iana_subtype_values[] = {
{ LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" },
{ 0, NULL }
};
static void
print_ets_priority_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t Priority Assignment Table"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4,
ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f));
}
static void
print_tc_bandwidth_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TC Bandwidth Table"));
ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
static void
print_tsa_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TSA Assignment Table"));
ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
/*
* Print IEEE 802.1 private extensions. (802.1AB annex E)
*/
static int
lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
u_int i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07),
EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print IEEE 802.3 private extensions. (802.3bc)
*/
static int
lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Extract 34bits of latitude/longitude coordinates.
*/
static uint64_t
lldp_extract_latlon(const u_char *tptr)
{
uint64_t latlon;
latlon = *tptr & 0x3;
latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1);
return latlon;
}
/* objects defined in IANA subtype 00 00 5e
* (right now there is only one)
*/
static int
lldp_private_iana_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 8) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_iana_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_IANA_SUBTYPE_MUDURL:
ND_PRINT((ndo, "\n\t MUD-URL="));
(void)fn_printn(ndo, tptr+4, tlv_len-4, NULL);
break;
default:
hexdump=TRUE;
}
return hexdump;
}
/*
* Print private TIA extensions.
*/
static int
lldp_private_tia_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
uint8_t location_format;
uint16_t power_val;
u_int lci_len;
uint8_t ca_type, ca_len;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_tia_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)",
bittok2str(lldp_tia_capabilities_values, "none",
EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4)));
ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)",
tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)),
*(tptr + 6)));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY:
if (tlv_len < 8) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)",
tok2str(lldp_tia_application_type_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, ", Flags [%s]", bittok2str(
lldp_tia_network_policy_bits_values, "none", *(tptr + 5))));
ND_PRINT((ndo, "\n\t Vlan id %u",
LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5))));
ND_PRINT((ndo, ", L2 priority %u",
LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6))));
ND_PRINT((ndo, ", DSCP value %u",
LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6))));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID:
if (tlv_len < 5) {
return hexdump;
}
location_format = *(tptr+4);
ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)",
tok2str(lldp_tia_location_data_format_values, "unknown", location_format),
location_format));
switch (location_format) {
case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED:
if (tlv_len < 21) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64,
(*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5)));
ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64,
(*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10)));
ND_PRINT((ndo, "\n\t Altitude type %s (%u)",
tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)),
(*(tptr + 15) >> 4)));
ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x",
(EXTRACT_16BITS(tptr+15)>>6)&0x3f,
((EXTRACT_32BITS(tptr + 16) & 0x3fffffff))));
ND_PRINT((ndo, "\n\t Datum %s (0x%02x)",
tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)),
*(tptr + 20)));
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS:
if (tlv_len < 6) {
return hexdump;
}
lci_len = *(tptr+5);
if (lci_len < 3) {
return hexdump;
}
if (tlv_len < 7+lci_len) {
return hexdump;
}
ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ",
lci_len,
tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)),
*(tptr + 6)));
/* Country code */
safeputs(ndo, tptr + 7, 2);
lci_len = lci_len-3;
tptr = tptr + 9;
/* Decode each civic address element */
while (lci_len > 0) {
if (lci_len < 2) {
return hexdump;
}
ca_type = *(tptr);
ca_len = *(tptr+1);
tptr += 2;
lci_len -= 2;
ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ",
tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type),
ca_type, ca_len));
/* basic sanity check */
if ( ca_type == 0 || ca_len == 0) {
return hexdump;
}
if (lci_len < ca_len) {
return hexdump;
}
safeputs(ndo, tptr, ca_len);
tptr += ca_len;
lci_len -= ca_len;
}
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN:
ND_PRINT((ndo, "\n\t ECS ELIN id "));
safeputs(ndo, tptr + 5, tlv_len - 5);
break;
default:
ND_PRINT((ndo, "\n\t Location ID "));
print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5);
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Power type [%s]",
(*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device"));
ND_PRINT((ndo, ", Power source [%s]",
tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4)));
ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)",
tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f),
*(tptr + 4) & 0x0f));
power_val = EXTRACT_16BITS(tptr+5);
if (power_val < LLDP_TIA_POWER_VAL_MAX) {
ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10));
} else {
ND_PRINT((ndo, ", Power %u (Reserved)", power_val));
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID:
ND_PRINT((ndo, "\n\t %s ",
tok2str(lldp_tia_inventory_values, "unknown", subtype)));
safeputs(ndo, tptr + 4, tlv_len - 4);
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print DCBX Protocol fields (V 1.01).
*/
static int
lldp_private_dcbx_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
int subtype, hexdump = FALSE;
uint8_t tval;
uint16_t tlv;
uint32_t i, pgval, uval;
u_int tlen, tlv_type, tlv_len;
const u_char *tptr, *mptr;
if (len < 4) {
return hexdump;
}
subtype = *(pptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_dcbx_subtype_values, "unknown", subtype),
subtype));
/* by passing old version */
if (subtype == LLDP_DCBX_SUBTYPE_1)
return TRUE;
tptr = pptr + 4;
tlen = len - 4;
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
/* loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
/* decode every tlv */
switch (tlv_type) {
case LLDP_DCBX_CONTROL_TLV:
if (tlv_len < 10) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)",
LLDP_DCBX_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2)));
ND_PRINT((ndo, "\n\t Acknowledgement Number: %d",
EXTRACT_32BITS(tptr + 6)));
break;
case LLDP_DCBX_PRIORITY_GROUPS_TLV:
if (tlv_len < 17) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
ND_PRINT((ndo, "\n\t Priority Allocation"));
/*
* Array of 8 4-bit priority group ID values; we fetch all
* 32 bits and extract each nibble.
*/
pgval = EXTRACT_32BITS(tptr+4);
for (i = 0; i <= 7; i++) {
ND_PRINT((ndo, "\n\t PgId_%d: %d",
i, (pgval >> (28 - 4 * i)) & 0xF));
}
ND_PRINT((ndo, "\n\t Priority Group Allocation"));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i)));
ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8)));
break;
case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV:
if (tlv_len < 6) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Flow Control"));
ND_PRINT((ndo, " (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = *(tptr+4);
ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4)));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Priority Bit %d: %s",
i, (tval & (1 << i)) ? "Enabled" : "Disabled"));
ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5)));
break;
case LLDP_DCBX_APPLICATION_TLV:
if (tlv_len < 4) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)",
LLDP_DCBX_APPLICATION_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = tlv_len - 4;
mptr = tptr + 4;
while (tval >= 6) {
ND_PRINT((ndo, "\n\t Application Value"));
ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x",
EXTRACT_16BITS(mptr)));
uval = EXTRACT_24BITS(mptr+2);
ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s",
(uval >> 22),
(uval >> 22) ? "Socket Number" : "L2 EtherType"));
ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff));
ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5)));
tval = tval - 6;
mptr = mptr + 6;
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
trunc:
return hexdump;
}
static char *
lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len)
{
uint8_t af;
static char buf[BUFSIZE];
const char * (*pfunc)(netdissect_options *, const u_char *);
if (len < 1)
return NULL;
len--;
af = *tptr;
switch (af) {
case AFNUM_INET:
if (len < 4)
return NULL;
/* This cannot be assigned to ipaddr_string(), which is a macro. */
pfunc = getname;
break;
case AFNUM_INET6:
if (len < 16)
return NULL;
/* This cannot be assigned to ip6addr_string(), which is a macro. */
pfunc = getname6;
break;
case AFNUM_802:
if (len < 6)
return NULL;
pfunc = etheraddr_string;
break;
default:
pfunc = NULL;
break;
}
if (!pfunc) {
snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !",
tok2str(af_values, "Unknown", af), af);
} else {
snprintf(buf, sizeof(buf), "AFI %s (%u): %s",
tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1));
}
return buf;
}
static int
lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
void
lldp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
uint8_t subtype;
uint16_t tlv, cap, ena_cap;
u_int oui, tlen, hexdump, tlv_type, tlv_len;
const u_char *tptr;
char *network_addr;
tptr = pptr;
tlen = len;
ND_PRINT((ndo, "LLDP, length %u", len));
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t%s TLV (%u), length %u",
tok2str(lldp_tlv_values, "Unknown", tlv_type),
tlv_type, tlv_len));
}
/* infinite loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
switch (tlv_type) {
case LLDP_CHASSIS_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_chassis_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_CHASSIS_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_CHASSIS_LOCAL_SUBTYPE:
case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE:
case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE:
case LLDP_CHASSIS_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_PORT_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_port_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PORT_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_PORT_LOCAL_SUBTYPE:
case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE:
case LLDP_PORT_INTF_ALIAS_SUBTYPE:
case LLDP_PORT_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_PORT_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_TTL_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr)));
}
break;
case LLDP_PORT_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_NAME_TLV:
/*
* The system name is also print in non-verbose mode
* similar to the CDP printer.
*/
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
break;
case LLDP_SYSTEM_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_CAP_TLV:
if (ndo->ndo_vflag) {
/*
* XXX - IEEE Std 802.1AB-2009 says the first octet
* if a chassis ID subtype, with the system
* capabilities and enabled capabilities following
* it.
*/
if (tlv_len < 4) {
goto trunc;
}
cap = EXTRACT_16BITS(tptr);
ena_cap = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", cap), cap));
ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", ena_cap), ena_cap));
}
break;
case LLDP_MGMT_ADDR_TLV:
if (ndo->ndo_vflag) {
if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) {
goto trunc;
}
}
break;
case LLDP_PRIVATE_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 3) {
goto trunc;
}
oui = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui));
switch (oui) {
case OUI_IEEE_8021_PRIVATE:
hexdump = lldp_private_8021_print(ndo, tptr, tlv_len);
break;
case OUI_IEEE_8023_PRIVATE:
hexdump = lldp_private_8023_print(ndo, tptr, tlv_len);
break;
case OUI_IANA:
hexdump = lldp_private_iana_print(ndo, tptr, tlv_len);
break;
case OUI_TIA:
hexdump = lldp_private_tia_print(ndo, tptr, tlv_len);
break;
case OUI_DCBX:
hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len);
break;
default:
hexdump = TRUE;
break;
}
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|LLDP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2670_0 |
crossvul-cpp_data_good_1665_0 | /*
* QEMU VNC display driver
*
* Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
* Copyright (C) 2006 Fabrice Bellard
* Copyright (C) 2009 Red Hat, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "vnc.h"
#include "vnc-jobs.h"
#include "trace.h"
#include "sysemu/sysemu.h"
#include "qemu/sockets.h"
#include "qemu/timer.h"
#include "qemu/acl.h"
#include "qapi/qmp/types.h"
#include "qmp-commands.h"
#include "qemu/osdep.h"
#include "ui/input.h"
#include "qapi-event.h"
#define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
#define VNC_REFRESH_INTERVAL_INC 50
#define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
#include "vnc_keysym.h"
#include "d3des.h"
static VncDisplay *vnc_display; /* needed for info vnc */
static int vnc_cursor_define(VncState *vs);
static void vnc_release_modifiers(VncState *vs);
static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
{
#ifdef _VNC_DEBUG
static const char *mn[] = {
[0] = "undefined",
[VNC_SHARE_MODE_CONNECTING] = "connecting",
[VNC_SHARE_MODE_SHARED] = "shared",
[VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
[VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
};
fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
vs->csock, mn[vs->share_mode], mn[mode]);
#endif
if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
vs->vd->num_exclusive--;
}
vs->share_mode = mode;
if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
vs->vd->num_exclusive++;
}
}
static char *addr_to_string(const char *format,
struct sockaddr_storage *sa,
socklen_t salen) {
char *addr;
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
int err;
size_t addrlen;
if ((err = getnameinfo((struct sockaddr *)sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
VNC_DEBUG("Cannot resolve address %d: %s\n",
err, gai_strerror(err));
return NULL;
}
/* Enough for the existing format + the 2 vars we're
* substituting in. */
addrlen = strlen(format) + strlen(host) + strlen(serv);
addr = g_malloc(addrlen + 1);
snprintf(addr, addrlen, format, host, serv);
addr[addrlen] = '\0';
return addr;
}
char *vnc_socket_local_addr(const char *format, int fd) {
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
return NULL;
return addr_to_string(format, &sa, salen);
}
char *vnc_socket_remote_addr(const char *format, int fd) {
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
return NULL;
return addr_to_string(format, &sa, salen);
}
static VncBasicInfo *vnc_basic_info_get(struct sockaddr_storage *sa,
socklen_t salen)
{
VncBasicInfo *info;
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
int err;
if ((err = getnameinfo((struct sockaddr *)sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
VNC_DEBUG("Cannot resolve address %d: %s\n",
err, gai_strerror(err));
return NULL;
}
info = g_malloc0(sizeof(VncBasicInfo));
info->host = g_strdup(host);
info->service = g_strdup(serv);
info->family = inet_netfamily(sa->ss_family);
return info;
}
static VncBasicInfo *vnc_basic_info_get_from_server_addr(int fd)
{
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
return NULL;
}
return vnc_basic_info_get(&sa, salen);
}
static VncBasicInfo *vnc_basic_info_get_from_remote_addr(int fd)
{
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
return NULL;
}
return vnc_basic_info_get(&sa, salen);
}
static const char *vnc_auth_name(VncDisplay *vd) {
switch (vd->auth) {
case VNC_AUTH_INVALID:
return "invalid";
case VNC_AUTH_NONE:
return "none";
case VNC_AUTH_VNC:
return "vnc";
case VNC_AUTH_RA2:
return "ra2";
case VNC_AUTH_RA2NE:
return "ra2ne";
case VNC_AUTH_TIGHT:
return "tight";
case VNC_AUTH_ULTRA:
return "ultra";
case VNC_AUTH_TLS:
return "tls";
case VNC_AUTH_VENCRYPT:
#ifdef CONFIG_VNC_TLS
switch (vd->subauth) {
case VNC_AUTH_VENCRYPT_PLAIN:
return "vencrypt+plain";
case VNC_AUTH_VENCRYPT_TLSNONE:
return "vencrypt+tls+none";
case VNC_AUTH_VENCRYPT_TLSVNC:
return "vencrypt+tls+vnc";
case VNC_AUTH_VENCRYPT_TLSPLAIN:
return "vencrypt+tls+plain";
case VNC_AUTH_VENCRYPT_X509NONE:
return "vencrypt+x509+none";
case VNC_AUTH_VENCRYPT_X509VNC:
return "vencrypt+x509+vnc";
case VNC_AUTH_VENCRYPT_X509PLAIN:
return "vencrypt+x509+plain";
case VNC_AUTH_VENCRYPT_TLSSASL:
return "vencrypt+tls+sasl";
case VNC_AUTH_VENCRYPT_X509SASL:
return "vencrypt+x509+sasl";
default:
return "vencrypt";
}
#else
return "vencrypt";
#endif
case VNC_AUTH_SASL:
return "sasl";
}
return "unknown";
}
static VncServerInfo *vnc_server_info_get(void)
{
VncServerInfo *info;
VncBasicInfo *bi = vnc_basic_info_get_from_server_addr(vnc_display->lsock);
if (!bi) {
return NULL;
}
info = g_malloc(sizeof(*info));
info->base = bi;
info->has_auth = true;
info->auth = g_strdup(vnc_auth_name(vnc_display));
return info;
}
static void vnc_client_cache_auth(VncState *client)
{
if (!client->info) {
return;
}
#ifdef CONFIG_VNC_TLS
if (client->tls.session &&
client->tls.dname) {
client->info->has_x509_dname = true;
client->info->x509_dname = g_strdup(client->tls.dname);
}
#endif
#ifdef CONFIG_VNC_SASL
if (client->sasl.conn &&
client->sasl.username) {
client->info->has_sasl_username = true;
client->info->sasl_username = g_strdup(client->sasl.username);
}
#endif
}
static void vnc_client_cache_addr(VncState *client)
{
VncBasicInfo *bi = vnc_basic_info_get_from_remote_addr(client->csock);
if (bi) {
client->info = g_malloc0(sizeof(*client->info));
client->info->base = bi;
}
}
static void vnc_qmp_event(VncState *vs, QAPIEvent event)
{
VncServerInfo *si;
if (!vs->info) {
return;
}
g_assert(vs->info->base);
si = vnc_server_info_get();
if (!si) {
return;
}
switch (event) {
case QAPI_EVENT_VNC_CONNECTED:
qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);
break;
case QAPI_EVENT_VNC_INITIALIZED:
qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
break;
case QAPI_EVENT_VNC_DISCONNECTED:
qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
break;
default:
break;
}
qapi_free_VncServerInfo(si);
}
static VncClientInfo *qmp_query_vnc_client(const VncState *client)
{
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
VncClientInfo *info;
if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
return NULL;
}
if (getnameinfo((struct sockaddr *)&sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
return NULL;
}
info = g_malloc0(sizeof(*info));
info->base = g_malloc0(sizeof(*info->base));
info->base->host = g_strdup(host);
info->base->service = g_strdup(serv);
info->base->family = inet_netfamily(sa.ss_family);
#ifdef CONFIG_VNC_TLS
if (client->tls.session && client->tls.dname) {
info->has_x509_dname = true;
info->x509_dname = g_strdup(client->tls.dname);
}
#endif
#ifdef CONFIG_VNC_SASL
if (client->sasl.conn && client->sasl.username) {
info->has_sasl_username = true;
info->sasl_username = g_strdup(client->sasl.username);
}
#endif
return info;
}
VncInfo *qmp_query_vnc(Error **errp)
{
VncInfo *info = g_malloc0(sizeof(*info));
if (vnc_display == NULL || vnc_display->display == NULL) {
info->enabled = false;
} else {
VncClientInfoList *cur_item = NULL;
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
VncState *client;
info->enabled = true;
/* for compatibility with the original command */
info->has_clients = true;
QTAILQ_FOREACH(client, &vnc_display->clients, next) {
VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
cinfo->value = qmp_query_vnc_client(client);
/* XXX: waiting for the qapi to support GSList */
if (!cur_item) {
info->clients = cur_item = cinfo;
} else {
cur_item->next = cinfo;
cur_item = cinfo;
}
}
if (vnc_display->lsock == -1) {
return info;
}
if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
&salen) == -1) {
error_set(errp, QERR_UNDEFINED_ERROR);
goto out_error;
}
if (getnameinfo((struct sockaddr *)&sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
error_set(errp, QERR_UNDEFINED_ERROR);
goto out_error;
}
info->has_host = true;
info->host = g_strdup(host);
info->has_service = true;
info->service = g_strdup(serv);
info->has_family = true;
info->family = inet_netfamily(sa.ss_family);
info->has_auth = true;
info->auth = g_strdup(vnc_auth_name(vnc_display));
}
return info;
out_error:
qapi_free_VncInfo(info);
return NULL;
}
/* TODO
1) Get the queue working for IO.
2) there is some weirdness when using the -S option (the screen is grey
and not totally invalidated
3) resolutions > 1024
*/
static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
static void vnc_disconnect_start(VncState *vs);
static void vnc_colordepth(VncState *vs);
static void framebuffer_update_request(VncState *vs, int incremental,
int x_position, int y_position,
int w, int h);
static void vnc_refresh(DisplayChangeListener *dcl);
static int vnc_refresh_server_surface(VncDisplay *vd);
static void vnc_dpy_update(DisplayChangeListener *dcl,
int x, int y, int w, int h)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
struct VncSurface *s = &vd->guest;
int width = surface_width(vd->ds);
int height = surface_height(vd->ds);
/* this is needed this to ensure we updated all affected
* blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
w += (x % VNC_DIRTY_PIXELS_PER_BIT);
x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
x = MIN(x, width);
y = MIN(y, height);
w = MIN(x + w, width) - x;
h = MIN(y + h, height);
for (; y < h; y++) {
bitmap_set(s->dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
}
}
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
int32_t encoding)
{
vnc_write_u16(vs, x);
vnc_write_u16(vs, y);
vnc_write_u16(vs, w);
vnc_write_u16(vs, h);
vnc_write_s32(vs, encoding);
}
void buffer_reserve(Buffer *buffer, size_t len)
{
if ((buffer->capacity - buffer->offset) < len) {
buffer->capacity += (len + 1024);
buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
if (buffer->buffer == NULL) {
fprintf(stderr, "vnc: out of memory\n");
exit(1);
}
}
}
static int buffer_empty(Buffer *buffer)
{
return buffer->offset == 0;
}
uint8_t *buffer_end(Buffer *buffer)
{
return buffer->buffer + buffer->offset;
}
void buffer_reset(Buffer *buffer)
{
buffer->offset = 0;
}
void buffer_free(Buffer *buffer)
{
g_free(buffer->buffer);
buffer->offset = 0;
buffer->capacity = 0;
buffer->buffer = NULL;
}
void buffer_append(Buffer *buffer, const void *data, size_t len)
{
memcpy(buffer->buffer + buffer->offset, data, len);
buffer->offset += len;
}
void buffer_advance(Buffer *buf, size_t len)
{
memmove(buf->buffer, buf->buffer + len,
(buf->offset - len));
buf->offset -= len;
}
static void vnc_desktop_resize(VncState *vs)
{
DisplaySurface *ds = vs->vd->ds;
if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
return;
}
if (vs->client_width == surface_width(ds) &&
vs->client_height == surface_height(ds)) {
return;
}
vs->client_width = surface_width(ds);
vs->client_height = surface_height(ds);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
VNC_ENCODING_DESKTOPRESIZE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_abort_display_jobs(VncDisplay *vd)
{
VncState *vs;
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = true;
vnc_unlock_output(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_jobs_join(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = false;
vnc_unlock_output(vs);
}
}
int vnc_server_fb_stride(VncDisplay *vd)
{
return pixman_image_get_stride(vd->server);
}
void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
{
uint8_t *ptr;
ptr = (uint8_t *)pixman_image_get_data(vd->server);
ptr += y * vnc_server_fb_stride(vd);
ptr += x * VNC_SERVER_FB_BYTES;
return ptr;
}
/* this sets only the visible pixels of a dirty bitmap */
#define VNC_SET_VISIBLE_PIXELS_DIRTY(bitmap, w, h) {\
int y;\
memset(bitmap, 0x00, sizeof(bitmap));\
for (y = 0; y < h; y++) {\
bitmap_set(bitmap[y], 0,\
DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));\
} \
}
static void vnc_dpy_switch(DisplayChangeListener *dcl,
DisplaySurface *surface)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs;
vnc_abort_display_jobs(vd);
/* server surface */
qemu_pixman_image_unref(vd->server);
vd->ds = surface;
vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
surface_width(vd->ds),
surface_height(vd->ds),
NULL, 0);
/* guest surface */
#if 0 /* FIXME */
if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
console_color_init(ds);
#endif
qemu_pixman_image_unref(vd->guest.fb);
vd->guest.fb = pixman_image_ref(surface->image);
vd->guest.format = surface->format;
VNC_SET_VISIBLE_PIXELS_DIRTY(vd->guest.dirty,
surface_width(vd->ds),
surface_height(vd->ds));
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_colordepth(vs);
vnc_desktop_resize(vs);
if (vs->vd->cursor) {
vnc_cursor_define(vs);
}
VNC_SET_VISIBLE_PIXELS_DIRTY(vs->dirty,
surface_width(vd->ds),
surface_height(vd->ds));
}
}
/* fastest code */
static void vnc_write_pixels_copy(VncState *vs,
void *pixels, int size)
{
vnc_write(vs, pixels, size);
}
/* slowest but generic code. */
void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
{
uint8_t r, g, b;
#if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
#else
# error need some bits here if you change VNC_SERVER_FB_FORMAT
#endif
v = (r << vs->client_pf.rshift) |
(g << vs->client_pf.gshift) |
(b << vs->client_pf.bshift);
switch (vs->client_pf.bytes_per_pixel) {
case 1:
buf[0] = v;
break;
case 2:
if (vs->client_be) {
buf[0] = v >> 8;
buf[1] = v;
} else {
buf[1] = v >> 8;
buf[0] = v;
}
break;
default:
case 4:
if (vs->client_be) {
buf[0] = v >> 24;
buf[1] = v >> 16;
buf[2] = v >> 8;
buf[3] = v;
} else {
buf[3] = v >> 24;
buf[2] = v >> 16;
buf[1] = v >> 8;
buf[0] = v;
}
break;
}
}
static void vnc_write_pixels_generic(VncState *vs,
void *pixels1, int size)
{
uint8_t buf[4];
if (VNC_SERVER_FB_BYTES == 4) {
uint32_t *pixels = pixels1;
int n, i;
n = size >> 2;
for (i = 0; i < n; i++) {
vnc_convert_pixel(vs, buf, pixels[i]);
vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
}
}
}
int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
{
int i;
uint8_t *row;
VncDisplay *vd = vs->vd;
row = vnc_server_fb_ptr(vd, x, y);
for (i = 0; i < h; i++) {
vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
row += vnc_server_fb_stride(vd);
}
return 1;
}
int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
{
int n = 0;
switch(vs->vnc_encoding) {
case VNC_ENCODING_ZLIB:
n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_HEXTILE:
vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_TIGHT:
n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_TIGHT_PNG:
n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_ZRLE:
n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_ZYWRLE:
n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
break;
default:
vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
break;
}
return n;
}
static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
{
/* send bitblit op to the vnc client */
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
vnc_write_u16(vs, src_x);
vnc_write_u16(vs, src_y);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_dpy_copy(DisplayChangeListener *dcl,
int src_x, int src_y,
int dst_x, int dst_y, int w, int h)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs, *vn;
uint8_t *src_row;
uint8_t *dst_row;
int i, x, y, pitch, inc, w_lim, s;
int cmp_bytes;
vnc_refresh_server_surface(vd);
QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
vs->force_update = 1;
vnc_update_client(vs, 1, true);
/* vs might be free()ed here */
}
}
/* do bitblit op on the local surface too */
pitch = vnc_server_fb_stride(vd);
src_row = vnc_server_fb_ptr(vd, src_x, src_y);
dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
y = dst_y;
inc = 1;
if (dst_y > src_y) {
/* copy backwards */
src_row += pitch * (h-1);
dst_row += pitch * (h-1);
pitch = -pitch;
y = dst_y + h - 1;
inc = -1;
}
w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
if (w_lim < 0) {
w_lim = w;
} else {
w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
}
for (i = 0; i < h; i++) {
for (x = 0; x <= w_lim;
x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
if (x == w_lim) {
if ((s = w - w_lim) == 0)
break;
} else if (!x) {
s = (VNC_DIRTY_PIXELS_PER_BIT -
(dst_x % VNC_DIRTY_PIXELS_PER_BIT));
s = MIN(s, w_lim);
} else {
s = VNC_DIRTY_PIXELS_PER_BIT;
}
cmp_bytes = s * VNC_SERVER_FB_BYTES;
if (memcmp(src_row, dst_row, cmp_bytes) == 0)
continue;
memmove(dst_row, src_row, cmp_bytes);
QTAILQ_FOREACH(vs, &vd->clients, next) {
if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
vs->dirty[y]);
}
}
}
src_row += pitch - w * VNC_SERVER_FB_BYTES;
dst_row += pitch - w * VNC_SERVER_FB_BYTES;
y += inc;
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
}
}
}
static void vnc_mouse_set(DisplayChangeListener *dcl,
int x, int y, int visible)
{
/* can we ask the client(s) to move the pointer ??? */
}
static int vnc_cursor_define(VncState *vs)
{
QEMUCursor *c = vs->vd->cursor;
int isize;
if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0); /* padding */
vnc_write_u16(vs, 1); /* # of rects */
vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
VNC_ENCODING_RICH_CURSOR);
isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
vnc_write_pixels_generic(vs, c->data, isize);
vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
vnc_unlock_output(vs);
return 0;
}
return -1;
}
static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
QEMUCursor *c)
{
VncDisplay *vd = vnc_display;
VncState *vs;
cursor_put(vd->cursor);
g_free(vd->cursor_mask);
vd->cursor = c;
cursor_get(vd->cursor);
vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
vd->cursor_mask = g_malloc0(vd->cursor_msize);
cursor_get_mono_mask(c, 0, vd->cursor_mask);
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_cursor_define(vs);
}
}
static int find_and_clear_dirty_height(struct VncState *vs,
int y, int last_x, int x, int height)
{
int h;
for (h = 1; h < (height - y); h++) {
if (!test_bit(last_x, vs->dirty[y + h])) {
break;
}
bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
}
return h;
}
static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
{
if (vs->need_update && vs->csock != -1) {
VncDisplay *vd = vs->vd;
VncJob *job;
int y;
int height, width;
int n = 0;
if (vs->output.offset && !vs->audio_cap && !vs->force_update)
/* kernel send buffers are full -> drop frames to throttle */
return 0;
if (!has_dirty && !vs->audio_cap && !vs->force_update)
return 0;
/*
* Send screen updates to the vnc client using the server
* surface and server dirty map. guest surface updates
* happening in parallel don't disturb us, the next pass will
* send them to the client.
*/
job = vnc_job_new(vs);
height = MIN(pixman_image_get_height(vd->server), vs->client_height);
width = MIN(pixman_image_get_width(vd->server), vs->client_width);
y = 0;
for (;;) {
int x, h;
unsigned long x2;
unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
height * VNC_DIRTY_BPL(vs),
y * VNC_DIRTY_BPL(vs));
if (offset == height * VNC_DIRTY_BPL(vs)) {
/* no more dirty bits */
break;
}
y = offset / VNC_DIRTY_BPL(vs);
x = offset % VNC_DIRTY_BPL(vs);
x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
VNC_DIRTY_BPL(vs), x);
bitmap_clear(vs->dirty[y], x, x2 - x);
h = find_and_clear_dirty_height(vs, y, x, x2, height);
x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
if (x2 > x) {
n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
(x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
}
}
vnc_job_push(job);
if (sync) {
vnc_jobs_join(vs);
}
vs->force_update = 0;
return n;
}
if (vs->csock == -1) {
vnc_disconnect_finish(vs);
} else if (sync) {
vnc_jobs_join(vs);
}
return 0;
}
/* audio */
static void audio_capture_notify(void *opaque, audcnotification_e cmd)
{
VncState *vs = opaque;
switch (cmd) {
case AUD_CNOTIFY_DISABLE:
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
vnc_unlock_output(vs);
vnc_flush(vs);
break;
case AUD_CNOTIFY_ENABLE:
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
vnc_unlock_output(vs);
vnc_flush(vs);
break;
}
}
static void audio_capture_destroy(void *opaque)
{
}
static void audio_capture(void *opaque, void *buf, int size)
{
VncState *vs = opaque;
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
vnc_write_u32(vs, size);
vnc_write(vs, buf, size);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void audio_add(VncState *vs)
{
struct audio_capture_ops ops;
if (vs->audio_cap) {
error_report("audio already running");
return;
}
ops.notify = audio_capture_notify;
ops.destroy = audio_capture_destroy;
ops.capture = audio_capture;
vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
if (!vs->audio_cap) {
error_report("Failed to add audio capture");
}
}
static void audio_del(VncState *vs)
{
if (vs->audio_cap) {
AUD_del_capture(vs->audio_cap, vs);
vs->audio_cap = NULL;
}
}
static void vnc_disconnect_start(VncState *vs)
{
if (vs->csock == -1)
return;
vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
closesocket(vs->csock);
vs->csock = -1;
}
void vnc_disconnect_finish(VncState *vs)
{
int i;
vnc_jobs_join(vs); /* Wait encoding jobs */
vnc_lock_output(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
buffer_free(&vs->input);
buffer_free(&vs->output);
#ifdef CONFIG_VNC_WS
buffer_free(&vs->ws_input);
buffer_free(&vs->ws_output);
#endif /* CONFIG_VNC_WS */
qapi_free_VncClientInfo(vs->info);
vnc_zlib_clear(vs);
vnc_tight_clear(vs);
vnc_zrle_clear(vs);
#ifdef CONFIG_VNC_TLS
vnc_tls_client_cleanup(vs);
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
vnc_sasl_client_cleanup(vs);
#endif /* CONFIG_VNC_SASL */
audio_del(vs);
vnc_release_modifiers(vs);
if (vs->initialized) {
QTAILQ_REMOVE(&vs->vd->clients, vs, next);
qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
}
if (vs->vd->lock_key_sync)
qemu_remove_led_event_handler(vs->led);
vnc_unlock_output(vs);
qemu_mutex_destroy(&vs->output_mutex);
if (vs->bh != NULL) {
qemu_bh_delete(vs->bh);
}
buffer_free(&vs->jobs_buffer);
for (i = 0; i < VNC_STAT_ROWS; ++i) {
g_free(vs->lossy_rect[i]);
}
g_free(vs->lossy_rect);
g_free(vs);
}
int vnc_client_io_error(VncState *vs, int ret, int last_errno)
{
if (ret == 0 || ret == -1) {
if (ret == -1) {
switch (last_errno) {
case EINTR:
case EAGAIN:
#ifdef _WIN32
case WSAEWOULDBLOCK:
#endif
return 0;
default:
break;
}
}
VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
ret, ret < 0 ? last_errno : 0);
vnc_disconnect_start(vs);
return 0;
}
return ret;
}
void vnc_client_error(VncState *vs)
{
VNC_DEBUG("Closing down client sock: protocol error\n");
vnc_disconnect_start(vs);
}
#ifdef CONFIG_VNC_TLS
static long vnc_client_write_tls(gnutls_session_t *session,
const uint8_t *data,
size_t datalen)
{
long ret = gnutls_write(*session, data, datalen);
if (ret < 0) {
if (ret == GNUTLS_E_AGAIN) {
errno = EAGAIN;
} else {
errno = EIO;
}
ret = -1;
}
return ret;
}
#endif /* CONFIG_VNC_TLS */
/*
* Called to write a chunk of data to the client socket. The data may
* be the raw data, or may have already been encoded by SASL.
* The data will be written either straight onto the socket, or
* written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
*
* NB, it is theoretically possible to have 2 layers of encryption,
* both SASL, and this TLS layer. It is highly unlikely in practice
* though, since SASL encryption will typically be a no-op if TLS
* is active
*
* Returns the number of bytes written, which may be less than
* the requested 'datalen' if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
{
long ret;
#ifdef CONFIG_VNC_TLS
if (vs->tls.session) {
ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
} else {
#ifdef CONFIG_VNC_WS
if (vs->ws_tls.session) {
ret = vnc_client_write_tls(&vs->ws_tls.session, data, datalen);
} else
#endif /* CONFIG_VNC_WS */
#endif /* CONFIG_VNC_TLS */
{
ret = send(vs->csock, (const void *)data, datalen, 0);
}
#ifdef CONFIG_VNC_TLS
}
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
return vnc_client_io_error(vs, ret, socket_error());
}
/*
* Called to write buffered data to the client socket, when not
* using any SASL SSF encryption layers. Will write as much data
* as possible without blocking. If all buffered data is written,
* will switch the FD poll() handler back to read monitoring.
*
* Returns the number of bytes written, which may be less than
* the buffered output data if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
static long vnc_client_write_plain(VncState *vs)
{
long ret;
#ifdef CONFIG_VNC_SASL
VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
vs->output.buffer, vs->output.capacity, vs->output.offset,
vs->sasl.waitWriteSSF);
if (vs->sasl.conn &&
vs->sasl.runSSF &&
vs->sasl.waitWriteSSF) {
ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
if (ret)
vs->sasl.waitWriteSSF -= ret;
} else
#endif /* CONFIG_VNC_SASL */
ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
if (!ret)
return 0;
buffer_advance(&vs->output, ret);
if (vs->output.offset == 0) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
return ret;
}
/*
* First function called whenever there is data to be written to
* the client socket. Will delegate actual work according to whether
* SASL SSF layers are enabled (thus requiring encryption calls)
*/
static void vnc_client_write_locked(void *opaque)
{
VncState *vs = opaque;
#ifdef CONFIG_VNC_SASL
if (vs->sasl.conn &&
vs->sasl.runSSF &&
!vs->sasl.waitWriteSSF) {
vnc_client_write_sasl(vs);
} else
#endif /* CONFIG_VNC_SASL */
{
#ifdef CONFIG_VNC_WS
if (vs->encode_ws) {
vnc_client_write_ws(vs);
} else
#endif /* CONFIG_VNC_WS */
{
vnc_client_write_plain(vs);
}
}
}
void vnc_client_write(void *opaque)
{
VncState *vs = opaque;
vnc_lock_output(vs);
if (vs->output.offset
#ifdef CONFIG_VNC_WS
|| vs->ws_output.offset
#endif
) {
vnc_client_write_locked(opaque);
} else if (vs->csock != -1) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
vnc_unlock_output(vs);
}
void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
{
vs->read_handler = func;
vs->read_handler_expect = expecting;
}
#ifdef CONFIG_VNC_TLS
static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
size_t datalen)
{
long ret = gnutls_read(*session, data, datalen);
if (ret < 0) {
if (ret == GNUTLS_E_AGAIN) {
errno = EAGAIN;
} else {
errno = EIO;
}
ret = -1;
}
return ret;
}
#endif /* CONFIG_VNC_TLS */
/*
* Called to read a chunk of data from the client socket. The data may
* be the raw data, or may need to be further decoded by SASL.
* The data will be read either straight from to the socket, or
* read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
*
* NB, it is theoretically possible to have 2 layers of encryption,
* both SASL, and this TLS layer. It is highly unlikely in practice
* though, since SASL encryption will typically be a no-op if TLS
* is active
*
* Returns the number of bytes read, which may be less than
* the requested 'datalen' if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
{
long ret;
#ifdef CONFIG_VNC_TLS
if (vs->tls.session) {
ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
} else {
#ifdef CONFIG_VNC_WS
if (vs->ws_tls.session) {
ret = vnc_client_read_tls(&vs->ws_tls.session, data, datalen);
} else
#endif /* CONFIG_VNC_WS */
#endif /* CONFIG_VNC_TLS */
{
ret = qemu_recv(vs->csock, data, datalen, 0);
}
#ifdef CONFIG_VNC_TLS
}
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
return vnc_client_io_error(vs, ret, socket_error());
}
/*
* Called to read data from the client socket to the input buffer,
* when not using any SASL SSF encryption layers. Will read as much
* data as possible without blocking.
*
* Returns the number of bytes read. Returns -1 on error, and
* disconnects the client socket.
*/
static long vnc_client_read_plain(VncState *vs)
{
int ret;
VNC_DEBUG("Read plain %p size %zd offset %zd\n",
vs->input.buffer, vs->input.capacity, vs->input.offset);
buffer_reserve(&vs->input, 4096);
ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
if (!ret)
return 0;
vs->input.offset += ret;
return ret;
}
static void vnc_jobs_bh(void *opaque)
{
VncState *vs = opaque;
vnc_jobs_consume_buffer(vs);
}
/*
* First function called whenever there is more data to be read from
* the client socket. Will delegate actual work according to whether
* SASL SSF layers are enabled (thus requiring decryption calls)
*/
void vnc_client_read(void *opaque)
{
VncState *vs = opaque;
long ret;
#ifdef CONFIG_VNC_SASL
if (vs->sasl.conn && vs->sasl.runSSF)
ret = vnc_client_read_sasl(vs);
else
#endif /* CONFIG_VNC_SASL */
#ifdef CONFIG_VNC_WS
if (vs->encode_ws) {
ret = vnc_client_read_ws(vs);
if (ret == -1) {
vnc_disconnect_start(vs);
return;
} else if (ret == -2) {
vnc_client_error(vs);
return;
}
} else
#endif /* CONFIG_VNC_WS */
{
ret = vnc_client_read_plain(vs);
}
if (!ret) {
if (vs->csock == -1)
vnc_disconnect_finish(vs);
return;
}
while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
size_t len = vs->read_handler_expect;
int ret;
ret = vs->read_handler(vs, vs->input.buffer, len);
if (vs->csock == -1) {
vnc_disconnect_finish(vs);
return;
}
if (!ret) {
buffer_advance(&vs->input, len);
} else {
vs->read_handler_expect = ret;
}
}
}
void vnc_write(VncState *vs, const void *data, size_t len)
{
buffer_reserve(&vs->output, len);
if (vs->csock != -1 && buffer_empty(&vs->output)) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
}
buffer_append(&vs->output, data, len);
}
void vnc_write_s32(VncState *vs, int32_t value)
{
vnc_write_u32(vs, *(uint32_t *)&value);
}
void vnc_write_u32(VncState *vs, uint32_t value)
{
uint8_t buf[4];
buf[0] = (value >> 24) & 0xFF;
buf[1] = (value >> 16) & 0xFF;
buf[2] = (value >> 8) & 0xFF;
buf[3] = value & 0xFF;
vnc_write(vs, buf, 4);
}
void vnc_write_u16(VncState *vs, uint16_t value)
{
uint8_t buf[2];
buf[0] = (value >> 8) & 0xFF;
buf[1] = value & 0xFF;
vnc_write(vs, buf, 2);
}
void vnc_write_u8(VncState *vs, uint8_t value)
{
vnc_write(vs, (char *)&value, 1);
}
void vnc_flush(VncState *vs)
{
vnc_lock_output(vs);
if (vs->csock != -1 && (vs->output.offset
#ifdef CONFIG_VNC_WS
|| vs->ws_output.offset
#endif
)) {
vnc_client_write_locked(vs);
}
vnc_unlock_output(vs);
}
static uint8_t read_u8(uint8_t *data, size_t offset)
{
return data[offset];
}
static uint16_t read_u16(uint8_t *data, size_t offset)
{
return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
}
static int32_t read_s32(uint8_t *data, size_t offset)
{
return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]);
}
uint32_t read_u32(uint8_t *data, size_t offset)
{
return ((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]);
}
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
{
}
static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
static void pointer_event(VncState *vs, int button_mask, int x, int y)
{
static uint32_t bmap[INPUT_BUTTON_MAX] = {
[INPUT_BUTTON_LEFT] = 0x01,
[INPUT_BUTTON_MIDDLE] = 0x02,
[INPUT_BUTTON_RIGHT] = 0x04,
[INPUT_BUTTON_WHEEL_UP] = 0x08,
[INPUT_BUTTON_WHEEL_DOWN] = 0x10,
};
QemuConsole *con = vs->vd->dcl.con;
int width = surface_width(vs->vd->ds);
int height = surface_height(vs->vd->ds);
if (vs->last_bmask != button_mask) {
qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
vs->last_bmask = button_mask;
}
if (vs->absolute) {
qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
} else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
} else {
if (vs->last_x != -1) {
qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
}
vs->last_x = x;
vs->last_y = y;
}
qemu_input_event_sync();
}
static void reset_keys(VncState *vs)
{
int i;
for(i = 0; i < 256; i++) {
if (vs->modifiers_state[i]) {
qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
vs->modifiers_state[i] = 0;
}
}
}
static void press_key(VncState *vs, int keysym)
{
int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
qemu_input_event_send_key_delay(0);
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
qemu_input_event_send_key_delay(0);
}
static int current_led_state(VncState *vs)
{
int ledstate = 0;
if (vs->modifiers_state[0x46]) {
ledstate |= QEMU_SCROLL_LOCK_LED;
}
if (vs->modifiers_state[0x45]) {
ledstate |= QEMU_NUM_LOCK_LED;
}
if (vs->modifiers_state[0x3a]) {
ledstate |= QEMU_CAPS_LOCK_LED;
}
return ledstate;
}
static void vnc_led_state_change(VncState *vs)
{
int ledstate = 0;
if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
return;
}
ledstate = current_led_state(vs);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
vnc_write_u8(vs, ledstate);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void kbd_leds(void *opaque, int ledstate)
{
VncState *vs = opaque;
int caps, num, scr;
bool has_changed = (ledstate != current_led_state(vs));
trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
(ledstate & QEMU_NUM_LOCK_LED),
(ledstate & QEMU_SCROLL_LOCK_LED));
caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
scr = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
if (vs->modifiers_state[0x3a] != caps) {
vs->modifiers_state[0x3a] = caps;
}
if (vs->modifiers_state[0x45] != num) {
vs->modifiers_state[0x45] = num;
}
if (vs->modifiers_state[0x46] != scr) {
vs->modifiers_state[0x46] = scr;
}
/* Sending the current led state message to the client */
if (has_changed) {
vnc_led_state_change(vs);
}
}
static void do_key_event(VncState *vs, int down, int keycode, int sym)
{
/* QEMU console switch */
switch(keycode) {
case 0x2a: /* Left Shift */
case 0x36: /* Right Shift */
case 0x1d: /* Left CTRL */
case 0x9d: /* Right CTRL */
case 0x38: /* Left ALT */
case 0xb8: /* Right ALT */
if (down)
vs->modifiers_state[keycode] = 1;
else
vs->modifiers_state[keycode] = 0;
break;
case 0x02 ... 0x0a: /* '1' to '9' keys */
if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
/* Reset the modifiers sent to the current console */
reset_keys(vs);
console_select(keycode - 0x02);
return;
}
break;
case 0x3a: /* CapsLock */
case 0x45: /* NumLock */
if (down)
vs->modifiers_state[keycode] ^= 1;
break;
}
/* Turn off the lock state sync logic if the client support the led
state extension.
*/
if (down && vs->vd->lock_key_sync &&
!vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
/* If the numlock state needs to change then simulate an additional
keypress before sending this one. This will happen if the user
toggles numlock away from the VNC window.
*/
if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
if (!vs->modifiers_state[0x45]) {
trace_vnc_key_sync_numlock(true);
vs->modifiers_state[0x45] = 1;
press_key(vs, 0xff7f);
}
} else {
if (vs->modifiers_state[0x45]) {
trace_vnc_key_sync_numlock(false);
vs->modifiers_state[0x45] = 0;
press_key(vs, 0xff7f);
}
}
}
if (down && vs->vd->lock_key_sync &&
!vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
/* If the capslock state needs to change then simulate an additional
keypress before sending this one. This will happen if the user
toggles capslock away from the VNC window.
*/
int uppercase = !!(sym >= 'A' && sym <= 'Z');
int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
int capslock = !!(vs->modifiers_state[0x3a]);
if (capslock) {
if (uppercase == shift) {
trace_vnc_key_sync_capslock(false);
vs->modifiers_state[0x3a] = 0;
press_key(vs, 0xffe5);
}
} else {
if (uppercase != shift) {
trace_vnc_key_sync_capslock(true);
vs->modifiers_state[0x3a] = 1;
press_key(vs, 0xffe5);
}
}
}
if (qemu_console_is_graphic(NULL)) {
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
} else {
bool numlock = vs->modifiers_state[0x45];
bool control = (vs->modifiers_state[0x1d] ||
vs->modifiers_state[0x9d]);
/* QEMU console emulation */
if (down) {
switch (keycode) {
case 0x2a: /* Left Shift */
case 0x36: /* Right Shift */
case 0x1d: /* Left CTRL */
case 0x9d: /* Right CTRL */
case 0x38: /* Left ALT */
case 0xb8: /* Right ALT */
break;
case 0xc8:
kbd_put_keysym(QEMU_KEY_UP);
break;
case 0xd0:
kbd_put_keysym(QEMU_KEY_DOWN);
break;
case 0xcb:
kbd_put_keysym(QEMU_KEY_LEFT);
break;
case 0xcd:
kbd_put_keysym(QEMU_KEY_RIGHT);
break;
case 0xd3:
kbd_put_keysym(QEMU_KEY_DELETE);
break;
case 0xc7:
kbd_put_keysym(QEMU_KEY_HOME);
break;
case 0xcf:
kbd_put_keysym(QEMU_KEY_END);
break;
case 0xc9:
kbd_put_keysym(QEMU_KEY_PAGEUP);
break;
case 0xd1:
kbd_put_keysym(QEMU_KEY_PAGEDOWN);
break;
case 0x47:
kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
break;
case 0x48:
kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
break;
case 0x49:
kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
break;
case 0x4b:
kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
break;
case 0x4c:
kbd_put_keysym('5');
break;
case 0x4d:
kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
break;
case 0x4f:
kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
break;
case 0x50:
kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
break;
case 0x51:
kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
break;
case 0x52:
kbd_put_keysym('0');
break;
case 0x53:
kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
break;
case 0xb5:
kbd_put_keysym('/');
break;
case 0x37:
kbd_put_keysym('*');
break;
case 0x4a:
kbd_put_keysym('-');
break;
case 0x4e:
kbd_put_keysym('+');
break;
case 0x9c:
kbd_put_keysym('\n');
break;
default:
if (control) {
kbd_put_keysym(sym & 0x1f);
} else {
kbd_put_keysym(sym);
}
break;
}
}
}
}
static void vnc_release_modifiers(VncState *vs)
{
static const int keycodes[] = {
/* shift, control, alt keys, both left & right */
0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
};
int i, keycode;
if (!qemu_console_is_graphic(NULL)) {
return;
}
for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
keycode = keycodes[i];
if (!vs->modifiers_state[keycode]) {
continue;
}
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
}
}
static const char *code2name(int keycode)
{
return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
}
static void key_event(VncState *vs, int down, uint32_t sym)
{
int keycode;
int lsym = sym;
if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
lsym = lsym - 'A' + 'a';
}
keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
do_key_event(vs, down, keycode, sym);
}
static void ext_key_event(VncState *vs, int down,
uint32_t sym, uint16_t keycode)
{
/* if the user specifies a keyboard layout, always use it */
if (keyboard_layout) {
key_event(vs, down, sym);
} else {
trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
do_key_event(vs, down, keycode, sym);
}
}
static void framebuffer_update_request(VncState *vs, int incremental,
int x_position, int y_position,
int w, int h)
{
int i;
const size_t width = surface_width(vs->vd->ds) / VNC_DIRTY_PIXELS_PER_BIT;
const size_t height = surface_height(vs->vd->ds);
if (y_position > height) {
y_position = height;
}
if (y_position + h >= height) {
h = height - y_position;
}
vs->need_update = 1;
if (!incremental) {
vs->force_update = 1;
for (i = 0; i < h; i++) {
bitmap_set(vs->dirty[y_position + i], 0, width);
bitmap_clear(vs->dirty[y_position + i], width,
VNC_DIRTY_BITS - width);
}
}
}
static void send_ext_key_event_ack(VncState *vs)
{
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_EXT_KEY_EVENT);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void send_ext_audio_ack(VncState *vs)
{
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_AUDIO);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
{
int i;
unsigned int enc = 0;
vs->features = 0;
vs->vnc_encoding = 0;
vs->tight.compression = 9;
vs->tight.quality = -1; /* Lossless by default */
vs->absolute = -1;
/*
* Start from the end because the encodings are sent in order of preference.
* This way the preferred encoding (first encoding defined in the array)
* will be set at the end of the loop.
*/
for (i = n_encodings - 1; i >= 0; i--) {
enc = encodings[i];
switch (enc) {
case VNC_ENCODING_RAW:
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_COPYRECT:
vs->features |= VNC_FEATURE_COPYRECT_MASK;
break;
case VNC_ENCODING_HEXTILE:
vs->features |= VNC_FEATURE_HEXTILE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_TIGHT:
vs->features |= VNC_FEATURE_TIGHT_MASK;
vs->vnc_encoding = enc;
break;
#ifdef CONFIG_VNC_PNG
case VNC_ENCODING_TIGHT_PNG:
vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
vs->vnc_encoding = enc;
break;
#endif
case VNC_ENCODING_ZLIB:
vs->features |= VNC_FEATURE_ZLIB_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_ZRLE:
vs->features |= VNC_FEATURE_ZRLE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_ZYWRLE:
vs->features |= VNC_FEATURE_ZYWRLE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_DESKTOPRESIZE:
vs->features |= VNC_FEATURE_RESIZE_MASK;
break;
case VNC_ENCODING_POINTER_TYPE_CHANGE:
vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
break;
case VNC_ENCODING_RICH_CURSOR:
vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
break;
case VNC_ENCODING_EXT_KEY_EVENT:
send_ext_key_event_ack(vs);
break;
case VNC_ENCODING_AUDIO:
send_ext_audio_ack(vs);
break;
case VNC_ENCODING_WMVi:
vs->features |= VNC_FEATURE_WMVI_MASK;
break;
case VNC_ENCODING_LED_STATE:
vs->features |= VNC_FEATURE_LED_STATE_MASK;
break;
case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
vs->tight.compression = (enc & 0x0F);
break;
case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
if (vs->vd->lossy) {
vs->tight.quality = (enc & 0x0F);
}
break;
default:
VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
break;
}
}
vnc_desktop_resize(vs);
check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
vnc_led_state_change(vs);
}
static void set_pixel_conversion(VncState *vs)
{
pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
if (fmt == VNC_SERVER_FB_FORMAT) {
vs->write_pixels = vnc_write_pixels_copy;
vnc_hextile_set_pixel_conversion(vs, 0);
} else {
vs->write_pixels = vnc_write_pixels_generic;
vnc_hextile_set_pixel_conversion(vs, 1);
}
}
static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.rmask = red_max << red_shift;
vs->client_pf.gmax = green_max;
vs->client_pf.gbits = hweight_long(green_max);
vs->client_pf.gshift = green_shift;
vs->client_pf.gmask = green_max << green_shift;
vs->client_pf.bmax = blue_max;
vs->client_pf.bbits = hweight_long(blue_max);
vs->client_pf.bshift = blue_shift;
vs->client_pf.bmask = blue_max << blue_shift;
vs->client_pf.bits_per_pixel = bits_per_pixel;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
static void pixel_format_message (VncState *vs) {
char pad[3] = { 0, 0, 0 };
vs->client_pf = qemu_default_pixelformat(32);
vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
vnc_write_u8(vs, vs->client_pf.depth); /* depth */
#ifdef HOST_WORDS_BIGENDIAN
vnc_write_u8(vs, 1); /* big-endian-flag */
#else
vnc_write_u8(vs, 0); /* big-endian-flag */
#endif
vnc_write_u8(vs, 1); /* true-color-flag */
vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
vnc_write(vs, pad, 3); /* padding */
vnc_hextile_set_pixel_conversion(vs, 0);
vs->write_pixels = vnc_write_pixels_copy;
}
static void vnc_colordepth(VncState *vs)
{
if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
/* Sending a WMVi message to notify the client*/
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_WMVi);
pixel_format_message(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
} else {
set_pixel_conversion(vs);
}
}
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
{
int i;
uint16_t limit;
VncDisplay *vd = vs->vd;
if (data[0] > 3) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
}
switch (data[0]) {
case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
if (len == 1)
return 20;
set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
read_u8(data, 6), read_u8(data, 7),
read_u16(data, 8), read_u16(data, 10),
read_u16(data, 12), read_u8(data, 14),
read_u8(data, 15), read_u8(data, 16));
break;
case VNC_MSG_CLIENT_SET_ENCODINGS:
if (len == 1)
return 4;
if (len == 4) {
limit = read_u16(data, 2);
if (limit > 0)
return 4 + (limit * 4);
} else
limit = read_u16(data, 2);
for (i = 0; i < limit; i++) {
int32_t val = read_s32(data, 4 + (i * 4));
memcpy(data + 4 + (i * 4), &val, sizeof(val));
}
set_encodings(vs, (int32_t *)(data + 4), limit);
break;
case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
if (len == 1)
return 10;
framebuffer_update_request(vs,
read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
read_u16(data, 6), read_u16(data, 8));
break;
case VNC_MSG_CLIENT_KEY_EVENT:
if (len == 1)
return 8;
key_event(vs, read_u8(data, 1), read_u32(data, 4));
break;
case VNC_MSG_CLIENT_POINTER_EVENT:
if (len == 1)
return 6;
pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
break;
case VNC_MSG_CLIENT_CUT_TEXT:
if (len == 1) {
return 8;
}
if (len == 8) {
uint32_t dlen = read_u32(data, 4);
if (dlen > (1 << 20)) {
error_report("vnc: client_cut_text msg payload has %u bytes"
" which exceeds our limit of 1MB.", dlen);
vnc_client_error(vs);
break;
}
if (dlen > 0) {
return 8 + dlen;
}
}
client_cut_text(vs, read_u32(data, 4), data + 8);
break;
case VNC_MSG_CLIENT_QEMU:
if (len == 1)
return 2;
switch (read_u8(data, 1)) {
case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
if (len == 2)
return 12;
ext_key_event(vs, read_u16(data, 2),
read_u32(data, 4), read_u32(data, 8));
break;
case VNC_MSG_CLIENT_QEMU_AUDIO:
if (len == 2)
return 4;
switch (read_u16 (data, 2)) {
case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
audio_add(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
audio_del(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
if (len == 4)
return 10;
switch (read_u8(data, 4)) {
case 0: vs->as.fmt = AUD_FMT_U8; break;
case 1: vs->as.fmt = AUD_FMT_S8; break;
case 2: vs->as.fmt = AUD_FMT_U16; break;
case 3: vs->as.fmt = AUD_FMT_S16; break;
case 4: vs->as.fmt = AUD_FMT_U32; break;
case 5: vs->as.fmt = AUD_FMT_S32; break;
default:
printf("Invalid audio format %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
vs->as.nchannels = read_u8(data, 5);
if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
printf("Invalid audio channel coount %d\n",
read_u8(data, 5));
vnc_client_error(vs);
break;
}
vs->as.freq = read_u32(data, 6);
break;
default:
printf ("Invalid audio message %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", read_u16(data, 0));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", data[0]);
vnc_client_error(vs);
break;
}
vnc_read_when(vs, protocol_client_msg, 1);
return 0;
}
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
{
char buf[1024];
VncShareMode mode;
int size;
mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
switch (vs->vd->share_policy) {
case VNC_SHARE_POLICY_IGNORE:
/*
* Ignore the shared flag. Nothing to do here.
*
* Doesn't conform to the rfb spec but is traditional qemu
* behavior, thus left here as option for compatibility
* reasons.
*/
break;
case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
/*
* Policy: Allow clients ask for exclusive access.
*
* Implementation: When a client asks for exclusive access,
* disconnect all others. Shared connects are allowed as long
* as no exclusive connection exists.
*
* This is how the rfb spec suggests to handle the shared flag.
*/
if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
VncState *client;
QTAILQ_FOREACH(client, &vs->vd->clients, next) {
if (vs == client) {
continue;
}
if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
client->share_mode != VNC_SHARE_MODE_SHARED) {
continue;
}
vnc_disconnect_start(client);
}
}
if (mode == VNC_SHARE_MODE_SHARED) {
if (vs->vd->num_exclusive > 0) {
vnc_disconnect_start(vs);
return 0;
}
}
break;
case VNC_SHARE_POLICY_FORCE_SHARED:
/*
* Policy: Shared connects only.
* Implementation: Disallow clients asking for exclusive access.
*
* Useful for shared desktop sessions where you don't want
* someone forgetting to say -shared when running the vnc
* client disconnect everybody else.
*/
if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
vnc_disconnect_start(vs);
return 0;
}
break;
}
vnc_set_share_mode(vs, mode);
vs->client_width = surface_width(vs->vd->ds);
vs->client_height = surface_height(vs->vd->ds);
vnc_write_u16(vs, vs->client_width);
vnc_write_u16(vs, vs->client_height);
pixel_format_message(vs);
if (qemu_name)
size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
else
size = snprintf(buf, sizeof(buf), "QEMU");
vnc_write_u32(vs, size);
vnc_write(vs, buf, size);
vnc_flush(vs);
vnc_client_cache_auth(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
vnc_read_when(vs, protocol_client_msg, 1);
return 0;
}
void start_client_init(VncState *vs)
{
vnc_read_when(vs, protocol_client_init, 1);
}
static void make_challenge(VncState *vs)
{
int i;
srand(time(NULL)+getpid()+getpid()*987654+rand());
for (i = 0 ; i < sizeof(vs->challenge) ; i++)
vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
}
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
{
unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
int i, j, pwlen;
unsigned char key[8];
time_t now = time(NULL);
if (!vs->vd->password) {
VNC_DEBUG("No password configured on server");
goto reject;
}
if (vs->vd->expires < now) {
VNC_DEBUG("Password is expired");
goto reject;
}
memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
/* Calculate the expected challenge response */
pwlen = strlen(vs->vd->password);
for (i=0; i<sizeof(key); i++)
key[i] = i<pwlen ? vs->vd->password[i] : 0;
deskey(key, EN0);
for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
des(response+j, response+j);
/* Compare expected vs actual challenge response */
if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
VNC_DEBUG("Client challenge response did not match\n");
goto reject;
} else {
VNC_DEBUG("Accepting VNC challenge response\n");
vnc_write_u32(vs, 0); /* Accept auth */
vnc_flush(vs);
start_client_init(vs);
}
return 0;
reject:
vnc_write_u32(vs, 1); /* Reject auth */
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_flush(vs);
vnc_client_error(vs);
return 0;
}
void start_auth_vnc(VncState *vs)
{
make_challenge(vs);
/* Send client a 'random' challenge */
vnc_write(vs, vs->challenge, sizeof(vs->challenge));
vnc_flush(vs);
vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
}
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
{
/* We only advertise 1 auth scheme at a time, so client
* must pick the one we sent. Verify this */
if (data[0] != vs->auth) { /* Reject auth */
VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
vnc_write_u32(vs, 1);
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_client_error(vs);
} else { /* Accept requested auth */
VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
switch (vs->auth) {
case VNC_AUTH_NONE:
VNC_DEBUG("Accept auth none\n");
if (vs->minor >= 8) {
vnc_write_u32(vs, 0); /* Accept auth completion */
vnc_flush(vs);
}
start_client_init(vs);
break;
case VNC_AUTH_VNC:
VNC_DEBUG("Start VNC auth\n");
start_auth_vnc(vs);
break;
#ifdef CONFIG_VNC_TLS
case VNC_AUTH_VENCRYPT:
VNC_DEBUG("Accept VeNCrypt auth\n");
start_auth_vencrypt(vs);
break;
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
case VNC_AUTH_SASL:
VNC_DEBUG("Accept SASL auth\n");
start_auth_sasl(vs);
break;
#endif /* CONFIG_VNC_SASL */
default: /* Should not be possible, but just in case */
VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
vnc_write_u8(vs, 1);
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_client_error(vs);
}
}
return 0;
}
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
{
char local[13];
memcpy(local, version, 12);
local[12] = 0;
if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
VNC_DEBUG("Malformed protocol version %s\n", local);
vnc_client_error(vs);
return 0;
}
VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
if (vs->major != 3 ||
(vs->minor != 3 &&
vs->minor != 4 &&
vs->minor != 5 &&
vs->minor != 7 &&
vs->minor != 8)) {
VNC_DEBUG("Unsupported client version\n");
vnc_write_u32(vs, VNC_AUTH_INVALID);
vnc_flush(vs);
vnc_client_error(vs);
return 0;
}
/* Some broken clients report v3.4 or v3.5, which spec requires to be treated
* as equivalent to v3.3 by servers
*/
if (vs->minor == 4 || vs->minor == 5)
vs->minor = 3;
if (vs->minor == 3) {
if (vs->auth == VNC_AUTH_NONE) {
VNC_DEBUG("Tell client auth none\n");
vnc_write_u32(vs, vs->auth);
vnc_flush(vs);
start_client_init(vs);
} else if (vs->auth == VNC_AUTH_VNC) {
VNC_DEBUG("Tell client VNC auth\n");
vnc_write_u32(vs, vs->auth);
vnc_flush(vs);
start_auth_vnc(vs);
} else {
VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
vnc_write_u32(vs, VNC_AUTH_INVALID);
vnc_flush(vs);
vnc_client_error(vs);
}
} else {
VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
vnc_write_u8(vs, 1); /* num auth */
vnc_write_u8(vs, vs->auth);
vnc_read_when(vs, protocol_client_auth, 1);
vnc_flush(vs);
}
return 0;
}
static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
{
struct VncSurface *vs = &vd->guest;
return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
}
void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
{
int i, j;
w = (x + w) / VNC_STAT_RECT;
h = (y + h) / VNC_STAT_RECT;
x /= VNC_STAT_RECT;
y /= VNC_STAT_RECT;
for (j = y; j <= h; j++) {
for (i = x; i <= w; i++) {
vs->lossy_rect[j][i] = 1;
}
}
}
static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
{
VncState *vs;
int sty = y / VNC_STAT_RECT;
int stx = x / VNC_STAT_RECT;
int has_dirty = 0;
y = y / VNC_STAT_RECT * VNC_STAT_RECT;
x = x / VNC_STAT_RECT * VNC_STAT_RECT;
QTAILQ_FOREACH(vs, &vd->clients, next) {
int j;
/* kernel send buffers are full -> refresh later */
if (vs->output.offset) {
continue;
}
if (!vs->lossy_rect[sty][stx]) {
continue;
}
vs->lossy_rect[sty][stx] = 0;
for (j = 0; j < VNC_STAT_RECT; ++j) {
bitmap_set(vs->dirty[y + j],
x / VNC_DIRTY_PIXELS_PER_BIT,
VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
}
has_dirty++;
}
return has_dirty;
}
static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
{
int width = pixman_image_get_width(vd->guest.fb);
int height = pixman_image_get_height(vd->guest.fb);
int x, y;
struct timeval res;
int has_dirty = 0;
for (y = 0; y < height; y += VNC_STAT_RECT) {
for (x = 0; x < width; x += VNC_STAT_RECT) {
VncRectStat *rect = vnc_stat_rect(vd, x, y);
rect->updated = false;
}
}
qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
if (timercmp(&vd->guest.last_freq_check, &res, >)) {
return has_dirty;
}
vd->guest.last_freq_check = *tv;
for (y = 0; y < height; y += VNC_STAT_RECT) {
for (x = 0; x < width; x += VNC_STAT_RECT) {
VncRectStat *rect= vnc_stat_rect(vd, x, y);
int count = ARRAY_SIZE(rect->times);
struct timeval min, max;
if (!timerisset(&rect->times[count - 1])) {
continue ;
}
max = rect->times[(rect->idx + count - 1) % count];
qemu_timersub(tv, &max, &res);
if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
rect->freq = 0;
has_dirty += vnc_refresh_lossy_rect(vd, x, y);
memset(rect->times, 0, sizeof (rect->times));
continue ;
}
min = rect->times[rect->idx];
max = rect->times[(rect->idx + count - 1) % count];
qemu_timersub(&max, &min, &res);
rect->freq = res.tv_sec + res.tv_usec / 1000000.;
rect->freq /= count;
rect->freq = 1. / rect->freq;
}
}
return has_dirty;
}
double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
{
int i, j;
double total = 0;
int num = 0;
x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
for (j = y; j <= y + h; j += VNC_STAT_RECT) {
for (i = x; i <= x + w; i += VNC_STAT_RECT) {
total += vnc_stat_rect(vs->vd, i, j)->freq;
num++;
}
}
if (num) {
return total / num;
} else {
return 0;
}
}
static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
{
VncRectStat *rect;
rect = vnc_stat_rect(vd, x, y);
if (rect->updated) {
return ;
}
rect->times[rect->idx] = *tv;
rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
rect->updated = true;
}
static int vnc_refresh_server_surface(VncDisplay *vd)
{
int width = pixman_image_get_width(vd->guest.fb);
int height = pixman_image_get_height(vd->guest.fb);
int y;
uint8_t *guest_row0 = NULL, *server_row0;
int guest_stride = 0, server_stride;
int cmp_bytes;
VncState *vs;
int has_dirty = 0;
pixman_image_t *tmpbuf = NULL;
struct timeval tv = { 0, 0 };
if (!vd->non_adaptive) {
gettimeofday(&tv, NULL);
has_dirty = vnc_update_stats(vd, &tv);
}
/*
* Walk through the guest dirty map.
* Check and copy modified bits from guest to server surface.
* Update server dirty map.
*/
cmp_bytes = VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES;
if (cmp_bytes > vnc_server_fb_stride(vd)) {
cmp_bytes = vnc_server_fb_stride(vd);
}
if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
int width = pixman_image_get_width(vd->server);
tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
} else {
guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
guest_stride = pixman_image_get_stride(vd->guest.fb);
}
server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
server_stride = pixman_image_get_stride(vd->server);
y = 0;
for (;;) {
int x;
uint8_t *guest_ptr, *server_ptr;
unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
height * VNC_DIRTY_BPL(&vd->guest),
y * VNC_DIRTY_BPL(&vd->guest));
if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
/* no more dirty bits */
break;
}
y = offset / VNC_DIRTY_BPL(&vd->guest);
x = offset % VNC_DIRTY_BPL(&vd->guest);
server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
} else {
guest_ptr = guest_row0 + y * guest_stride;
}
guest_ptr += x * cmp_bytes;
for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
continue;
}
if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0) {
continue;
}
memcpy(server_ptr, guest_ptr, cmp_bytes);
if (!vd->non_adaptive) {
vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
y, &tv);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
set_bit(x, vs->dirty[y]);
}
has_dirty++;
}
y++;
}
qemu_pixman_image_unref(tmpbuf);
return has_dirty;
}
static void vnc_refresh(DisplayChangeListener *dcl)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs, *vn;
int has_dirty, rects = 0;
graphic_hw_update(NULL);
if (vnc_trylock_display(vd)) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
return;
}
has_dirty = vnc_refresh_server_surface(vd);
vnc_unlock_display(vd);
QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
rects += vnc_update_client(vs, has_dirty, false);
/* vs might be free()ed here */
}
if (QTAILQ_EMPTY(&vd->clients)) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
return;
}
if (has_dirty && rects) {
vd->dcl.update_interval /= 2;
if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
}
} else {
vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
}
}
}
static void vnc_connect(VncDisplay *vd, int csock,
bool skipauth, bool websocket)
{
VncState *vs = g_malloc0(sizeof(VncState));
int i;
vs->csock = csock;
if (skipauth) {
vs->auth = VNC_AUTH_NONE;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
#endif
} else {
vs->auth = vd->auth;
#ifdef CONFIG_VNC_TLS
vs->subauth = vd->subauth;
#endif
}
vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
for (i = 0; i < VNC_STAT_ROWS; ++i) {
vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
}
VNC_DEBUG("New client on socket %d\n", csock);
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
qemu_set_nonblock(vs->csock);
#ifdef CONFIG_VNC_WS
if (websocket) {
vs->websocket = 1;
#ifdef CONFIG_VNC_TLS
if (vd->tls.x509cert) {
qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
NULL, vs);
} else
#endif /* CONFIG_VNC_TLS */
{
qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
NULL, vs);
}
} else
#endif /* CONFIG_VNC_WS */
{
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
vnc_client_cache_addr(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
vs->vd = vd;
#ifdef CONFIG_VNC_WS
if (!vs->websocket)
#endif
{
vnc_init_state(vs);
}
}
void vnc_init_state(VncState *vs)
{
vs->initialized = true;
VncDisplay *vd = vs->vd;
vs->last_x = -1;
vs->last_y = -1;
vs->as.freq = 44100;
vs->as.nchannels = 2;
vs->as.fmt = AUD_FMT_S16;
vs->as.endianness = 0;
qemu_mutex_init(&vs->output_mutex);
vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
graphic_hw_update(NULL);
vnc_write(vs, "RFB 003.008\n", 12);
vnc_flush(vs);
vnc_read_when(vs, protocol_version, 12);
reset_keys(vs);
if (vs->vd->lock_key_sync)
vs->led = qemu_add_led_event_handler(kbd_leds, vs);
vs->mouse_mode_notifier.notify = check_pointer_type_change;
qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
/* vs might be free()ed here */
}
static void vnc_listen_read(void *opaque, bool websocket)
{
VncDisplay *vs = opaque;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int csock;
/* Catch-up */
graphic_hw_update(NULL);
#ifdef CONFIG_VNC_WS
if (websocket) {
csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
} else
#endif /* CONFIG_VNC_WS */
{
csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
}
if (csock != -1) {
vnc_connect(vs, csock, false, websocket);
}
}
static void vnc_listen_regular_read(void *opaque)
{
vnc_listen_read(opaque, false);
}
#ifdef CONFIG_VNC_WS
static void vnc_listen_websocket_read(void *opaque)
{
vnc_listen_read(opaque, true);
}
#endif /* CONFIG_VNC_WS */
static const DisplayChangeListenerOps dcl_ops = {
.dpy_name = "vnc",
.dpy_refresh = vnc_refresh,
.dpy_gfx_copy = vnc_dpy_copy,
.dpy_gfx_update = vnc_dpy_update,
.dpy_gfx_switch = vnc_dpy_switch,
.dpy_mouse_set = vnc_mouse_set,
.dpy_cursor_define = vnc_dpy_cursor_define,
};
void vnc_display_init(DisplayState *ds)
{
VncDisplay *vs = g_malloc0(sizeof(*vs));
vnc_display = vs;
vs->lsock = -1;
#ifdef CONFIG_VNC_WS
vs->lwebsock = -1;
#endif
QTAILQ_INIT(&vs->clients);
vs->expires = TIME_MAX;
if (keyboard_layout) {
trace_vnc_key_map_init(keyboard_layout);
vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
} else {
vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
}
if (!vs->kbd_layout)
exit(1);
qemu_mutex_init(&vs->mutex);
vnc_start_worker_thread();
vs->dcl.ops = &dcl_ops;
register_displaychangelistener(&vs->dcl);
}
static void vnc_display_close(DisplayState *ds)
{
VncDisplay *vs = vnc_display;
if (!vs)
return;
g_free(vs->display);
vs->display = NULL;
if (vs->lsock != -1) {
qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
close(vs->lsock);
vs->lsock = -1;
}
#ifdef CONFIG_VNC_WS
g_free(vs->ws_display);
vs->ws_display = NULL;
if (vs->lwebsock != -1) {
qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
close(vs->lwebsock);
vs->lwebsock = -1;
}
#endif /* CONFIG_VNC_WS */
vs->auth = VNC_AUTH_INVALID;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
vs->tls.x509verify = 0;
#endif
}
int vnc_display_password(DisplayState *ds, const char *password)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -EINVAL;
}
if (vs->auth == VNC_AUTH_NONE) {
error_printf_unless_qmp("If you want use passwords please enable "
"password auth using '-vnc ${dpy},password'.");
return -EINVAL;
}
g_free(vs->password);
vs->password = g_strdup(password);
return 0;
}
int vnc_display_pw_expire(DisplayState *ds, time_t expires)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -EINVAL;
}
vs->expires = expires;
return 0;
}
char *vnc_display_local_addr(DisplayState *ds)
{
VncDisplay *vs = vnc_display;
return vnc_socket_local_addr("%s:%s", vs->lsock);
}
void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
{
VncDisplay *vs = vnc_display;
const char *options;
int password = 0;
int reverse = 0;
#ifdef CONFIG_VNC_TLS
int tls = 0, x509 = 0;
#endif
#ifdef CONFIG_VNC_SASL
int sasl = 0;
int saslErr;
#endif
#if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
int acl = 0;
#endif
int lock_key_sync = 1;
if (!vnc_display) {
error_setg(errp, "VNC display not active");
return;
}
vnc_display_close(ds);
if (strcmp(display, "none") == 0)
return;
vs->display = g_strdup(display);
vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
options = display;
while ((options = strchr(options, ','))) {
options++;
if (strncmp(options, "password", 8) == 0) {
if (fips_get_state()) {
error_setg(errp,
"VNC password auth disabled due to FIPS mode, "
"consider using the VeNCrypt or SASL authentication "
"methods as an alternative");
goto fail;
}
password = 1; /* Require password auth */
} else if (strncmp(options, "reverse", 7) == 0) {
reverse = 1;
} else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
lock_key_sync = 0;
#ifdef CONFIG_VNC_SASL
} else if (strncmp(options, "sasl", 4) == 0) {
sasl = 1; /* Require SASL auth */
#endif
#ifdef CONFIG_VNC_WS
} else if (strncmp(options, "websocket", 9) == 0) {
char *start, *end;
vs->websocket = 1;
/* Check for 'websocket=<port>' */
start = strchr(options, '=');
end = strchr(options, ',');
if (start && (!end || (start < end))) {
int len = end ? end-(start+1) : strlen(start+1);
if (len < 6) {
/* extract the host specification from display */
char *host = NULL, *port = NULL, *host_end = NULL;
port = g_strndup(start + 1, len);
/* ipv6 hosts have colons */
end = strchr(display, ',');
host_end = g_strrstr_len(display, end - display, ":");
if (host_end) {
host = g_strndup(display, host_end - display + 1);
} else {
host = g_strndup(":", 1);
}
vs->ws_display = g_strconcat(host, port, NULL);
g_free(host);
g_free(port);
}
}
#endif /* CONFIG_VNC_WS */
#ifdef CONFIG_VNC_TLS
} else if (strncmp(options, "tls", 3) == 0) {
tls = 1; /* Require TLS */
} else if (strncmp(options, "x509", 4) == 0) {
char *start, *end;
x509 = 1; /* Require x509 certificates */
if (strncmp(options, "x509verify", 10) == 0)
vs->tls.x509verify = 1; /* ...and verify client certs */
/* Now check for 'x509=/some/path' postfix
* and use that to setup x509 certificate/key paths */
start = strchr(options, '=');
end = strchr(options, ',');
if (start && (!end || (start < end))) {
int len = end ? end-(start+1) : strlen(start+1);
char *path = g_strndup(start + 1, len);
VNC_DEBUG("Trying certificate path '%s'\n", path);
if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
error_setg(errp, "Failed to find x509 certificates/keys in %s", path);
g_free(path);
goto fail;
}
g_free(path);
} else {
error_setg(errp, "No certificate path provided");
goto fail;
}
#endif
#if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
} else if (strncmp(options, "acl", 3) == 0) {
acl = 1;
#endif
} else if (strncmp(options, "lossy", 5) == 0) {
#ifdef CONFIG_VNC_JPEG
vs->lossy = true;
#endif
} else if (strncmp(options, "non-adaptive", 12) == 0) {
vs->non_adaptive = true;
} else if (strncmp(options, "share=", 6) == 0) {
if (strncmp(options+6, "ignore", 6) == 0) {
vs->share_policy = VNC_SHARE_POLICY_IGNORE;
} else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
} else if (strncmp(options+6, "force-shared", 12) == 0) {
vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
} else {
error_setg(errp, "unknown vnc share= option");
goto fail;
}
}
}
/* adaptive updates are only used with tight encoding and
* if lossy updates are enabled so we can disable all the
* calculations otherwise */
if (!vs->lossy) {
vs->non_adaptive = true;
}
#ifdef CONFIG_VNC_TLS
if (acl && x509 && vs->tls.x509verify) {
if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
fprintf(stderr, "Failed to create x509 dname ACL\n");
exit(1);
}
}
#endif
#ifdef CONFIG_VNC_SASL
if (acl && sasl) {
if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
fprintf(stderr, "Failed to create username ACL\n");
exit(1);
}
}
#endif
/*
* Combinations we support here:
*
* - no-auth (clear text, no auth)
* - password (clear text, weak auth)
* - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
* - tls (encrypt, weak anonymous creds, no auth)
* - tls + password (encrypt, weak anonymous creds, weak auth)
* - tls + sasl (encrypt, weak anonymous creds, good auth)
* - tls + x509 (encrypt, good x509 creds, no auth)
* - tls + x509 + password (encrypt, good x509 creds, weak auth)
* - tls + x509 + sasl (encrypt, good x509 creds, good auth)
*
* NB1. TLS is a stackable auth scheme.
* NB2. the x509 schemes have option to validate a client cert dname
*/
if (password) {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 password auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
} else {
VNC_DEBUG("Initializing VNC server with TLS password auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
}
} else {
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Initializing VNC server with password auth\n");
vs->auth = VNC_AUTH_VNC;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
} else if (sasl) {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
} else {
VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
}
} else {
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Initializing VNC server with SASL auth\n");
vs->auth = VNC_AUTH_SASL;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif /* CONFIG_VNC_TLS */
#endif /* CONFIG_VNC_SASL */
} else {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 no auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
} else {
VNC_DEBUG("Initializing VNC server with TLS no auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
}
} else {
#endif
VNC_DEBUG("Initializing VNC server with no auth\n");
vs->auth = VNC_AUTH_NONE;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif
}
#ifdef CONFIG_VNC_SASL
if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
error_setg(errp, "Failed to initialize SASL auth: %s",
sasl_errstring(saslErr, NULL, NULL));
goto fail;
}
#endif
vs->lock_key_sync = lock_key_sync;
if (reverse) {
/* connect to viewer */
int csock;
vs->lsock = -1;
#ifdef CONFIG_VNC_WS
vs->lwebsock = -1;
#endif
if (strncmp(display, "unix:", 5) == 0) {
csock = unix_connect(display+5, errp);
} else {
csock = inet_connect(display, errp);
}
if (csock < 0) {
goto fail;
}
vnc_connect(vs, csock, false, false);
} else {
/* listen for connects */
char *dpy;
dpy = g_malloc(256);
if (strncmp(display, "unix:", 5) == 0) {
pstrcpy(dpy, 256, "unix:");
vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
} else {
vs->lsock = inet_listen(display, dpy, 256,
SOCK_STREAM, 5900, errp);
if (vs->lsock < 0) {
g_free(dpy);
goto fail;
}
#ifdef CONFIG_VNC_WS
if (vs->websocket) {
if (vs->ws_display) {
vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
SOCK_STREAM, 0, errp);
} else {
vs->lwebsock = inet_listen(vs->display, NULL, 256,
SOCK_STREAM, 5700, errp);
}
if (vs->lwebsock < 0) {
if (vs->lsock) {
close(vs->lsock);
vs->lsock = -1;
}
g_free(dpy);
goto fail;
}
}
#endif /* CONFIG_VNC_WS */
}
g_free(vs->display);
vs->display = dpy;
qemu_set_fd_handler2(vs->lsock, NULL,
vnc_listen_regular_read, NULL, vs);
#ifdef CONFIG_VNC_WS
if (vs->websocket) {
qemu_set_fd_handler2(vs->lwebsock, NULL,
vnc_listen_websocket_read, NULL, vs);
}
#endif /* CONFIG_VNC_WS */
}
return;
fail:
g_free(vs->display);
vs->display = NULL;
#ifdef CONFIG_VNC_WS
g_free(vs->ws_display);
vs->ws_display = NULL;
#endif /* CONFIG_VNC_WS */
}
void vnc_display_add_client(DisplayState *ds, int csock, bool skipauth)
{
VncDisplay *vs = vnc_display;
vnc_connect(vs, csock, skipauth, false);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_1665_0 |
crossvul-cpp_data_bad_2670_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
* IEEE and TIA extensions by Carles Kishimoto <carles.kishimoto@gmail.com>
* DCBX extensions by Kaladhar Musunuru <kaladharm@sourceforge.net>
*/
/* \summary: IEEE 802.1ab Link Layer Discovery Protocol (LLDP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "af.h"
#include "oui.h"
#define LLDP_EXTRACT_TYPE(x) (((x)&0xfe00)>>9)
#define LLDP_EXTRACT_LEN(x) ((x)&0x01ff)
/*
* TLV type codes
*/
#define LLDP_END_TLV 0
#define LLDP_CHASSIS_ID_TLV 1
#define LLDP_PORT_ID_TLV 2
#define LLDP_TTL_TLV 3
#define LLDP_PORT_DESCR_TLV 4
#define LLDP_SYSTEM_NAME_TLV 5
#define LLDP_SYSTEM_DESCR_TLV 6
#define LLDP_SYSTEM_CAP_TLV 7
#define LLDP_MGMT_ADDR_TLV 8
#define LLDP_PRIVATE_TLV 127
static const struct tok lldp_tlv_values[] = {
{ LLDP_END_TLV, "End" },
{ LLDP_CHASSIS_ID_TLV, "Chassis ID" },
{ LLDP_PORT_ID_TLV, "Port ID" },
{ LLDP_TTL_TLV, "Time to Live" },
{ LLDP_PORT_DESCR_TLV, "Port Description" },
{ LLDP_SYSTEM_NAME_TLV, "System Name" },
{ LLDP_SYSTEM_DESCR_TLV, "System Description" },
{ LLDP_SYSTEM_CAP_TLV, "System Capabilities" },
{ LLDP_MGMT_ADDR_TLV, "Management Address" },
{ LLDP_PRIVATE_TLV, "Organization specific" },
{ 0, NULL}
};
/*
* Chassis ID subtypes
*/
#define LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE 1
#define LLDP_CHASSIS_INTF_ALIAS_SUBTYPE 2
#define LLDP_CHASSIS_PORT_COMP_SUBTYPE 3
#define LLDP_CHASSIS_MAC_ADDR_SUBTYPE 4
#define LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE 5
#define LLDP_CHASSIS_INTF_NAME_SUBTYPE 6
#define LLDP_CHASSIS_LOCAL_SUBTYPE 7
static const struct tok lldp_chassis_subtype_values[] = {
{ LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE, "Chassis component"},
{ LLDP_CHASSIS_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_CHASSIS_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_CHASSIS_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE, "Network address"},
{ LLDP_CHASSIS_INTF_NAME_SUBTYPE, "Interface name"},
{ LLDP_CHASSIS_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* Port ID subtypes
*/
#define LLDP_PORT_INTF_ALIAS_SUBTYPE 1
#define LLDP_PORT_PORT_COMP_SUBTYPE 2
#define LLDP_PORT_MAC_ADDR_SUBTYPE 3
#define LLDP_PORT_NETWORK_ADDR_SUBTYPE 4
#define LLDP_PORT_INTF_NAME_SUBTYPE 5
#define LLDP_PORT_AGENT_CIRC_ID_SUBTYPE 6
#define LLDP_PORT_LOCAL_SUBTYPE 7
static const struct tok lldp_port_subtype_values[] = {
{ LLDP_PORT_INTF_ALIAS_SUBTYPE, "Interface alias"},
{ LLDP_PORT_PORT_COMP_SUBTYPE, "Port component"},
{ LLDP_PORT_MAC_ADDR_SUBTYPE, "MAC address"},
{ LLDP_PORT_NETWORK_ADDR_SUBTYPE, "Network Address"},
{ LLDP_PORT_INTF_NAME_SUBTYPE, "Interface Name"},
{ LLDP_PORT_AGENT_CIRC_ID_SUBTYPE, "Agent circuit ID"},
{ LLDP_PORT_LOCAL_SUBTYPE, "Local"},
{ 0, NULL}
};
/*
* System Capabilities
*/
#define LLDP_CAP_OTHER (1 << 0)
#define LLDP_CAP_REPEATER (1 << 1)
#define LLDP_CAP_BRIDGE (1 << 2)
#define LLDP_CAP_WLAN_AP (1 << 3)
#define LLDP_CAP_ROUTER (1 << 4)
#define LLDP_CAP_PHONE (1 << 5)
#define LLDP_CAP_DOCSIS (1 << 6)
#define LLDP_CAP_STATION_ONLY (1 << 7)
static const struct tok lldp_cap_values[] = {
{ LLDP_CAP_OTHER, "Other"},
{ LLDP_CAP_REPEATER, "Repeater"},
{ LLDP_CAP_BRIDGE, "Bridge"},
{ LLDP_CAP_WLAN_AP, "WLAN AP"},
{ LLDP_CAP_ROUTER, "Router"},
{ LLDP_CAP_PHONE, "Telephone"},
{ LLDP_CAP_DOCSIS, "Docsis"},
{ LLDP_CAP_STATION_ONLY, "Station Only"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID 1
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID 2
#define LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME 3
#define LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY 4
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION 8
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION 9
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION 10
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION 11
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY 12
#define LLDP_PRIVATE_8021_SUBTYPE_EVB 13
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP 14
static const struct tok lldp_8021_subtype_values[] = {
{ LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID, "Port VLAN Id"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID, "Port and Protocol VLAN ID"},
{ LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME, "VLAN name"},
{ LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY, "Protocol Identity"},
{ LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION, "Congestion Notification"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION, "ETS Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION, "ETS Recommendation"},
{ LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION, "Priority Flow Control Configuration"},
{ LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY, "Application Priority"},
{ LLDP_PRIVATE_8021_SUBTYPE_EVB, "EVB"},
{ LLDP_PRIVATE_8021_SUBTYPE_CDCP,"CDCP"},
{ 0, NULL}
};
#define LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT (1 << 1)
#define LLDP_8021_PORT_PROTOCOL_VLAN_STATUS (1 << 2)
static const struct tok lldp_8021_port_protocol_id_values[] = {
{ LLDP_8021_PORT_PROTOCOL_VLAN_SUPPORT, "supported"},
{ LLDP_8021_PORT_PROTOCOL_VLAN_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_PRIVATE_8023_SUBTYPE_MACPHY 1
#define LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER 2
#define LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR 3
#define LLDP_PRIVATE_8023_SUBTYPE_MTU 4
static const struct tok lldp_8023_subtype_values[] = {
{ LLDP_PRIVATE_8023_SUBTYPE_MACPHY, "MAC/PHY configuration/status"},
{ LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER, "Power via MDI"},
{ LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR, "Link aggregation"},
{ LLDP_PRIVATE_8023_SUBTYPE_MTU, "Max frame size"},
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES 1
#define LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY 2
#define LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID 3
#define LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI 4
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV 5
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV 6
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV 7
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER 8
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME 9
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME 10
#define LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID 11
static const struct tok lldp_tia_subtype_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES, "LLDP-MED Capabilities" },
{ LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY, "Network policy" },
{ LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID, "Location identification" },
{ LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI, "Extended power-via-MDI" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Inventory - hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Inventory - firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Inventory - software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Inventory - serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Inventory - manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Inventory - model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Inventory - asset ID" },
{ 0, NULL}
};
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS 1
#define LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS 2
static const struct tok lldp_tia_location_altitude_type_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_METERS, "meters"},
{ LLDP_PRIVATE_TIA_LOCATION_ALTITUDE_FLOORS, "floors"},
{ 0, NULL}
};
/* ANSI/TIA-1057 - Annex B */
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1 1
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2 2
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3 3
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4 4
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5 5
#define LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6 6
static const struct tok lldp_tia_location_lci_catype_values[] = {
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A1, "national subdivisions (state,canton,region,province,prefecture)"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A2, "county, parish, gun, district"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A3, "city, township, shi"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A4, "city division, borough, city district, ward chou"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A5, "neighborhood, block"},
{ LLDP_PRIVATE_TIA_LOCATION_LCI_CATYPE_A6, "street"},
{ 0, NULL}
};
static const struct tok lldp_tia_location_lci_what_values[] = {
{ 0, "location of DHCP server"},
{ 1, "location of the network element believed to be closest to the client"},
{ 2, "location of the client"},
{ 0, NULL}
};
/*
* From RFC 3636 - dot3MauType
*/
#define LLDP_MAU_TYPE_UNKNOWN 0
#define LLDP_MAU_TYPE_AUI 1
#define LLDP_MAU_TYPE_10BASE_5 2
#define LLDP_MAU_TYPE_FOIRL 3
#define LLDP_MAU_TYPE_10BASE_2 4
#define LLDP_MAU_TYPE_10BASE_T 5
#define LLDP_MAU_TYPE_10BASE_FP 6
#define LLDP_MAU_TYPE_10BASE_FB 7
#define LLDP_MAU_TYPE_10BASE_FL 8
#define LLDP_MAU_TYPE_10BROAD36 9
#define LLDP_MAU_TYPE_10BASE_T_HD 10
#define LLDP_MAU_TYPE_10BASE_T_FD 11
#define LLDP_MAU_TYPE_10BASE_FL_HD 12
#define LLDP_MAU_TYPE_10BASE_FL_FD 13
#define LLDP_MAU_TYPE_100BASE_T4 14
#define LLDP_MAU_TYPE_100BASE_TX_HD 15
#define LLDP_MAU_TYPE_100BASE_TX_FD 16
#define LLDP_MAU_TYPE_100BASE_FX_HD 17
#define LLDP_MAU_TYPE_100BASE_FX_FD 18
#define LLDP_MAU_TYPE_100BASE_T2_HD 19
#define LLDP_MAU_TYPE_100BASE_T2_FD 20
#define LLDP_MAU_TYPE_1000BASE_X_HD 21
#define LLDP_MAU_TYPE_1000BASE_X_FD 22
#define LLDP_MAU_TYPE_1000BASE_LX_HD 23
#define LLDP_MAU_TYPE_1000BASE_LX_FD 24
#define LLDP_MAU_TYPE_1000BASE_SX_HD 25
#define LLDP_MAU_TYPE_1000BASE_SX_FD 26
#define LLDP_MAU_TYPE_1000BASE_CX_HD 27
#define LLDP_MAU_TYPE_1000BASE_CX_FD 28
#define LLDP_MAU_TYPE_1000BASE_T_HD 29
#define LLDP_MAU_TYPE_1000BASE_T_FD 30
#define LLDP_MAU_TYPE_10GBASE_X 31
#define LLDP_MAU_TYPE_10GBASE_LX4 32
#define LLDP_MAU_TYPE_10GBASE_R 33
#define LLDP_MAU_TYPE_10GBASE_ER 34
#define LLDP_MAU_TYPE_10GBASE_LR 35
#define LLDP_MAU_TYPE_10GBASE_SR 36
#define LLDP_MAU_TYPE_10GBASE_W 37
#define LLDP_MAU_TYPE_10GBASE_EW 38
#define LLDP_MAU_TYPE_10GBASE_LW 39
#define LLDP_MAU_TYPE_10GBASE_SW 40
static const struct tok lldp_mau_types_values[] = {
{ LLDP_MAU_TYPE_UNKNOWN, "Unknown"},
{ LLDP_MAU_TYPE_AUI, "AUI"},
{ LLDP_MAU_TYPE_10BASE_5, "10BASE_5"},
{ LLDP_MAU_TYPE_FOIRL, "FOIRL"},
{ LLDP_MAU_TYPE_10BASE_2, "10BASE2"},
{ LLDP_MAU_TYPE_10BASE_T, "10BASET duplex mode unknown"},
{ LLDP_MAU_TYPE_10BASE_FP, "10BASEFP"},
{ LLDP_MAU_TYPE_10BASE_FB, "10BASEFB"},
{ LLDP_MAU_TYPE_10BASE_FL, "10BASEFL duplex mode unknown"},
{ LLDP_MAU_TYPE_10BROAD36, "10BROAD36"},
{ LLDP_MAU_TYPE_10BASE_T_HD, "10BASET hdx"},
{ LLDP_MAU_TYPE_10BASE_T_FD, "10BASET fdx"},
{ LLDP_MAU_TYPE_10BASE_FL_HD, "10BASEFL hdx"},
{ LLDP_MAU_TYPE_10BASE_FL_FD, "10BASEFL fdx"},
{ LLDP_MAU_TYPE_100BASE_T4, "100BASET4"},
{ LLDP_MAU_TYPE_100BASE_TX_HD, "100BASETX hdx"},
{ LLDP_MAU_TYPE_100BASE_TX_FD, "100BASETX fdx"},
{ LLDP_MAU_TYPE_100BASE_FX_HD, "100BASEFX hdx"},
{ LLDP_MAU_TYPE_100BASE_FX_FD, "100BASEFX fdx"},
{ LLDP_MAU_TYPE_100BASE_T2_HD, "100BASET2 hdx"},
{ LLDP_MAU_TYPE_100BASE_T2_FD, "100BASET2 fdx"},
{ LLDP_MAU_TYPE_1000BASE_X_HD, "1000BASEX hdx"},
{ LLDP_MAU_TYPE_1000BASE_X_FD, "1000BASEX fdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_HD, "1000BASELX hdx"},
{ LLDP_MAU_TYPE_1000BASE_LX_FD, "1000BASELX fdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_HD, "1000BASESX hdx"},
{ LLDP_MAU_TYPE_1000BASE_SX_FD, "1000BASESX fdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_HD, "1000BASECX hdx"},
{ LLDP_MAU_TYPE_1000BASE_CX_FD, "1000BASECX fdx"},
{ LLDP_MAU_TYPE_1000BASE_T_HD, "1000BASET hdx"},
{ LLDP_MAU_TYPE_1000BASE_T_FD, "1000BASET fdx"},
{ LLDP_MAU_TYPE_10GBASE_X, "10GBASEX"},
{ LLDP_MAU_TYPE_10GBASE_LX4, "10GBASELX4"},
{ LLDP_MAU_TYPE_10GBASE_R, "10GBASER"},
{ LLDP_MAU_TYPE_10GBASE_ER, "10GBASEER"},
{ LLDP_MAU_TYPE_10GBASE_LR, "10GBASELR"},
{ LLDP_MAU_TYPE_10GBASE_SR, "10GBASESR"},
{ LLDP_MAU_TYPE_10GBASE_W, "10GBASEW"},
{ LLDP_MAU_TYPE_10GBASE_EW, "10GBASEEW"},
{ LLDP_MAU_TYPE_10GBASE_LW, "10GBASELW"},
{ LLDP_MAU_TYPE_10GBASE_SW, "10GBASESW"},
{ 0, NULL}
};
#define LLDP_8023_AUTONEGOTIATION_SUPPORT (1 << 0)
#define LLDP_8023_AUTONEGOTIATION_STATUS (1 << 1)
static const struct tok lldp_8023_autonegotiation_values[] = {
{ LLDP_8023_AUTONEGOTIATION_SUPPORT, "supported"},
{ LLDP_8023_AUTONEGOTIATION_STATUS, "enabled"},
{ 0, NULL}
};
#define LLDP_TIA_CAPABILITY_MED (1 << 0)
#define LLDP_TIA_CAPABILITY_NETWORK_POLICY (1 << 1)
#define LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION (1 << 2)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE (1 << 3)
#define LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD (1 << 4)
#define LLDP_TIA_CAPABILITY_INVENTORY (1 << 5)
static const struct tok lldp_tia_capabilities_values[] = {
{ LLDP_TIA_CAPABILITY_MED, "LLDP-MED capabilities"},
{ LLDP_TIA_CAPABILITY_NETWORK_POLICY, "network policy"},
{ LLDP_TIA_CAPABILITY_LOCATION_IDENTIFICATION, "location identification"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PSE, "extended power via MDI-PSE"},
{ LLDP_TIA_CAPABILITY_EXTENDED_POWER_MDI_PD, "extended power via MDI-PD"},
{ LLDP_TIA_CAPABILITY_INVENTORY, "Inventory"},
{ 0, NULL}
};
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1 1
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2 2
#define LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3 3
#define LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY 4
static const struct tok lldp_tia_device_type_values[] = {
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_1, "endpoint class 1"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_2, "endpoint class 2"},
{ LLDP_TIA_DEVICE_TYPE_ENDPOINT_CLASS_3, "endpoint class 3"},
{ LLDP_TIA_DEVICE_TYPE_NETWORK_CONNECTIVITY, "network connectivity"},
{ 0, NULL}
};
#define LLDP_TIA_APPLICATION_TYPE_VOICE 1
#define LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING 2
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE 3
#define LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING 4
#define LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE 5
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING 6
#define LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO 7
#define LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING 8
static const struct tok lldp_tia_application_type_values[] = {
{ LLDP_TIA_APPLICATION_TYPE_VOICE, "voice"},
{ LLDP_TIA_APPLICATION_TYPE_VOICE_SIGNALING, "voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE, "guest voice"},
{ LLDP_TIA_APPLICATION_TYPE_GUEST_VOICE_SIGNALING, "guest voice signaling"},
{ LLDP_TIA_APPLICATION_TYPE_SOFTPHONE_VOICE, "softphone voice"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_CONFERENCING, "video conferencing"},
{ LLDP_TIA_APPLICATION_TYPE_STREAMING_VIDEO, "streaming video"},
{ LLDP_TIA_APPLICATION_TYPE_VIDEO_SIGNALING, "video signaling"},
{ 0, NULL}
};
#define LLDP_TIA_NETWORK_POLICY_X_BIT (1 << 5)
#define LLDP_TIA_NETWORK_POLICY_T_BIT (1 << 6)
#define LLDP_TIA_NETWORK_POLICY_U_BIT (1 << 7)
static const struct tok lldp_tia_network_policy_bits_values[] = {
{ LLDP_TIA_NETWORK_POLICY_U_BIT, "Unknown"},
{ LLDP_TIA_NETWORK_POLICY_T_BIT, "Tagged"},
{ LLDP_TIA_NETWORK_POLICY_X_BIT, "reserved"},
{ 0, NULL}
};
#define LLDP_EXTRACT_NETWORK_POLICY_VLAN(x) (((x)&0x1ffe)>>1)
#define LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(x) (((x)&0x01ff)>>6)
#define LLDP_EXTRACT_NETWORK_POLICY_DSCP(x) ((x)&0x003f)
#define LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED 1
#define LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS 2
#define LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN 3
static const struct tok lldp_tia_location_data_format_values[] = {
{ LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED, "coordinate-based LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS, "civic address LCI"},
{ LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN, "ECS ELIN"},
{ 0, NULL}
};
#define LLDP_TIA_LOCATION_DATUM_WGS_84 1
#define LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88 2
#define LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW 3
static const struct tok lldp_tia_location_datum_type_values[] = {
{ LLDP_TIA_LOCATION_DATUM_WGS_84, "World Geodesic System 1984"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_NAVD_88, "North American Datum 1983 (NAVD88)"},
{ LLDP_TIA_LOCATION_DATUM_NAD_83_MLLW, "North American Datum 1983 (MLLW)"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_SOURCE_PSE 1
#define LLDP_TIA_POWER_SOURCE_LOCAL 2
#define LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL 3
static const struct tok lldp_tia_power_source_values[] = {
{ LLDP_TIA_POWER_SOURCE_PSE, "PSE - primary power source"},
{ LLDP_TIA_POWER_SOURCE_LOCAL, "local - backup power source"},
{ LLDP_TIA_POWER_SOURCE_PSE_AND_LOCAL, "PSE+local - reserved"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_PRIORITY_CRITICAL 1
#define LLDP_TIA_POWER_PRIORITY_HIGH 2
#define LLDP_TIA_POWER_PRIORITY_LOW 3
static const struct tok lldp_tia_power_priority_values[] = {
{ LLDP_TIA_POWER_PRIORITY_CRITICAL, "critical"},
{ LLDP_TIA_POWER_PRIORITY_HIGH, "high"},
{ LLDP_TIA_POWER_PRIORITY_LOW, "low"},
{ 0, NULL}
};
#define LLDP_TIA_POWER_VAL_MAX 1024
static const struct tok lldp_tia_inventory_values[] = {
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV, "Hardware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV, "Firmware revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV, "Software revision" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER, "Serial number" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME, "Manufacturer name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME, "Model name" },
{ LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID, "Asset ID" },
{ 0, NULL}
};
/*
* From RFC 3636 - ifMauAutoNegCapAdvertisedBits
*/
#define LLDP_MAU_PMD_OTHER (1 << 15)
#define LLDP_MAU_PMD_10BASE_T (1 << 14)
#define LLDP_MAU_PMD_10BASE_T_FD (1 << 13)
#define LLDP_MAU_PMD_100BASE_T4 (1 << 12)
#define LLDP_MAU_PMD_100BASE_TX (1 << 11)
#define LLDP_MAU_PMD_100BASE_TX_FD (1 << 10)
#define LLDP_MAU_PMD_100BASE_T2 (1 << 9)
#define LLDP_MAU_PMD_100BASE_T2_FD (1 << 8)
#define LLDP_MAU_PMD_FDXPAUSE (1 << 7)
#define LLDP_MAU_PMD_FDXAPAUSE (1 << 6)
#define LLDP_MAU_PMD_FDXSPAUSE (1 << 5)
#define LLDP_MAU_PMD_FDXBPAUSE (1 << 4)
#define LLDP_MAU_PMD_1000BASE_X (1 << 3)
#define LLDP_MAU_PMD_1000BASE_X_FD (1 << 2)
#define LLDP_MAU_PMD_1000BASE_T (1 << 1)
#define LLDP_MAU_PMD_1000BASE_T_FD (1 << 0)
static const struct tok lldp_pmd_capability_values[] = {
{ LLDP_MAU_PMD_10BASE_T, "10BASE-T hdx"},
{ LLDP_MAU_PMD_10BASE_T_FD, "10BASE-T fdx"},
{ LLDP_MAU_PMD_100BASE_T4, "100BASE-T4"},
{ LLDP_MAU_PMD_100BASE_TX, "100BASE-TX hdx"},
{ LLDP_MAU_PMD_100BASE_TX_FD, "100BASE-TX fdx"},
{ LLDP_MAU_PMD_100BASE_T2, "100BASE-T2 hdx"},
{ LLDP_MAU_PMD_100BASE_T2_FD, "100BASE-T2 fdx"},
{ LLDP_MAU_PMD_FDXPAUSE, "Pause for fdx links"},
{ LLDP_MAU_PMD_FDXAPAUSE, "Asym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXSPAUSE, "Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_FDXBPAUSE, "Asym and Sym PAUSE for fdx"},
{ LLDP_MAU_PMD_1000BASE_X, "1000BASE-{X LX SX CX} hdx"},
{ LLDP_MAU_PMD_1000BASE_X_FD, "1000BASE-{X LX SX CX} fdx"},
{ LLDP_MAU_PMD_1000BASE_T, "1000BASE-T hdx"},
{ LLDP_MAU_PMD_1000BASE_T_FD, "1000BASE-T fdx"},
{ 0, NULL}
};
#define LLDP_MDI_PORT_CLASS (1 << 0)
#define LLDP_MDI_POWER_SUPPORT (1 << 1)
#define LLDP_MDI_POWER_STATE (1 << 2)
#define LLDP_MDI_PAIR_CONTROL_ABILITY (1 << 3)
static const struct tok lldp_mdi_values[] = {
{ LLDP_MDI_PORT_CLASS, "PSE"},
{ LLDP_MDI_POWER_SUPPORT, "supported"},
{ LLDP_MDI_POWER_STATE, "enabled"},
{ LLDP_MDI_PAIR_CONTROL_ABILITY, "can be controlled"},
{ 0, NULL}
};
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL 1
#define LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE 2
static const struct tok lldp_mdi_power_pairs_values[] = {
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SIGNAL, "signal"},
{ LLDP_MDI_PSE_PORT_POWER_PAIRS_SPARE, "spare"},
{ 0, NULL}
};
#define LLDP_MDI_POWER_CLASS0 1
#define LLDP_MDI_POWER_CLASS1 2
#define LLDP_MDI_POWER_CLASS2 3
#define LLDP_MDI_POWER_CLASS3 4
#define LLDP_MDI_POWER_CLASS4 5
static const struct tok lldp_mdi_power_class_values[] = {
{ LLDP_MDI_POWER_CLASS0, "class0"},
{ LLDP_MDI_POWER_CLASS1, "class1"},
{ LLDP_MDI_POWER_CLASS2, "class2"},
{ LLDP_MDI_POWER_CLASS3, "class3"},
{ LLDP_MDI_POWER_CLASS4, "class4"},
{ 0, NULL}
};
#define LLDP_AGGREGATION_CAPABILTIY (1 << 0)
#define LLDP_AGGREGATION_STATUS (1 << 1)
static const struct tok lldp_aggregation_values[] = {
{ LLDP_AGGREGATION_CAPABILTIY, "supported"},
{ LLDP_AGGREGATION_STATUS, "enabled"},
{ 0, NULL}
};
/*
* DCBX protocol subtypes.
*/
#define LLDP_DCBX_SUBTYPE_1 1
#define LLDP_DCBX_SUBTYPE_2 2
static const struct tok lldp_dcbx_subtype_values[] = {
{ LLDP_DCBX_SUBTYPE_1, "DCB Capability Exchange Protocol Rev 1" },
{ LLDP_DCBX_SUBTYPE_2, "DCB Capability Exchange Protocol Rev 1.01" },
{ 0, NULL}
};
#define LLDP_DCBX_CONTROL_TLV 1
#define LLDP_DCBX_PRIORITY_GROUPS_TLV 2
#define LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV 3
#define LLDP_DCBX_APPLICATION_TLV 4
/*
* Interface numbering subtypes.
*/
#define LLDP_INTF_NUMB_IFX_SUBTYPE 2
#define LLDP_INTF_NUMB_SYSPORT_SUBTYPE 3
static const struct tok lldp_intf_numb_subtype_values[] = {
{ LLDP_INTF_NUMB_IFX_SUBTYPE, "Interface Index" },
{ LLDP_INTF_NUMB_SYSPORT_SUBTYPE, "System Port Number" },
{ 0, NULL}
};
#define LLDP_INTF_NUM_LEN 5
#define LLDP_EVB_MODE_NOT_SUPPORTED 0
#define LLDP_EVB_MODE_EVB_BRIDGE 1
#define LLDP_EVB_MODE_EVB_STATION 2
#define LLDP_EVB_MODE_RESERVED 3
static const struct tok lldp_evb_mode_values[]={
{ LLDP_EVB_MODE_NOT_SUPPORTED, "Not Supported"},
{ LLDP_EVB_MODE_EVB_BRIDGE, "EVB Bridge"},
{ LLDP_EVB_MODE_EVB_STATION, "EVB Staion"},
{ LLDP_EVB_MODE_RESERVED, "Reserved for future Standardization"},
{ 0, NULL},
};
#define NO_OF_BITS 8
#define LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH 25
#define LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH 6
#define LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH 5
#define LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH 9
#define LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH 8
#define LLDP_IANA_SUBTYPE_MUDURL 1
static const struct tok lldp_iana_subtype_values[] = {
{ LLDP_IANA_SUBTYPE_MUDURL, "MUD-URL" },
{ 0, NULL }
};
static void
print_ets_priority_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t Priority Assignment Table"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0]>>4,ptr[0]&0x0f,ptr[1]>>4,ptr[1]&0x0f,ptr[2]>>4,
ptr[2] & 0x0f, ptr[3] >> 4, ptr[3] & 0x0f));
}
static void
print_tc_bandwidth_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TC Bandwidth Table"));
ND_PRINT((ndo, "\n\t TC%% : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
static void
print_tsa_assignment_table(netdissect_options *ndo,
const u_char *ptr)
{
ND_PRINT((ndo, "\n\t TSA Assignment Table"));
ND_PRINT((ndo, "\n\t Traffic Class: 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : %-3d %-3d %-3d %-3d %-3d %-3d %-3d %-3d",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5], ptr[6], ptr[7]));
}
/*
* Print IEEE 802.1 private extensions. (802.1AB annex E)
*/
static int
lldp_private_8021_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
u_int sublen;
u_int tval;
uint8_t i;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8021_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port vlan id (PVID): %u",
EXTRACT_16BITS(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)",
EXTRACT_16BITS(tptr+5),
bittok2str(lldp_8021_port_protocol_id_values, "none", *(tptr+4)),
*(tptr + 4)));
break;
case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME:
if (tlv_len < 6) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan id (VID): %u", EXTRACT_16BITS(tptr + 4)));
if (tlv_len < 7) {
return hexdump;
}
sublen = *(tptr+6);
if (tlv_len < 7+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t vlan name: "));
safeputs(ndo, tptr + 7, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY:
if (tlv_len < 5) {
return hexdump;
}
sublen = *(tptr+4);
if (tlv_len < 5+sublen) {
return hexdump;
}
ND_PRINT((ndo, "\n\t protocol identity: "));
safeputs(ndo, tptr + 5, sublen);
break;
case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Pre-Priority CNPV Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Pre-Priority Ready Indicator"));
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing:%d, CBS:%d, RES:%d, Max TCs:%d",
tval >> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07));
/*Print Priority Assignment Table*/
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table*/
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
/*Print Priority Assignment Table */
print_ets_priority_assignment_table(ndo, tptr + 5);
/*Print TC Bandwidth Table */
print_tc_bandwidth_table(ndo, tptr + 9);
/* Print TSA Assignment Table */
print_tsa_assignment_table(ndo, tptr + 17);
break;
case LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_PFC_CONFIGURATION_LENGTH) {
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Willing: %d, MBC: %d, RES: %d, PFC cap:%d ",
tval >> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f)));
ND_PRINT((ndo, "\n\t PFC Enable"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t Priority : 0 1 2 3 4 5 6 7"));
ND_PRINT((ndo, "\n\t Value : "));
for(i=0;i<NO_OF_BITS;i++)
ND_PRINT((ndo, "%-2d ", (tval >> i) & 0x01));
break;
case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH) {
return hexdump;
}
ND_PRINT((ndo, "\n\t RES: %d", *(tptr + 4)));
if(tlv_len<=LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY_MIN_LENGTH){
return hexdump;
}
/* Length of Application Priority Table */
sublen=tlv_len-5;
if(sublen%3!=0){
return hexdump;
}
i=0;
ND_PRINT((ndo, "\n\t Application Priority Table"));
while(i<sublen) {
tval=*(tptr+i+5);
ND_PRINT((ndo, "\n\t Priority: %d, RES: %d, Sel: %d",
tval >> 5, (tval >> 3) & 0x03, (tval & 0x07)));
ND_PRINT((ndo, "Protocol ID: %d", EXTRACT_16BITS(tptr + i + 5)));
i=i+3;
}
break;
case LLDP_PRIVATE_8021_SUBTYPE_EVB:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_EVB_LENGTH){
return hexdump;
}
ND_PRINT((ndo, "\n\t EVB Bridge Status"));
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t RES: %d, BGID: %d, RRCAP: %d, RRCTR: %d",
tval >> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01));
ND_PRINT((ndo, "\n\t EVB Station Status"));
tval=*(tptr+5);
ND_PRINT((ndo, "\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d",
tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03));
tval=*(tptr+6);
ND_PRINT((ndo, "\n\t R: %d, RTE: %d, ",tval >> 5, tval & 0x1f));
tval=*(tptr+7);
ND_PRINT((ndo, "EVB Mode: %s [%d]",
tok2str(lldp_evb_mode_values, "unknown", tval >> 6), tval >> 6));
ND_PRINT((ndo, "\n\t ROL: %d, RWD: %d, ", (tval >> 5) & 0x01, tval & 0x1f));
tval=*(tptr+8);
ND_PRINT((ndo, "RES: %d, ROL: %d, RKA: %d", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f));
break;
case LLDP_PRIVATE_8021_SUBTYPE_CDCP:
if(tlv_len<LLDP_PRIVATE_8021_SUBTYPE_CDCP_MIN_LENGTH){
return hexdump;
}
tval=*(tptr+4);
ND_PRINT((ndo, "\n\t Role: %d, RES: %d, Scomp: %d ",
tval >> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01));
ND_PRINT((ndo, "ChnCap: %d", EXTRACT_16BITS(tptr + 6) & 0x0fff));
sublen=tlv_len-8;
if(sublen%3!=0) {
return hexdump;
}
i=0;
while(i<sublen) {
tval=EXTRACT_24BITS(tptr+i+8);
ND_PRINT((ndo, "\n\t SCID: %d, SVID: %d",
tval >> 12, tval & 0x000fff));
i=i+3;
}
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print IEEE 802.3 private extensions. (802.3bc)
*/
static int
lldp_private_8023_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_8023_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_8023_SUBTYPE_MACPHY:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)",
bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)",
bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)),
EXTRACT_16BITS(tptr + 5)));
ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)",
tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)),
EXTRACT_16BITS(tptr + 7)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s",
bittok2str(lldp_mdi_values, "none", *(tptr+4)),
tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)),
tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6))));
break;
case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR:
if (tlv_len < 9) {
return hexdump;
}
ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u",
bittok2str(lldp_aggregation_values, "none", *(tptr+4)),
EXTRACT_32BITS(tptr + 5)));
break;
case LLDP_PRIVATE_8023_SUBTYPE_MTU:
ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Extract 34bits of latitude/longitude coordinates.
*/
static uint64_t
lldp_extract_latlon(const u_char *tptr)
{
uint64_t latlon;
latlon = *tptr & 0x3;
latlon = (latlon << 32) | EXTRACT_32BITS(tptr+1);
return latlon;
}
/* objects defined in IANA subtype 00 00 5e
* (right now there is only one)
*/
static int
lldp_private_iana_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
if (tlv_len < 8) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_iana_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_IANA_SUBTYPE_MUDURL:
ND_PRINT((ndo, "\n\t MUD-URL="));
(void)fn_printn(ndo, tptr+4, tlv_len-4, NULL);
break;
default:
hexdump=TRUE;
}
return hexdump;
}
/*
* Print private TIA extensions.
*/
static int
lldp_private_tia_print(netdissect_options *ndo,
const u_char *tptr, u_int tlv_len)
{
int subtype, hexdump = FALSE;
uint8_t location_format;
uint16_t power_val;
u_int lci_len;
uint8_t ca_type, ca_len;
if (tlv_len < 4) {
return hexdump;
}
subtype = *(tptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_tia_subtype_values, "unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PRIVATE_TIA_SUBTYPE_CAPABILITIES:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Media capabilities [%s] (0x%04x)",
bittok2str(lldp_tia_capabilities_values, "none",
EXTRACT_16BITS(tptr + 4)), EXTRACT_16BITS(tptr + 4)));
ND_PRINT((ndo, "\n\t Device type [%s] (0x%02x)",
tok2str(lldp_tia_device_type_values, "unknown", *(tptr+6)),
*(tptr + 6)));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_NETWORK_POLICY:
if (tlv_len < 8) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Application type [%s] (0x%02x)",
tok2str(lldp_tia_application_type_values, "none", *(tptr+4)),
*(tptr + 4)));
ND_PRINT((ndo, ", Flags [%s]", bittok2str(
lldp_tia_network_policy_bits_values, "none", *(tptr + 5))));
ND_PRINT((ndo, "\n\t Vlan id %u",
LLDP_EXTRACT_NETWORK_POLICY_VLAN(EXTRACT_16BITS(tptr + 5))));
ND_PRINT((ndo, ", L2 priority %u",
LLDP_EXTRACT_NETWORK_POLICY_L2_PRIORITY(EXTRACT_16BITS(tptr + 6))));
ND_PRINT((ndo, ", DSCP value %u",
LLDP_EXTRACT_NETWORK_POLICY_DSCP(EXTRACT_16BITS(tptr + 6))));
break;
case LLDP_PRIVATE_TIA_SUBTYPE_LOCAL_ID:
if (tlv_len < 5) {
return hexdump;
}
location_format = *(tptr+4);
ND_PRINT((ndo, "\n\t Location data format %s (0x%02x)",
tok2str(lldp_tia_location_data_format_values, "unknown", location_format),
location_format));
switch (location_format) {
case LLDP_TIA_LOCATION_DATA_FORMAT_COORDINATE_BASED:
if (tlv_len < 21) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Latitude resolution %u, latitude value %" PRIu64,
(*(tptr + 5) >> 2), lldp_extract_latlon(tptr + 5)));
ND_PRINT((ndo, "\n\t Longitude resolution %u, longitude value %" PRIu64,
(*(tptr + 10) >> 2), lldp_extract_latlon(tptr + 10)));
ND_PRINT((ndo, "\n\t Altitude type %s (%u)",
tok2str(lldp_tia_location_altitude_type_values, "unknown",(*(tptr+15)>>4)),
(*(tptr + 15) >> 4)));
ND_PRINT((ndo, "\n\t Altitude resolution %u, altitude value 0x%x",
(EXTRACT_16BITS(tptr+15)>>6)&0x3f,
((EXTRACT_32BITS(tptr + 16) & 0x3fffffff))));
ND_PRINT((ndo, "\n\t Datum %s (0x%02x)",
tok2str(lldp_tia_location_datum_type_values, "unknown", *(tptr+20)),
*(tptr + 20)));
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_CIVIC_ADDRESS:
if (tlv_len < 6) {
return hexdump;
}
lci_len = *(tptr+5);
if (lci_len < 3) {
return hexdump;
}
if (tlv_len < 7+lci_len) {
return hexdump;
}
ND_PRINT((ndo, "\n\t LCI length %u, LCI what %s (0x%02x), Country-code ",
lci_len,
tok2str(lldp_tia_location_lci_what_values, "unknown", *(tptr+6)),
*(tptr + 6)));
/* Country code */
safeputs(ndo, tptr + 7, 2);
lci_len = lci_len-3;
tptr = tptr + 9;
/* Decode each civic address element */
while (lci_len > 0) {
if (lci_len < 2) {
return hexdump;
}
ca_type = *(tptr);
ca_len = *(tptr+1);
tptr += 2;
lci_len -= 2;
ND_PRINT((ndo, "\n\t CA type \'%s\' (%u), length %u: ",
tok2str(lldp_tia_location_lci_catype_values, "unknown", ca_type),
ca_type, ca_len));
/* basic sanity check */
if ( ca_type == 0 || ca_len == 0) {
return hexdump;
}
if (lci_len < ca_len) {
return hexdump;
}
safeputs(ndo, tptr, ca_len);
tptr += ca_len;
lci_len -= ca_len;
}
break;
case LLDP_TIA_LOCATION_DATA_FORMAT_ECS_ELIN:
ND_PRINT((ndo, "\n\t ECS ELIN id "));
safeputs(ndo, tptr + 5, tlv_len - 5);
break;
default:
ND_PRINT((ndo, "\n\t Location ID "));
print_unknown_data(ndo, tptr + 5, "\n\t ", tlv_len - 5);
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_EXTENDED_POWER_MDI:
if (tlv_len < 7) {
return hexdump;
}
ND_PRINT((ndo, "\n\t Power type [%s]",
(*(tptr + 4) & 0xC0 >> 6) ? "PD device" : "PSE device"));
ND_PRINT((ndo, ", Power source [%s]",
tok2str(lldp_tia_power_source_values, "none", (*(tptr + 4) & 0x30) >> 4)));
ND_PRINT((ndo, "\n\t Power priority [%s] (0x%02x)",
tok2str(lldp_tia_power_priority_values, "none", *(tptr+4)&0x0f),
*(tptr + 4) & 0x0f));
power_val = EXTRACT_16BITS(tptr+5);
if (power_val < LLDP_TIA_POWER_VAL_MAX) {
ND_PRINT((ndo, ", Power %.1f Watts", ((float)power_val) / 10));
} else {
ND_PRINT((ndo, ", Power %u (Reserved)", power_val));
}
break;
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_HARDWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_FIRMWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SOFTWARE_REV:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_SERIAL_NUMBER:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MANUFACTURER_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_MODEL_NAME:
case LLDP_PRIVATE_TIA_SUBTYPE_INVENTORY_ASSET_ID:
ND_PRINT((ndo, "\n\t %s ",
tok2str(lldp_tia_inventory_values, "unknown", subtype)));
safeputs(ndo, tptr + 4, tlv_len - 4);
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
/*
* Print DCBX Protocol fields (V 1.01).
*/
static int
lldp_private_dcbx_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
int subtype, hexdump = FALSE;
uint8_t tval;
uint16_t tlv;
uint32_t i, pgval, uval;
u_int tlen, tlv_type, tlv_len;
const u_char *tptr, *mptr;
if (len < 4) {
return hexdump;
}
subtype = *(pptr+3);
ND_PRINT((ndo, "\n\t %s Subtype (%u)",
tok2str(lldp_dcbx_subtype_values, "unknown", subtype),
subtype));
/* by passing old version */
if (subtype == LLDP_DCBX_SUBTYPE_1)
return TRUE;
tptr = pptr + 4;
tlen = len - 4;
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
/* loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
/* decode every tlv */
switch (tlv_type) {
case LLDP_DCBX_CONTROL_TLV:
if (tlv_len < 10) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Control - Protocol Control (type 0x%x, length %d)",
LLDP_DCBX_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Sequence Number: %d", EXTRACT_32BITS(tptr + 2)));
ND_PRINT((ndo, "\n\t Acknowledgement Number: %d",
EXTRACT_32BITS(tptr + 6)));
break;
case LLDP_DCBX_PRIORITY_GROUPS_TLV:
if (tlv_len < 17) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Group (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_GROUPS_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
ND_PRINT((ndo, "\n\t Priority Allocation"));
/*
* Array of 8 4-bit priority group ID values; we fetch all
* 32 bits and extract each nibble.
*/
pgval = EXTRACT_32BITS(tptr+4);
for (i = 0; i <= 7; i++) {
ND_PRINT((ndo, "\n\t PgId_%d: %d",
i, (pgval >> (28 - 4 * i)) & 0xF));
}
ND_PRINT((ndo, "\n\t Priority Group Allocation"));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Pg percentage[%d]: %d", i, *(tptr + 8 + i)));
ND_PRINT((ndo, "\n\t NumTCsSupported: %d", *(tptr + 8 + 8)));
break;
case LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV:
if (tlv_len < 6) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Priority Flow Control"));
ND_PRINT((ndo, " (type 0x%x, length %d)",
LLDP_DCBX_PRIORITY_FLOW_CONTROL_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = *(tptr+4);
ND_PRINT((ndo, "\n\t PFC Config (0x%02X)", *(tptr + 4)));
for (i = 0; i <= 7; i++)
ND_PRINT((ndo, "\n\t Priority Bit %d: %s",
i, (tval & (1 << i)) ? "Enabled" : "Disabled"));
ND_PRINT((ndo, "\n\t NumTCPFCSupported: %d", *(tptr + 5)));
break;
case LLDP_DCBX_APPLICATION_TLV:
if (tlv_len < 4) {
goto trunc;
}
ND_PRINT((ndo, "\n\t Feature - Application (type 0x%x, length %d)",
LLDP_DCBX_APPLICATION_TLV, tlv_len));
ND_PRINT((ndo, "\n\t Oper_Version: %d", *tptr));
ND_PRINT((ndo, "\n\t Max_Version: %d", *(tptr + 1)));
ND_PRINT((ndo, "\n\t Info block(0x%02X): ", *(tptr + 2)));
tval = *(tptr+2);
ND_PRINT((ndo, "Enable bit: %d, Willing bit: %d, Error Bit: %d",
(tval & 0x80) ? 1 : 0, (tval & 0x40) ? 1 : 0,
(tval & 0x20) ? 1 : 0));
ND_PRINT((ndo, "\n\t SubType: %d", *(tptr + 3)));
tval = tlv_len - 4;
mptr = tptr + 4;
while (tval >= 6) {
ND_PRINT((ndo, "\n\t Application Value"));
ND_PRINT((ndo, "\n\t Application Protocol ID: 0x%04x",
EXTRACT_16BITS(mptr)));
uval = EXTRACT_24BITS(mptr+2);
ND_PRINT((ndo, "\n\t SF (0x%x) Application Protocol ID is %s",
(uval >> 22),
(uval >> 22) ? "Socket Number" : "L2 EtherType"));
ND_PRINT((ndo, "\n\t OUI: 0x%06x", uval & 0x3fffff));
ND_PRINT((ndo, "\n\t User Priority Map: 0x%02x", *(mptr + 5)));
tval = tval - 6;
mptr = mptr + 6;
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
trunc:
return hexdump;
}
static char *
lldp_network_addr_print(netdissect_options *ndo, const u_char *tptr, u_int len)
{
uint8_t af;
static char buf[BUFSIZE];
const char * (*pfunc)(netdissect_options *, const u_char *);
if (len < 1)
return NULL;
len--;
af = *tptr;
switch (af) {
case AFNUM_INET:
if (len < 4)
return NULL;
/* This cannot be assigned to ipaddr_string(), which is a macro. */
pfunc = getname;
break;
case AFNUM_INET6:
if (len < 16)
return NULL;
/* This cannot be assigned to ip6addr_string(), which is a macro. */
pfunc = getname6;
break;
case AFNUM_802:
if (len < 6)
return NULL;
pfunc = etheraddr_string;
break;
default:
pfunc = NULL;
break;
}
if (!pfunc) {
snprintf(buf, sizeof(buf), "AFI %s (%u), no AF printer !",
tok2str(af_values, "Unknown", af), af);
} else {
snprintf(buf, sizeof(buf), "AFI %s (%u): %s",
tok2str(af_values, "Unknown", af), af, (*pfunc)(ndo, tptr+1));
}
return buf;
}
static int
lldp_mgmt_addr_tlv_print(netdissect_options *ndo,
const u_char *pptr, u_int len)
{
uint8_t mgmt_addr_len, intf_num_subtype, oid_len;
const u_char *tptr;
u_int tlen;
char *mgmt_addr;
tlen = len;
tptr = pptr;
if (tlen < 1) {
return 0;
}
mgmt_addr_len = *tptr++;
tlen--;
if (tlen < mgmt_addr_len) {
return 0;
}
mgmt_addr = lldp_network_addr_print(ndo, tptr, mgmt_addr_len);
if (mgmt_addr == NULL) {
return 0;
}
ND_PRINT((ndo, "\n\t Management Address length %u, %s",
mgmt_addr_len, mgmt_addr));
tptr += mgmt_addr_len;
tlen -= mgmt_addr_len;
if (tlen < LLDP_INTF_NUM_LEN) {
return 0;
}
intf_num_subtype = *tptr;
ND_PRINT((ndo, "\n\t %s Interface Numbering (%u): %u",
tok2str(lldp_intf_numb_subtype_values, "Unknown", intf_num_subtype),
intf_num_subtype,
EXTRACT_32BITS(tptr + 1)));
tptr += LLDP_INTF_NUM_LEN;
tlen -= LLDP_INTF_NUM_LEN;
/*
* The OID is optional.
*/
if (tlen) {
oid_len = *tptr;
if (tlen < oid_len) {
return 0;
}
if (oid_len) {
ND_PRINT((ndo, "\n\t OID length %u", oid_len));
safeputs(ndo, tptr + 1, oid_len);
}
}
return 1;
}
void
lldp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
uint8_t subtype;
uint16_t tlv, cap, ena_cap;
u_int oui, tlen, hexdump, tlv_type, tlv_len;
const u_char *tptr;
char *network_addr;
tptr = pptr;
tlen = len;
ND_PRINT((ndo, "LLDP, length %u", len));
while (tlen >= sizeof(tlv)) {
ND_TCHECK2(*tptr, sizeof(tlv));
tlv = EXTRACT_16BITS(tptr);
tlv_type = LLDP_EXTRACT_TYPE(tlv);
tlv_len = LLDP_EXTRACT_LEN(tlv);
hexdump = FALSE;
tlen -= sizeof(tlv);
tptr += sizeof(tlv);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t%s TLV (%u), length %u",
tok2str(lldp_tlv_values, "Unknown", tlv_type),
tlv_type, tlv_len));
}
/* infinite loop check */
if (!tlv_type || !tlv_len) {
break;
}
ND_TCHECK2(*tptr, tlv_len);
if (tlen < tlv_len) {
goto trunc;
}
switch (tlv_type) {
case LLDP_CHASSIS_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_chassis_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_CHASSIS_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_CHASSIS_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_CHASSIS_LOCAL_SUBTYPE:
case LLDP_CHASSIS_CHASSIS_COMP_SUBTYPE:
case LLDP_CHASSIS_INTF_ALIAS_SUBTYPE:
case LLDP_CHASSIS_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_CHASSIS_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_PORT_ID_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
subtype = *tptr;
ND_PRINT((ndo, "\n\t Subtype %s (%u): ",
tok2str(lldp_port_subtype_values, "Unknown", subtype),
subtype));
switch (subtype) {
case LLDP_PORT_MAC_ADDR_SUBTYPE:
if (tlv_len < 1+6) {
goto trunc;
}
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr + 1)));
break;
case LLDP_PORT_INTF_NAME_SUBTYPE: /* fall through */
case LLDP_PORT_LOCAL_SUBTYPE:
case LLDP_PORT_AGENT_CIRC_ID_SUBTYPE:
case LLDP_PORT_INTF_ALIAS_SUBTYPE:
case LLDP_PORT_PORT_COMP_SUBTYPE:
safeputs(ndo, tptr + 1, tlv_len - 1);
break;
case LLDP_PORT_NETWORK_ADDR_SUBTYPE:
network_addr = lldp_network_addr_print(ndo, tptr+1, tlv_len-1);
if (network_addr == NULL) {
goto trunc;
}
ND_PRINT((ndo, "%s", network_addr));
break;
default:
hexdump = TRUE;
break;
}
}
break;
case LLDP_TTL_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 2) {
goto trunc;
}
ND_PRINT((ndo, ": TTL %us", EXTRACT_16BITS(tptr)));
}
break;
case LLDP_PORT_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_NAME_TLV:
/*
* The system name is also print in non-verbose mode
* similar to the CDP printer.
*/
ND_PRINT((ndo, ": "));
safeputs(ndo, tptr, tlv_len);
break;
case LLDP_SYSTEM_DESCR_TLV:
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "\n\t "));
safeputs(ndo, tptr, tlv_len);
}
break;
case LLDP_SYSTEM_CAP_TLV:
if (ndo->ndo_vflag) {
/*
* XXX - IEEE Std 802.1AB-2009 says the first octet
* if a chassis ID subtype, with the system
* capabilities and enabled capabilities following
* it.
*/
if (tlv_len < 4) {
goto trunc;
}
cap = EXTRACT_16BITS(tptr);
ena_cap = EXTRACT_16BITS(tptr+2);
ND_PRINT((ndo, "\n\t System Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", cap), cap));
ND_PRINT((ndo, "\n\t Enabled Capabilities [%s] (0x%04x)",
bittok2str(lldp_cap_values, "none", ena_cap), ena_cap));
}
break;
case LLDP_MGMT_ADDR_TLV:
if (ndo->ndo_vflag) {
if (!lldp_mgmt_addr_tlv_print(ndo, tptr, tlv_len)) {
goto trunc;
}
}
break;
case LLDP_PRIVATE_TLV:
if (ndo->ndo_vflag) {
if (tlv_len < 3) {
goto trunc;
}
oui = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, ": OUI %s (0x%06x)", tok2str(oui_values, "Unknown", oui), oui));
switch (oui) {
case OUI_IEEE_8021_PRIVATE:
hexdump = lldp_private_8021_print(ndo, tptr, tlv_len);
break;
case OUI_IEEE_8023_PRIVATE:
hexdump = lldp_private_8023_print(ndo, tptr, tlv_len);
break;
case OUI_IANA:
hexdump = lldp_private_iana_print(ndo, tptr, tlv_len);
break;
case OUI_TIA:
hexdump = lldp_private_tia_print(ndo, tptr, tlv_len);
break;
case OUI_DCBX:
hexdump = lldp_private_dcbx_print(ndo, tptr, tlv_len);
break;
default:
hexdump = TRUE;
break;
}
}
break;
default:
hexdump = TRUE;
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || (ndo->ndo_vflag && hexdump)) {
print_unknown_data(ndo, tptr, "\n\t ", tlv_len);
}
tlen -= tlv_len;
tptr += tlv_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|LLDP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2670_0 |
crossvul-cpp_data_good_456_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2013 Conifer Software. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// pack_utils.c
// This module provides the high-level API for creating WavPack files from
// audio data. It manages the buffers used to deinterleave the data passed
// in from the application into the individual streams and it handles the
// generation of riff headers and the "fixup" on the first WavPack block
// header for the case where the number of samples was unknown (or wrong).
// The actual audio stream compression is handled in the pack.c module.
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "wavpack_local.h"
///////////////////////////// executable code ////////////////////////////////
// Open context for writing WavPack files. The returned context pointer is used
// in all following calls to the library. The "blockout" function will be used
// to store the actual completed WavPack blocks and will be called with the id
// pointers containing user defined data (one for the wv file and one for the
// wvc file). A return value of NULL indicates that memory could not be
// allocated for the context.
WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id)
{
WavpackContext *wpc = malloc (sizeof (WavpackContext));
if (!wpc)
return NULL;
CLEAR (*wpc);
wpc->total_samples = -1;
wpc->stream_version = CUR_STREAM_VERS;
wpc->blockout = blockout;
wpc->wv_out = wv_id;
wpc->wvc_out = wvc_id;
return wpc;
}
static int add_to_metadata (WavpackContext *wpc, void *data, uint32_t bcount, unsigned char id);
// New for version 5.0, this function allows the application to store a file extension and a
// file_format identification. The extension would be used by the unpacker if the user had not
// specified the target filename, and specifically handles the case where the original file
// had the "wrong" extension for the file format (e.g., a Wave64 file having a "wav" extension)
// or an alternative (e.g., "bwf") or where the file format is not known. Specifying a file
// format besides the default WP_FORMAT_WAV will ensure that old decoders will not be able to
// see the non-wav wrapper provided with WavpackAddWrapper() (which they would end up putting
// on a file with a .wav extension).
void WavpackSetFileInformation (WavpackContext *wpc, char *file_extension, unsigned char file_format)
{
if (file_extension && strlen (file_extension) < sizeof (wpc->file_extension)) {
add_to_metadata (wpc, file_extension, (uint32_t) strlen (file_extension), ID_ALT_EXTENSION);
strcpy (wpc->file_extension, file_extension);
}
wpc->file_format = file_format;
}
// Set configuration for writing WavPack files. This must be done before
// sending any actual samples, however it is okay to send wrapper or other
// metadata before calling this. The "config" structure contains the following
// required information:
// config->bytes_per_sample see WavpackGetBytesPerSample() for info
// config->bits_per_sample see WavpackGetBitsPerSample() for info
// config->channel_mask Microsoft standard (mono = 4, stereo = 3)
// config->num_channels self evident
// config->sample_rate self evident
// In addition, the following fields and flags may be set:
// config->flags:
// --------------
// o CONFIG_HYBRID_FLAG select hybrid mode (must set bitrate)
// o CONFIG_JOINT_STEREO select joint stereo (must set override also)
// o CONFIG_JOINT_OVERRIDE override default joint stereo selection
// o CONFIG_HYBRID_SHAPE select hybrid noise shaping (set override &
// shaping_weight != 0.0)
// o CONFIG_SHAPE_OVERRIDE override default hybrid noise shaping
// (set CONFIG_HYBRID_SHAPE and shaping_weight)
// o CONFIG_FAST_FLAG "fast" compression mode
// o CONFIG_HIGH_FLAG "high" compression mode
// o CONFIG_BITRATE_KBPS hybrid bitrate is kbps, not bits / sample
// o CONFIG_CREATE_WVC create correction file
// o CONFIG_OPTIMIZE_WVC maximize bybrid compression (-cc option)
// o CONFIG_CALC_NOISE calc noise in hybrid mode
// o CONFIG_EXTRA_MODE extra processing mode (slow!)
// o CONFIG_SKIP_WVX no wvx stream for floats & large ints
// o CONFIG_MD5_CHECKSUM specify if you plan to store MD5 signature
// o CONFIG_CREATE_EXE specify if you plan to prepend sfx module
// o CONFIG_OPTIMIZE_MONO detect and optimize for mono files posing as
// stereo (uses a more recent stream format that
// is not compatible with decoders < 4.3)
// config->bitrate hybrid bitrate in either bits/sample or kbps
// config->shaping_weight hybrid noise shaping coefficient override
// config->block_samples force samples per WavPack block (0 = use deflt)
// config->float_norm_exp select floating-point data (127 for +/-1.0)
// config->xmode extra mode processing value override
// If the number of samples to be written is known then it should be passed
// here. If the duration is not known then pass -1. In the case that the size
// is not known (or the writing is terminated early) then it is suggested that
// the application retrieve the first block written and let the library update
// the total samples indication. A function is provided to do this update and
// it should be done to the "correction" file also. If this cannot be done
// (because a pipe is being used, for instance) then a valid WavPack will still
// be created, but when applications want to access that file they will have
// to seek all the way to the end to determine the actual duration. Also, if
// a RIFF header has been included then it should be updated as well or the
// WavPack file will not be directly unpackable to a valid wav file (although
// it will still be usable by itself). A return of FALSE indicates an error.
//
// The enhanced version of this function now allows setting the identities of
// any channels that are NOT standard Microsoft channels and are therefore not
// represented in the channel mask. WavPack files require that all the Microsoft
// channels come first (and in Microsoft order) and these are followed by any
// other channels (which can be in any order).
//
// The identities are provided in a NULL-terminated string (0x00 is not an allowed
// channel ID). The Microsoft channels may be provided as well (and will be checked)
// but it is really only necessary to provide the "unknown" channels. Any truly
// unknown channels are indicated with a 0xFF.
//
// The channel IDs so far reserved are listed here:
//
// 0: not allowed / terminator
// 1 - 18: Microsoft standard channels
// 30, 31: Stereo mix from RF64 (not really recommended, but RF64 specifies this)
// 33 - 44: Core Audio channels (see Core Audio specification)
// 127 - 128: Amio LeftHeight, Amio RightHeight
// 138 - 142: Amio BottomFrontLeft/Center/Right, Amio ProximityLeft/Right
// 200 - 207: Core Audio channels (see Core Audio specification)
// 221 - 224: Core Audio channels 301 - 305 (offset by 80)
// 255: Present but unknown or unused channel
//
// All other channel IDs are reserved. Ask if something you need is missing.
// Table of channels that will automatically "pair" into a single stereo stream
static const struct { unsigned char a, b; } stereo_pairs [] = {
{ 1, 2 }, // FL, FR
{ 5, 6 }, // BL, BR
{ 7, 8 }, // FLC, FRC
{ 10, 11 }, // SL, SR
{ 13, 15 }, // TFL, TFR
{ 16, 18 }, // TBL, TBR
{ 30, 31 }, // stereo mix L,R (RF64)
{ 33, 34 }, // Rls, Rrs
{ 35, 36 }, // Lw, Rw
{ 38, 39 }, // Lt, Rt
{ 127, 128 }, // Lh, Rh
{ 138, 140 }, // Bfl, Bfr
{ 141, 142 }, // Pl, Pr
{ 200, 201 }, // Amb_W, Amb_X
{ 202, 203 }, // Amb_Y, Amb_Z
{ 204, 205 }, // MS_Mid, MS_Side
{ 206, 207 }, // XY_X, XY_Y
{ 221, 222 }, // Hph_L, Hph_R
};
#define NUM_STEREO_PAIRS (sizeof (stereo_pairs) / sizeof (stereo_pairs [0]))
// Legacy version of this function for compatibility with existing applications. Note that this version
// also generates older streams to be compatible with all decoders back to 4.0, but of course cannot be
// used with > 2^32 samples or non-Microsoft channels. The older stream version only differs in that it
// does not support the "mono optimization" feature where stereo blocks containing identical audio data
// in both channels are encoded in mono for better efficiency.
int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples)
{
config->flags |= CONFIG_COMPATIBLE_WRITE; // write earlier version streams
if (total_samples == (uint32_t) -1)
return WavpackSetConfiguration64 (wpc, config, -1, NULL);
else
return WavpackSetConfiguration64 (wpc, config, total_samples, NULL);
}
int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
if (!config->sample_rate) {
strcpy (wpc->error_message, "sample rate cannot be zero!");
return FALSE;
}
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
// most options that don't apply to DSD we can simply ignore for now, but NOT hybrid mode!
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
// with DSD, very few PCM options work (or make sense), so only allow those that do
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
// all of this stuff only applies to PCM
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
// if a channel-identities string was specified, process that here, otherwise all channels
// not present in the channel mask are considered "unassigned"
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
// skip past channels that are specified in the channel mask (no reason to store those)
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
// now scan the string for an actually defined channel (and don't store if there aren't any)
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
// This loop goes through all the channels and creates the Wavpack "streams" for them to go in.
// A stream can hold either one or two channels, so we have several rules to determine how many
// channels will go in each stream.
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
// allocate the stream and initialize the pointer to it
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
// if there are any bits [still] set in the channel_mask, get the next one or two IDs from there
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
// next check for any channels identified in the channel-identities string
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
// assume anything we did not get is "unassigned"
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
// if we have 2 channels, this is where we decide if we can combine them into one stream:
// 1. they are "unassigned" and we've been told to combine unassigned pairs, or
// 2. they appear together in the valid "pairings" list
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
// This function allows setting the Core Audio File channel layout, many of which do not
// conform to the Microsoft ordering standard that Wavpack requires internally (at least for
// those channels present in the "channel mask"). In addition to the layout tag, this function
// allows a reordering string to be stored in the file to allow the unpacker to reorder the
// channels back to the specified layout (if it is aware of this feature and wants to restore
// the CAF order). The number of channels in the layout is specified in the lower nybble of
// the layout word, and if a reorder string is specified it must be that long. Note that all
// the reordering is actually done outside of this library, and that if reordering is done
// then the appropriate qmode bit must be set to ensure that any MD5 sum is stored with a new
// ID so that old decoders don't try to verify it (and to let the decoder know that a reorder
// might be required).
//
// Note: This function should only be used to encode Core Audio files in such a way that a
// verbatim archive can be created. Applications can just include the chan_ids parameter in
// the call to WavpackSetConfiguration64() if there are non-Microsoft channels to specify,
// or do nothing special if only Microsoft channels are present (the vast majority of cases).
int WavpackSetChannelLayout (WavpackContext *wpc, uint32_t layout_tag, const unsigned char *reorder)
{
int nchans = layout_tag & 0xff;
if ((layout_tag & 0xff00ff00) || nchans > wpc->config.num_channels)
return FALSE;
wpc->channel_layout = layout_tag;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
if (nchans && reorder) {
int min_index = 256, i;
for (i = 0; i < nchans; ++i)
if (reorder [i] < min_index)
min_index = reorder [i];
wpc->channel_reordering = malloc (nchans);
if (wpc->channel_reordering)
for (i = 0; i < nchans; ++i)
wpc->channel_reordering [i] = reorder [i] - min_index;
}
return TRUE;
}
// Prepare to actually pack samples by determining the size of the WavPack
// blocks and allocating sample buffers and initializing each stream. Call
// after WavpackSetConfiguration() and before WavpackPackSamples(). A return
// of FALSE indicates an error.
static int write_metadata_block (WavpackContext *wpc);
int WavpackPackInit (WavpackContext *wpc)
{
if (wpc->metabytes > 16384) // 16384 bytes still leaves plenty of room for audio
write_metadata_block (wpc); // in this block (otherwise write a special one)
// The default block size is a compromise. Longer blocks provide better encoding efficiency,
// but longer blocks adversely affect memory requirements and seeking performance. For WavPack
// version 5.0, the default block sizes have been reduced by half from the previous version,
// but the difference in encoding efficiency will generally be less than 0.1 percent.
if (wpc->dsd_multiplier) {
wpc->block_samples = (wpc->config.sample_rate % 7) ? 48000 : 44100;
if (wpc->config.flags & CONFIG_HIGH_FLAG)
wpc->block_samples /= 2;
if (wpc->config.num_channels == 1)
wpc->block_samples *= 2;
while (wpc->block_samples > 12000 && wpc->block_samples * wpc->config.num_channels > 300000)
wpc->block_samples /= 2;
}
else {
int divisor = (wpc->config.flags & CONFIG_HIGH_FLAG) ? 2 : 4;
while (wpc->config.sample_rate % divisor)
divisor--;
wpc->block_samples = wpc->config.sample_rate / divisor;
while (wpc->block_samples > 12000 && wpc->block_samples * wpc->config.num_channels > 75000)
wpc->block_samples /= 2;
while (wpc->block_samples * wpc->config.num_channels < 20000)
wpc->block_samples *= 2;
}
if (wpc->config.block_samples) {
if ((wpc->config.flags & CONFIG_MERGE_BLOCKS) &&
wpc->block_samples > (uint32_t) wpc->config.block_samples) {
wpc->block_boundary = wpc->config.block_samples;
wpc->block_samples /= wpc->config.block_samples;
wpc->block_samples *= wpc->config.block_samples;
}
else
wpc->block_samples = wpc->config.block_samples;
}
wpc->ave_block_samples = wpc->block_samples;
wpc->max_samples = wpc->block_samples + (wpc->block_samples >> 1);
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
wps->sample_buffer = malloc (wpc->max_samples * (wps->wphdr.flags & MONO_FLAG ? 4 : 8));
#ifdef ENABLE_DSD
if (wps->wphdr.flags & DSD_FLAG)
pack_dsd_init (wpc);
else
#endif
pack_init (wpc);
}
return TRUE;
}
// Pack the specified samples. Samples must be stored in longs in the native
// endian format of the executing processor. The number of samples specified
// indicates composite samples (sometimes called "frames"). So, the actual
// number of data points would be this "sample_count" times the number of
// channels. Note that samples are accumulated here until enough exist to
// create a complete WavPack block (or several blocks for multichannel audio).
// If an application wants to break a block at a specific sample, then it must
// simply call WavpackFlushSamples() to force an early termination. Completed
// WavPack blocks are send to the function provided in the initial call to
// WavpackOpenFileOutput(). A return of FALSE indicates an error.
static int pack_streams (WavpackContext *wpc, uint32_t block_samples);
static int create_riff_header (WavpackContext *wpc, int64_t total_samples, void *outbuffer);
int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count)
{
int nch = wpc->config.num_channels;
while (sample_count) {
int32_t *source_pointer = sample_buffer;
unsigned int samples_to_copy;
if (!wpc->riff_header_added && !wpc->riff_header_created && !wpc->file_format) {
char riff_header [128];
if (!add_to_metadata (wpc, riff_header, create_riff_header (wpc, wpc->total_samples, riff_header), ID_RIFF_HEADER))
return FALSE;
}
if (wpc->acc_samples + sample_count > wpc->max_samples)
samples_to_copy = wpc->max_samples - wpc->acc_samples;
else
samples_to_copy = sample_count;
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
int32_t *dptr, *sptr, cnt;
dptr = wps->sample_buffer + wpc->acc_samples * (wps->wphdr.flags & MONO_FLAG ? 1 : 2);
sptr = source_pointer;
cnt = samples_to_copy;
// This code used to just copy the 32-bit samples regardless of the actual size with the
// assumption that the caller had properly sign-extended the values (if they were smaller
// than 32 bits). However, several people have discovered that if the data isn't properly
// sign extended then ugly things happen (e.g. CRC errors that show up only on decode).
// To prevent this, we now explicitly sign-extend samples smaller than 32-bit when we
// copy, and the performance hit from doing this is very small (generally < 1%).
if (wps->wphdr.flags & MONO_FLAG) {
switch (wpc->config.bytes_per_sample) {
case 1:
while (cnt--) {
*dptr++ = (signed char) *sptr;
sptr += nch;
}
break;
case 2:
while (cnt--) {
*dptr++ = (int16_t) *sptr;
sptr += nch;
}
break;
case 3:
while (cnt--) {
*dptr++ = (*sptr << 8) >> 8;
sptr += nch;
}
break;
default:
while (cnt--) {
*dptr++ = *sptr;
sptr += nch;
}
}
source_pointer++;
}
else {
switch (wpc->config.bytes_per_sample) {
case 1:
while (cnt--) {
*dptr++ = (signed char) sptr [0];
*dptr++ = (signed char) sptr [1];
sptr += nch;
}
break;
case 2:
while (cnt--) {
*dptr++ = (int16_t) sptr [0];
*dptr++ = (int16_t) sptr [1];
sptr += nch;
}
break;
case 3:
while (cnt--) {
*dptr++ = (sptr [0] << 8) >> 8;
*dptr++ = (sptr [1] << 8) >> 8;
sptr += nch;
}
break;
default:
while (cnt--) {
*dptr++ = sptr [0];
*dptr++ = sptr [1];
sptr += nch;
}
}
source_pointer += 2;
}
}
sample_buffer += samples_to_copy * nch;
sample_count -= samples_to_copy;
if ((wpc->acc_samples += samples_to_copy) == wpc->max_samples &&
!pack_streams (wpc, wpc->block_samples))
return FALSE;
}
return TRUE;
}
// Flush all accumulated samples into WavPack blocks. This is normally called
// after all samples have been sent to WavpackPackSamples(), but can also be
// called to terminate a WavPack block at a specific sample (in other words it
// is possible to continue after this operation). This is also called to
// dump non-audio blocks like those holding metadata for various purposes.
// A return of FALSE indicates an error.
int WavpackFlushSamples (WavpackContext *wpc)
{
while (wpc->acc_samples) {
uint32_t block_samples;
if (wpc->acc_samples > wpc->block_samples)
block_samples = wpc->acc_samples / 2;
else
block_samples = wpc->acc_samples;
if (!pack_streams (wpc, block_samples))
return FALSE;
}
if (wpc->metacount)
write_metadata_block (wpc);
return TRUE;
}
// Note: The following function is no longer required because a proper wav
// header is now automatically generated for the application. However, if the
// application wants to generate its own header or wants to include additional
// chunks, then this function can still be used in which case the automatic
// wav header generation is suppressed.
// Add wrapper (currently RIFF only) to WavPack blocks. This should be called
// before sending any audio samples for the RIFF header or after all samples
// have been sent for any RIFF trailer. WavpackFlushSamples() should be called
// between sending the last samples and calling this for trailer data to make
// sure that headers and trailers don't get mixed up in very short files. If
// the exact contents of the RIFF header are not known because, for example,
// the file duration is uncertain or trailing chunks are possible, simply write
// a "dummy" header of the correct length. When all data has been written it
// will be possible to read the first block written and update the header
// directly. An example of this can be found in the Audition filter. A
// return of FALSE indicates an error.
int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount)
{
int64_t index = WavpackGetSampleIndex64 (wpc);
unsigned char meta_id;
if (!index || index == -1) {
wpc->riff_header_added = TRUE;
meta_id = wpc->file_format ? ID_ALT_HEADER : ID_RIFF_HEADER;
}
else {
wpc->riff_trailer_bytes += bcount;
meta_id = wpc->file_format ? ID_ALT_TRAILER : ID_RIFF_TRAILER;
}
return add_to_metadata (wpc, data, bcount, meta_id);
}
// Store computed MD5 sum in WavPack metadata. Note that the user must compute
// the 16 byte sum; it is not done here. A return of FALSE indicates an error.
// If any of the lower 8 bits of qmode are set, then this MD5 is stored with
// a metadata ID that old decoders do not recognize (because they would not
// interpret the qmode and would therefore fail the verification).
int WavpackStoreMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
return add_to_metadata (wpc, data, 16, (wpc->config.qmode & 0xff) ? ID_ALT_MD5_CHECKSUM : ID_MD5_CHECKSUM);
}
#pragma pack(push,4)
typedef struct {
char ckID [4];
uint64_t chunkSize64;
} CS64Chunk;
typedef struct {
uint64_t riffSize64, dataSize64, sampleCount64;
uint32_t tableLength;
} DS64Chunk;
typedef struct {
char ckID [4];
uint32_t ckSize;
char junk [28];
} JunkChunk;
#pragma pack(pop)
#define DS64ChunkFormat "DDDL"
static int create_riff_header (WavpackContext *wpc, int64_t total_samples, void *outbuffer)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
char *outptr = outbuffer;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
int64_t total_data_bytes, total_riff_bytes;
int32_t channel_mask = wpc->config.channel_mask;
int32_t sample_rate = wpc->config.sample_rate;
int bytes_per_sample = wpc->config.bytes_per_sample;
int bits_per_sample = wpc->config.bits_per_sample;
int format = (wpc->config.float_norm_exp) ? 3 : 1;
int num_channels = wpc->config.num_channels;
int wavhdrsize = 16;
wpc->riff_header_created = TRUE;
if (format == 3 && wpc->config.float_norm_exp != 127) {
strcpy (wpc->error_message, "can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
write_junk = 0;
do_rf64 = 1;
}
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + total_data_bytes + wpc->riff_trailer_bytes;
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
// write the RIFF chunks up to just before the data starts
outptr = (char *) memcpy (outptr, &riffhdr, sizeof (riffhdr)) + sizeof (riffhdr);
if (do_rf64) {
outptr = (char *) memcpy (outptr, &ds64hdr, sizeof (ds64hdr)) + sizeof (ds64hdr);
outptr = (char *) memcpy (outptr, &ds64_chunk, sizeof (ds64_chunk)) + sizeof (ds64_chunk);
}
if (write_junk)
outptr = (char *) memcpy (outptr, &junkchunk, sizeof (junkchunk)) + sizeof (junkchunk);
outptr = (char *) memcpy (outptr, &fmthdr, sizeof (fmthdr)) + sizeof (fmthdr);
outptr = (char *) memcpy (outptr, &wavhdr, wavhdrsize) + wavhdrsize;
outptr = (char *) memcpy (outptr, &datahdr, sizeof (datahdr)) + sizeof (datahdr);
return (int)(outptr - (char *) outbuffer);
}
static int block_add_checksum (unsigned char *buffer_start, unsigned char *buffer_end, int bytes);
static int pack_streams (WavpackContext *wpc, uint32_t block_samples)
{
uint32_t max_blocksize, max_chans = 1, bcount;
unsigned char *outbuff, *outend, *out2buff, *out2end;
int result = TRUE, i;
// for calculating output (block) buffer size, first see if any streams are stereo
for (i = 0; i < wpc->num_streams; i++)
if (!(wpc->streams [i]->wphdr.flags & MONO_FLAG)) {
max_chans = 2;
break;
}
// then calculate maximum size based on bytes / sample
max_blocksize = block_samples * max_chans * ((wpc->streams [0]->wphdr.flags & BYTES_STORED) + 1);
// add margin based on how much "negative" compression is possible with pathological audio
if ((wpc->config.flags & CONFIG_FLOAT_DATA) && !(wpc->config.flags & CONFIG_SKIP_WVX))
max_blocksize += max_blocksize; // 100% margin for lossless float data
else
max_blocksize += max_blocksize >> 2; // otherwise 25% margin for everything else
max_blocksize += wpc->metabytes + 1024; // finally, add metadata & another 1K margin
out2buff = (wpc->wvc_flag) ? malloc (max_blocksize) : NULL;
out2end = out2buff + max_blocksize;
outbuff = malloc (max_blocksize);
outend = outbuff + max_blocksize;
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
uint32_t flags = wps->wphdr.flags;
flags &= ~MAG_MASK;
flags += (1 << MAG_LSB) * ((flags & BYTES_STORED) * 8 + 7);
SET_BLOCK_INDEX (wps->wphdr, wps->sample_index);
wps->wphdr.block_samples = block_samples;
wps->wphdr.flags = flags;
wps->block2buff = out2buff;
wps->block2end = out2end;
wps->blockbuff = outbuff;
wps->blockend = outend;
#ifdef ENABLE_DSD
if (flags & DSD_FLAG)
result = pack_dsd_block (wpc, wps->sample_buffer);
else
#endif
result = pack_block (wpc, wps->sample_buffer);
if (result) {
result = block_add_checksum (outbuff, outend, (flags & HYBRID_FLAG) ? 2 : 4);
if (result && out2buff)
result = block_add_checksum (out2buff, out2end, 2);
}
wps->blockbuff = wps->block2buff = NULL;
if (wps->wphdr.block_samples != block_samples)
block_samples = wps->wphdr.block_samples;
if (!result) {
strcpy (wpc->error_message, "output buffer overflowed!");
break;
}
bcount = ((WavpackHeader *) outbuff)->ckSize + 8;
WavpackNativeToLittleEndian ((WavpackHeader *) outbuff, WavpackHeaderFormat);
result = wpc->blockout (wpc->wv_out, outbuff, bcount);
if (!result) {
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
break;
}
wpc->filelen += bcount;
if (out2buff) {
bcount = ((WavpackHeader *) out2buff)->ckSize + 8;
WavpackNativeToLittleEndian ((WavpackHeader *) out2buff, WavpackHeaderFormat);
result = wpc->blockout (wpc->wvc_out, out2buff, bcount);
if (!result) {
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
break;
}
wpc->file2len += bcount;
}
if (wpc->acc_samples != block_samples)
memmove (wps->sample_buffer, wps->sample_buffer + block_samples * (flags & MONO_FLAG ? 1 : 2),
(wpc->acc_samples - block_samples) * sizeof (int32_t) * (flags & MONO_FLAG ? 1 : 2));
}
wpc->current_stream = 0;
wpc->ave_block_samples = (wpc->ave_block_samples * 0x7 + block_samples + 0x4) >> 3;
wpc->acc_samples -= block_samples;
free (outbuff);
if (out2buff)
free (out2buff);
return result;
}
// Given the pointer to the first block written (to either a .wv or .wvc file),
// update the block with the actual number of samples written. If the wav
// header was generated by the library, then it is updated also. This should
// be done if WavpackSetConfiguration() was called with an incorrect number
// of samples (or -1). It is the responsibility of the application to read and
// rewrite the block. An example of this can be found in the Audition filter.
static void block_update_checksum (unsigned char *buffer_start);
void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block)
{
uint32_t wrapper_size;
WavpackLittleEndianToNative (first_block, WavpackHeaderFormat);
SET_TOTAL_SAMPLES (* (WavpackHeader *) first_block, WavpackGetSampleIndex64 (wpc));
if (wpc->riff_header_created && WavpackGetWrapperLocation (first_block, &wrapper_size)) {
unsigned char riff_header [128];
if (wrapper_size == create_riff_header (wpc, WavpackGetSampleIndex64 (wpc), riff_header))
memcpy (WavpackGetWrapperLocation (first_block, NULL), riff_header, wrapper_size);
}
block_update_checksum (first_block);
WavpackNativeToLittleEndian (first_block, WavpackHeaderFormat);
}
// Note: The following function is no longer required because the wav header
// automatically generated for the application will also be updated by
// WavpackUpdateNumSamples (). However, if the application wants to generate
// its own header or wants to include additional chunks, then this function
// still must be used to update the application generated header.
// Given the pointer to the first block written to a WavPack file, this
// function returns the location of the stored RIFF header that was originally
// written with WavpackAddWrapper(). This would normally be used to update
// the wav header to indicate that a different number of samples was actually
// written or if additional RIFF chunks are written at the end of the file.
// The "size" parameter can be set to non-NULL to obtain the exact size of the
// RIFF header, and the function will return FALSE if the header is not found
// in the block's metadata (or it is not a valid WavPack block). It is the
// responsibility of the application to read and rewrite the block. An example
// of this can be found in the Audition filter.
static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size);
void *WavpackGetWrapperLocation (void *first_block, uint32_t *size)
{
void *loc;
WavpackLittleEndianToNative (first_block, WavpackHeaderFormat);
loc = find_metadata (first_block, ID_RIFF_HEADER, size);
if (!loc)
loc = find_metadata (first_block, ID_ALT_HEADER, size);
WavpackNativeToLittleEndian (first_block, WavpackHeaderFormat);
return loc;
}
static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size)
{
WavpackHeader *wphdr = wavpack_block;
unsigned char *dp, meta_id, c1, c2;
int32_t bcount, meta_bc;
if (strncmp (wphdr->ckID, "wvpk", 4))
return NULL;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
break;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if ((meta_id & ID_UNIQUE) == desired_id) {
if ((bcount - meta_bc) >= 0) {
if (size)
*size = meta_bc - ((meta_id & ID_ODD_SIZE) ? 1 : 0);
return dp;
}
else
return NULL;
}
bcount -= meta_bc;
dp += meta_bc;
}
return NULL;
}
int copy_metadata (WavpackMetadata *wpmd, unsigned char *buffer_start, unsigned char *buffer_end)
{
uint32_t mdsize = wpmd->byte_length + (wpmd->byte_length & 1);
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
mdsize += (wpmd->byte_length > 510) ? 4 : 2;
buffer_start += wphdr->ckSize + 8;
if (buffer_start + mdsize >= buffer_end)
return FALSE;
buffer_start [0] = wpmd->id | (wpmd->byte_length & 1 ? ID_ODD_SIZE : 0);
buffer_start [1] = (wpmd->byte_length + 1) >> 1;
if (wpmd->byte_length > 510) {
buffer_start [0] |= ID_LARGE;
buffer_start [2] = (wpmd->byte_length + 1) >> 9;
buffer_start [3] = (wpmd->byte_length + 1) >> 17;
}
if (wpmd->data && wpmd->byte_length) {
memcpy (buffer_start + (wpmd->byte_length > 510 ? 4 : 2), wpmd->data, wpmd->byte_length);
if (wpmd->byte_length & 1) // if size is odd, make sure pad byte is a zero
buffer_start [mdsize - 1] = 0;
}
wphdr->ckSize += mdsize;
return TRUE;
}
static int add_to_metadata (WavpackContext *wpc, void *data, uint32_t bcount, unsigned char id)
{
WavpackMetadata *mdp;
unsigned char *src = data;
while (bcount) {
if (wpc->metacount) {
uint32_t bc = bcount;
mdp = wpc->metadata + wpc->metacount - 1;
if (mdp->id == id) {
if (wpc->metabytes + bcount > 1000000)
bc = 1000000 - wpc->metabytes;
mdp->data = realloc (mdp->data, mdp->byte_length + bc);
memcpy ((char *) mdp->data + mdp->byte_length, src, bc);
mdp->byte_length += bc;
wpc->metabytes += bc;
bcount -= bc;
src += bc;
if (wpc->metabytes >= 1000000 && !write_metadata_block (wpc))
return FALSE;
}
}
if (bcount) {
wpc->metadata = realloc (wpc->metadata, (wpc->metacount + 1) * sizeof (WavpackMetadata));
mdp = wpc->metadata + wpc->metacount++;
mdp->byte_length = 0;
mdp->data = NULL;
mdp->id = id;
}
}
return TRUE;
}
static char *write_metadata (WavpackMetadata *wpmd, char *outdata)
{
unsigned char id = wpmd->id, wordlen [3];
wordlen [0] = (wpmd->byte_length + 1) >> 1;
wordlen [1] = (wpmd->byte_length + 1) >> 9;
wordlen [2] = (wpmd->byte_length + 1) >> 17;
if (wpmd->byte_length & 1)
id |= ID_ODD_SIZE;
if (wordlen [1] || wordlen [2])
id |= ID_LARGE;
*outdata++ = id;
*outdata++ = wordlen [0];
if (id & ID_LARGE) {
*outdata++ = wordlen [1];
*outdata++ = wordlen [2];
}
if (wpmd->data && wpmd->byte_length) {
memcpy (outdata, wpmd->data, wpmd->byte_length);
outdata += wpmd->byte_length;
if (wpmd->byte_length & 1)
*outdata++ = 0;
}
return outdata;
}
static int write_metadata_block (WavpackContext *wpc)
{
char *block_buff, *block_ptr;
WavpackHeader *wphdr;
if (wpc->metacount) {
int metacount = wpc->metacount, block_size = sizeof (WavpackHeader);
WavpackMetadata *wpmdp = wpc->metadata;
while (metacount--) {
block_size += wpmdp->byte_length + (wpmdp->byte_length & 1);
block_size += (wpmdp->byte_length > 510) ? 4 : 2;
wpmdp++;
}
// allocate 6 extra bytes for 4-byte checksum (which we add last)
wphdr = (WavpackHeader *) (block_buff = malloc (block_size + 6));
CLEAR (*wphdr);
memcpy (wphdr->ckID, "wvpk", 4);
SET_TOTAL_SAMPLES (*wphdr, wpc->total_samples);
wphdr->version = wpc->stream_version;
wphdr->ckSize = block_size - 8;
wphdr->block_samples = 0;
block_ptr = (char *)(wphdr + 1);
wpmdp = wpc->metadata;
while (wpc->metacount) {
block_ptr = write_metadata (wpmdp, block_ptr);
wpc->metabytes -= wpmdp->byte_length;
free_metadata (wpmdp++);
wpc->metacount--;
}
free (wpc->metadata);
wpc->metadata = NULL;
// add a 4-byte checksum here (increases block size by 6)
block_add_checksum ((unsigned char *) block_buff, (unsigned char *) block_buff + (block_size += 6), 4);
WavpackNativeToLittleEndian ((WavpackHeader *) block_buff, WavpackHeaderFormat);
if (!wpc->blockout (wpc->wv_out, block_buff, block_size)) {
free (block_buff);
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
return FALSE;
}
free (block_buff);
}
return TRUE;
}
void free_metadata (WavpackMetadata *wpmd)
{
if (wpmd->data) {
free (wpmd->data);
wpmd->data = NULL;
}
}
// These two functions add or update the block checksums that were introduced in WavPack 5.0.
// The presence of the checksum is indicated by a flag in the wavpack header (HAS_CHECKSUM)
// and the actual metadata item should be the last one in the block, and can be either 2 or 4
// bytes. Of course, older versions of the decoder will simply ignore both of these.
static int block_add_checksum (unsigned char *buffer_start, unsigned char *buffer_end, int bytes)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer_start;
#else
unsigned char *csptr = buffer_start;
#endif
int bcount = wphdr->ckSize + 8, wcount;
uint32_t csum = (uint32_t) -1;
if (bytes != 2 && bytes != 4)
return FALSE;
if (bcount < sizeof (WavpackHeader) || (bcount & 1) || buffer_start + bcount + 2 + bytes > buffer_end)
return FALSE;
wphdr->flags |= HAS_CHECKSUM;
wphdr->ckSize += 2 + bytes;
wcount = bcount >> 1;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
#endif
buffer_start += bcount;
*buffer_start++ = ID_BLOCK_CHECKSUM;
*buffer_start++ = bytes >> 1;
if (bytes == 4) {
*buffer_start++ = csum;
*buffer_start++ = csum >> 8;
*buffer_start++ = csum >> 16;
*buffer_start++ = csum >> 24;
}
else {
csum ^= csum >> 16;
*buffer_start++ = csum;
*buffer_start++ = csum >> 8;
}
return TRUE;
}
static void block_update_checksum (unsigned char *buffer_start)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
unsigned char *dp, meta_id, c1, c2;
uint32_t bcount, meta_bc;
if (!(wphdr->flags & HAS_CHECKSUM))
return;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return;
if ((meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer_start;
#else
unsigned char *csptr = buffer_start;
#endif
int wcount = (int)(dp - 2 - buffer_start) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
*dp++ = csum;
*dp++ = csum >> 8;
*dp++ = csum >> 16;
*dp++ = csum >> 24;
return;
}
else {
csum ^= csum >> 16;
*dp++ = csum;
*dp++ = csum >> 8;
return;
}
}
bcount -= meta_bc;
dp += meta_bc;
}
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_456_0 |
crossvul-cpp_data_bad_3016_0 | // SPDX-License-Identifier: GPL-2.0
/*
* linux/mm/madvise.c
*
* Copyright (C) 1999 Linus Torvalds
* Copyright (C) 2002 Christoph Hellwig
*/
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/syscalls.h>
#include <linux/mempolicy.h>
#include <linux/page-isolation.h>
#include <linux/userfaultfd_k.h>
#include <linux/hugetlb.h>
#include <linux/falloc.h>
#include <linux/sched.h>
#include <linux/ksm.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/shmem_fs.h>
#include <linux/mmu_notifier.h>
#include <asm/tlb.h>
#include "internal.h"
/*
* Any behaviour which results in changes to the vma->vm_flags needs to
* take mmap_sem for writing. Others, which simply traverse vmas, need
* to only take it for reading.
*/
static int madvise_need_mmap_write(int behavior)
{
switch (behavior) {
case MADV_REMOVE:
case MADV_WILLNEED:
case MADV_DONTNEED:
case MADV_FREE:
return 0;
default:
/* be safe, default to 1. list exceptions explicitly */
return 1;
}
}
/*
* We can potentially split a vm area into separate
* areas, each area with its own behavior.
*/
static long madvise_behavior(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end, int behavior)
{
struct mm_struct *mm = vma->vm_mm;
int error = 0;
pgoff_t pgoff;
unsigned long new_flags = vma->vm_flags;
switch (behavior) {
case MADV_NORMAL:
new_flags = new_flags & ~VM_RAND_READ & ~VM_SEQ_READ;
break;
case MADV_SEQUENTIAL:
new_flags = (new_flags & ~VM_RAND_READ) | VM_SEQ_READ;
break;
case MADV_RANDOM:
new_flags = (new_flags & ~VM_SEQ_READ) | VM_RAND_READ;
break;
case MADV_DONTFORK:
new_flags |= VM_DONTCOPY;
break;
case MADV_DOFORK:
if (vma->vm_flags & VM_IO) {
error = -EINVAL;
goto out;
}
new_flags &= ~VM_DONTCOPY;
break;
case MADV_WIPEONFORK:
/* MADV_WIPEONFORK is only supported on anonymous memory. */
if (vma->vm_file || vma->vm_flags & VM_SHARED) {
error = -EINVAL;
goto out;
}
new_flags |= VM_WIPEONFORK;
break;
case MADV_KEEPONFORK:
new_flags &= ~VM_WIPEONFORK;
break;
case MADV_DONTDUMP:
new_flags |= VM_DONTDUMP;
break;
case MADV_DODUMP:
if (new_flags & VM_SPECIAL) {
error = -EINVAL;
goto out;
}
new_flags &= ~VM_DONTDUMP;
break;
case MADV_MERGEABLE:
case MADV_UNMERGEABLE:
error = ksm_madvise(vma, start, end, behavior, &new_flags);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
break;
case MADV_HUGEPAGE:
case MADV_NOHUGEPAGE:
error = hugepage_madvise(vma, &new_flags, behavior);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
break;
}
if (new_flags == vma->vm_flags) {
*prev = vma;
goto out;
}
pgoff = vma->vm_pgoff + ((start - vma->vm_start) >> PAGE_SHIFT);
*prev = vma_merge(mm, *prev, start, end, new_flags, vma->anon_vma,
vma->vm_file, pgoff, vma_policy(vma),
vma->vm_userfaultfd_ctx);
if (*prev) {
vma = *prev;
goto success;
}
*prev = vma;
if (start != vma->vm_start) {
if (unlikely(mm->map_count >= sysctl_max_map_count)) {
error = -ENOMEM;
goto out;
}
error = __split_vma(mm, vma, start, 1);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
}
if (end != vma->vm_end) {
if (unlikely(mm->map_count >= sysctl_max_map_count)) {
error = -ENOMEM;
goto out;
}
error = __split_vma(mm, vma, end, 0);
if (error) {
/*
* madvise() returns EAGAIN if kernel resources, such as
* slab, are temporarily unavailable.
*/
if (error == -ENOMEM)
error = -EAGAIN;
goto out;
}
}
success:
/*
* vm_flags is protected by the mmap_sem held in write mode.
*/
vma->vm_flags = new_flags;
out:
return error;
}
#ifdef CONFIG_SWAP
static int swapin_walk_pmd_entry(pmd_t *pmd, unsigned long start,
unsigned long end, struct mm_walk *walk)
{
pte_t *orig_pte;
struct vm_area_struct *vma = walk->private;
unsigned long index;
if (pmd_none_or_trans_huge_or_clear_bad(pmd))
return 0;
for (index = start; index != end; index += PAGE_SIZE) {
pte_t pte;
swp_entry_t entry;
struct page *page;
spinlock_t *ptl;
orig_pte = pte_offset_map_lock(vma->vm_mm, pmd, start, &ptl);
pte = *(orig_pte + ((index - start) / PAGE_SIZE));
pte_unmap_unlock(orig_pte, ptl);
if (pte_present(pte) || pte_none(pte))
continue;
entry = pte_to_swp_entry(pte);
if (unlikely(non_swap_entry(entry)))
continue;
page = read_swap_cache_async(entry, GFP_HIGHUSER_MOVABLE,
vma, index, false);
if (page)
put_page(page);
}
return 0;
}
static void force_swapin_readahead(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
struct mm_walk walk = {
.mm = vma->vm_mm,
.pmd_entry = swapin_walk_pmd_entry,
.private = vma,
};
walk_page_range(start, end, &walk);
lru_add_drain(); /* Push any new pages onto the LRU now */
}
static void force_shm_swapin_readahead(struct vm_area_struct *vma,
unsigned long start, unsigned long end,
struct address_space *mapping)
{
pgoff_t index;
struct page *page;
swp_entry_t swap;
for (; start < end; start += PAGE_SIZE) {
index = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
page = find_get_entry(mapping, index);
if (!radix_tree_exceptional_entry(page)) {
if (page)
put_page(page);
continue;
}
swap = radix_to_swp_entry(page);
page = read_swap_cache_async(swap, GFP_HIGHUSER_MOVABLE,
NULL, 0, false);
if (page)
put_page(page);
}
lru_add_drain(); /* Push any new pages onto the LRU now */
}
#endif /* CONFIG_SWAP */
/*
* Schedule all required I/O operations. Do not wait for completion.
*/
static long madvise_willneed(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
struct file *file = vma->vm_file;
#ifdef CONFIG_SWAP
if (!file) {
*prev = vma;
force_swapin_readahead(vma, start, end);
return 0;
}
if (shmem_mapping(file->f_mapping)) {
*prev = vma;
force_shm_swapin_readahead(vma, start, end,
file->f_mapping);
return 0;
}
#else
if (!file)
return -EBADF;
#endif
if (IS_DAX(file_inode(file))) {
/* no bad return value, but ignore advice */
return 0;
}
*prev = vma;
start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
if (end > vma->vm_end)
end = vma->vm_end;
end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
force_page_cache_readahead(file->f_mapping, file, start, end - start);
return 0;
}
static int madvise_free_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct mmu_gather *tlb = walk->private;
struct mm_struct *mm = tlb->mm;
struct vm_area_struct *vma = walk->vma;
spinlock_t *ptl;
pte_t *orig_pte, *pte, ptent;
struct page *page;
int nr_swap = 0;
unsigned long next;
next = pmd_addr_end(addr, end);
if (pmd_trans_huge(*pmd))
if (madvise_free_huge_pmd(tlb, vma, pmd, addr, next))
goto next;
if (pmd_trans_unstable(pmd))
return 0;
tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
orig_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
flush_tlb_batched_pending(mm);
arch_enter_lazy_mmu_mode();
for (; addr != end; pte++, addr += PAGE_SIZE) {
ptent = *pte;
if (pte_none(ptent))
continue;
/*
* If the pte has swp_entry, just clear page table to
* prevent swap-in which is more expensive rather than
* (page allocation + zeroing).
*/
if (!pte_present(ptent)) {
swp_entry_t entry;
entry = pte_to_swp_entry(ptent);
if (non_swap_entry(entry))
continue;
nr_swap--;
free_swap_and_cache(entry);
pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
continue;
}
page = _vm_normal_page(vma, addr, ptent, true);
if (!page)
continue;
/*
* If pmd isn't transhuge but the page is THP and
* is owned by only this process, split it and
* deactivate all pages.
*/
if (PageTransCompound(page)) {
if (page_mapcount(page) != 1)
goto out;
get_page(page);
if (!trylock_page(page)) {
put_page(page);
goto out;
}
pte_unmap_unlock(orig_pte, ptl);
if (split_huge_page(page)) {
unlock_page(page);
put_page(page);
pte_offset_map_lock(mm, pmd, addr, &ptl);
goto out;
}
unlock_page(page);
put_page(page);
pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
pte--;
addr -= PAGE_SIZE;
continue;
}
VM_BUG_ON_PAGE(PageTransCompound(page), page);
if (PageSwapCache(page) || PageDirty(page)) {
if (!trylock_page(page))
continue;
/*
* If page is shared with others, we couldn't clear
* PG_dirty of the page.
*/
if (page_mapcount(page) != 1) {
unlock_page(page);
continue;
}
if (PageSwapCache(page) && !try_to_free_swap(page)) {
unlock_page(page);
continue;
}
ClearPageDirty(page);
unlock_page(page);
}
if (pte_young(ptent) || pte_dirty(ptent)) {
/*
* Some of architecture(ex, PPC) don't update TLB
* with set_pte_at and tlb_remove_tlb_entry so for
* the portability, remap the pte with old|clean
* after pte clearing.
*/
ptent = ptep_get_and_clear_full(mm, addr, pte,
tlb->fullmm);
ptent = pte_mkold(ptent);
ptent = pte_mkclean(ptent);
set_pte_at(mm, addr, pte, ptent);
tlb_remove_tlb_entry(tlb, pte, addr);
}
mark_page_lazyfree(page);
}
out:
if (nr_swap) {
if (current->mm == mm)
sync_mm_rss(mm);
add_mm_counter(mm, MM_SWAPENTS, nr_swap);
}
arch_leave_lazy_mmu_mode();
pte_unmap_unlock(orig_pte, ptl);
cond_resched();
next:
return 0;
}
static void madvise_free_page_range(struct mmu_gather *tlb,
struct vm_area_struct *vma,
unsigned long addr, unsigned long end)
{
struct mm_walk free_walk = {
.pmd_entry = madvise_free_pte_range,
.mm = vma->vm_mm,
.private = tlb,
};
tlb_start_vma(tlb, vma);
walk_page_range(addr, end, &free_walk);
tlb_end_vma(tlb, vma);
}
static int madvise_free_single_vma(struct vm_area_struct *vma,
unsigned long start_addr, unsigned long end_addr)
{
unsigned long start, end;
struct mm_struct *mm = vma->vm_mm;
struct mmu_gather tlb;
/* MADV_FREE works for only anon vma at the moment */
if (!vma_is_anonymous(vma))
return -EINVAL;
start = max(vma->vm_start, start_addr);
if (start >= vma->vm_end)
return -EINVAL;
end = min(vma->vm_end, end_addr);
if (end <= vma->vm_start)
return -EINVAL;
lru_add_drain();
tlb_gather_mmu(&tlb, mm, start, end);
update_hiwater_rss(mm);
mmu_notifier_invalidate_range_start(mm, start, end);
madvise_free_page_range(&tlb, vma, start, end);
mmu_notifier_invalidate_range_end(mm, start, end);
tlb_finish_mmu(&tlb, start, end);
return 0;
}
/*
* Application no longer needs these pages. If the pages are dirty,
* it's OK to just throw them away. The app will be more careful about
* data it wants to keep. Be sure to free swap resources too. The
* zap_page_range call sets things up for shrink_active_list to actually free
* these pages later if no one else has touched them in the meantime,
* although we could add these pages to a global reuse list for
* shrink_active_list to pick up before reclaiming other pages.
*
* NB: This interface discards data rather than pushes it out to swap,
* as some implementations do. This has performance implications for
* applications like large transactional databases which want to discard
* pages in anonymous maps after committing to backing store the data
* that was kept in them. There is no reason to write this data out to
* the swap area if the application is discarding it.
*
* An interface that causes the system to free clean pages and flush
* dirty pages is already available as msync(MS_INVALIDATE).
*/
static long madvise_dontneed_single_vma(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
zap_page_range(vma, start, end - start);
return 0;
}
static long madvise_dontneed_free(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end,
int behavior)
{
*prev = vma;
if (!can_madv_dontneed_vma(vma))
return -EINVAL;
if (!userfaultfd_remove(vma, start, end)) {
*prev = NULL; /* mmap_sem has been dropped, prev is stale */
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, start);
if (!vma)
return -ENOMEM;
if (start < vma->vm_start) {
/*
* This "vma" under revalidation is the one
* with the lowest vma->vm_start where start
* is also < vma->vm_end. If start <
* vma->vm_start it means an hole materialized
* in the user address space within the
* virtual range passed to MADV_DONTNEED
* or MADV_FREE.
*/
return -ENOMEM;
}
if (!can_madv_dontneed_vma(vma))
return -EINVAL;
if (end > vma->vm_end) {
/*
* Don't fail if end > vma->vm_end. If the old
* vma was splitted while the mmap_sem was
* released the effect of the concurrent
* operation may not cause madvise() to
* have an undefined result. There may be an
* adjacent next vma that we'll walk
* next. userfaultfd_remove() will generate an
* UFFD_EVENT_REMOVE repetition on the
* end-vma->vm_end range, but the manager can
* handle a repetition fine.
*/
end = vma->vm_end;
}
VM_WARN_ON(start >= end);
}
if (behavior == MADV_DONTNEED)
return madvise_dontneed_single_vma(vma, start, end);
else if (behavior == MADV_FREE)
return madvise_free_single_vma(vma, start, end);
else
return -EINVAL;
}
/*
* Application wants to free up the pages and associated backing store.
* This is effectively punching a hole into the middle of a file.
*/
static long madvise_remove(struct vm_area_struct *vma,
struct vm_area_struct **prev,
unsigned long start, unsigned long end)
{
loff_t offset;
int error;
struct file *f;
*prev = NULL; /* tell sys_madvise we drop mmap_sem */
if (vma->vm_flags & VM_LOCKED)
return -EINVAL;
f = vma->vm_file;
if (!f || !f->f_mapping || !f->f_mapping->host) {
return -EINVAL;
}
if ((vma->vm_flags & (VM_SHARED|VM_WRITE)) != (VM_SHARED|VM_WRITE))
return -EACCES;
offset = (loff_t)(start - vma->vm_start)
+ ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
/*
* Filesystem's fallocate may need to take i_mutex. We need to
* explicitly grab a reference because the vma (and hence the
* vma's reference to the file) can go away as soon as we drop
* mmap_sem.
*/
get_file(f);
if (userfaultfd_remove(vma, start, end)) {
/* mmap_sem was not released by userfaultfd_remove() */
up_read(¤t->mm->mmap_sem);
}
error = vfs_fallocate(f,
FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
offset, end - start);
fput(f);
down_read(¤t->mm->mmap_sem);
return error;
}
#ifdef CONFIG_MEMORY_FAILURE
/*
* Error injection support for memory error handling.
*/
static int madvise_inject_error(int behavior,
unsigned long start, unsigned long end)
{
struct page *page;
struct zone *zone;
unsigned int order;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
for (; start < end; start += PAGE_SIZE << order) {
int ret;
ret = get_user_pages_fast(start, 1, 0, &page);
if (ret != 1)
return ret;
/*
* When soft offlining hugepages, after migrating the page
* we dissolve it, therefore in the second loop "page" will
* no longer be a compound page, and order will be 0.
*/
order = compound_order(compound_head(page));
if (PageHWPoison(page)) {
put_page(page);
continue;
}
if (behavior == MADV_SOFT_OFFLINE) {
pr_info("Soft offlining pfn %#lx at process virtual address %#lx\n",
page_to_pfn(page), start);
ret = soft_offline_page(page, MF_COUNT_INCREASED);
if (ret)
return ret;
continue;
}
pr_info("Injecting memory failure for pfn %#lx at process virtual address %#lx\n",
page_to_pfn(page), start);
ret = memory_failure(page_to_pfn(page), 0, MF_COUNT_INCREASED);
if (ret)
return ret;
}
/* Ensure that all poisoned pages are removed from per-cpu lists */
for_each_populated_zone(zone)
drain_all_pages(zone);
return 0;
}
#endif
static long
madvise_vma(struct vm_area_struct *vma, struct vm_area_struct **prev,
unsigned long start, unsigned long end, int behavior)
{
switch (behavior) {
case MADV_REMOVE:
return madvise_remove(vma, prev, start, end);
case MADV_WILLNEED:
return madvise_willneed(vma, prev, start, end);
case MADV_FREE:
case MADV_DONTNEED:
return madvise_dontneed_free(vma, prev, start, end, behavior);
default:
return madvise_behavior(vma, prev, start, end, behavior);
}
}
static bool
madvise_behavior_valid(int behavior)
{
switch (behavior) {
case MADV_DOFORK:
case MADV_DONTFORK:
case MADV_NORMAL:
case MADV_SEQUENTIAL:
case MADV_RANDOM:
case MADV_REMOVE:
case MADV_WILLNEED:
case MADV_DONTNEED:
case MADV_FREE:
#ifdef CONFIG_KSM
case MADV_MERGEABLE:
case MADV_UNMERGEABLE:
#endif
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
case MADV_HUGEPAGE:
case MADV_NOHUGEPAGE:
#endif
case MADV_DONTDUMP:
case MADV_DODUMP:
case MADV_WIPEONFORK:
case MADV_KEEPONFORK:
#ifdef CONFIG_MEMORY_FAILURE
case MADV_SOFT_OFFLINE:
case MADV_HWPOISON:
#endif
return true;
default:
return false;
}
}
/*
* The madvise(2) system call.
*
* Applications can use madvise() to advise the kernel how it should
* handle paging I/O in this VM area. The idea is to help the kernel
* use appropriate read-ahead and caching techniques. The information
* provided is advisory only, and can be safely disregarded by the
* kernel without affecting the correct operation of the application.
*
* behavior values:
* MADV_NORMAL - the default behavior is to read clusters. This
* results in some read-ahead and read-behind.
* MADV_RANDOM - the system should read the minimum amount of data
* on any access, since it is unlikely that the appli-
* cation will need more than what it asks for.
* MADV_SEQUENTIAL - pages in the given range will probably be accessed
* once, so they can be aggressively read ahead, and
* can be freed soon after they are accessed.
* MADV_WILLNEED - the application is notifying the system to read
* some pages ahead.
* MADV_DONTNEED - the application is finished with the given range,
* so the kernel can free resources associated with it.
* MADV_FREE - the application marks pages in the given range as lazy free,
* where actual purges are postponed until memory pressure happens.
* MADV_REMOVE - the application wants to free up the given range of
* pages and associated backing store.
* MADV_DONTFORK - omit this area from child's address space when forking:
* typically, to avoid COWing pages pinned by get_user_pages().
* MADV_DOFORK - cancel MADV_DONTFORK: no longer omit this area when forking.
* MADV_WIPEONFORK - present the child process with zero-filled memory in this
* range after a fork.
* MADV_KEEPONFORK - undo the effect of MADV_WIPEONFORK
* MADV_HWPOISON - trigger memory error handler as if the given memory range
* were corrupted by unrecoverable hardware memory failure.
* MADV_SOFT_OFFLINE - try to soft-offline the given range of memory.
* MADV_MERGEABLE - the application recommends that KSM try to merge pages in
* this area with pages of identical content from other such areas.
* MADV_UNMERGEABLE- cancel MADV_MERGEABLE: no longer merge pages with others.
* MADV_HUGEPAGE - the application wants to back the given range by transparent
* huge pages in the future. Existing pages might be coalesced and
* new pages might be allocated as THP.
* MADV_NOHUGEPAGE - mark the given range as not worth being backed by
* transparent huge pages so the existing pages will not be
* coalesced into THP and new pages will not be allocated as THP.
* MADV_DONTDUMP - the application wants to prevent pages in the given range
* from being included in its core dump.
* MADV_DODUMP - cancel MADV_DONTDUMP: no longer exclude from core dump.
*
* return values:
* zero - success
* -EINVAL - start + len < 0, start is not page-aligned,
* "behavior" is not a valid value, or application
* is attempting to release locked or shared pages,
* or the specified address range includes file, Huge TLB,
* MAP_SHARED or VMPFNMAP range.
* -ENOMEM - addresses in the specified range are not currently
* mapped, or are outside the AS of the process.
* -EIO - an I/O error occurred while paging in data.
* -EBADF - map exists, but area maps something that isn't a file.
* -EAGAIN - a kernel resource was temporarily unavailable.
*/
SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
{
unsigned long end, tmp;
struct vm_area_struct *vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
int write;
size_t len;
struct blk_plug plug;
if (!madvise_behavior_valid(behavior))
return error;
if (start & ~PAGE_MASK)
return error;
len = (len_in + ~PAGE_MASK) & PAGE_MASK;
/* Check to see whether len was rounded up from small -ve to zero */
if (len_in && !len)
return error;
end = start + len;
if (end < start)
return error;
error = 0;
if (end == start)
return error;
#ifdef CONFIG_MEMORY_FAILURE
if (behavior == MADV_HWPOISON || behavior == MADV_SOFT_OFFLINE)
return madvise_inject_error(behavior, start, start + len_in);
#endif
write = madvise_need_mmap_write(behavior);
if (write) {
if (down_write_killable(¤t->mm->mmap_sem))
return -EINTR;
} else {
down_read(¤t->mm->mmap_sem);
}
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - different from the way of handling in mlock etc.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
blk_start_plug(&plug);
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
goto out;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
goto out;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = madvise_vma(vma, &prev, start, tmp, behavior);
if (error)
goto out;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
goto out;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
out:
blk_finish_plug(&plug);
if (write)
up_write(¤t->mm->mmap_sem);
else
up_read(¤t->mm->mmap_sem);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_3016_0 |
crossvul-cpp_data_bad_456_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2013 Conifer Software. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// pack_utils.c
// This module provides the high-level API for creating WavPack files from
// audio data. It manages the buffers used to deinterleave the data passed
// in from the application into the individual streams and it handles the
// generation of riff headers and the "fixup" on the first WavPack block
// header for the case where the number of samples was unknown (or wrong).
// The actual audio stream compression is handled in the pack.c module.
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "wavpack_local.h"
///////////////////////////// executable code ////////////////////////////////
// Open context for writing WavPack files. The returned context pointer is used
// in all following calls to the library. The "blockout" function will be used
// to store the actual completed WavPack blocks and will be called with the id
// pointers containing user defined data (one for the wv file and one for the
// wvc file). A return value of NULL indicates that memory could not be
// allocated for the context.
WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id)
{
WavpackContext *wpc = malloc (sizeof (WavpackContext));
if (!wpc)
return NULL;
CLEAR (*wpc);
wpc->total_samples = -1;
wpc->stream_version = CUR_STREAM_VERS;
wpc->blockout = blockout;
wpc->wv_out = wv_id;
wpc->wvc_out = wvc_id;
return wpc;
}
static int add_to_metadata (WavpackContext *wpc, void *data, uint32_t bcount, unsigned char id);
// New for version 5.0, this function allows the application to store a file extension and a
// file_format identification. The extension would be used by the unpacker if the user had not
// specified the target filename, and specifically handles the case where the original file
// had the "wrong" extension for the file format (e.g., a Wave64 file having a "wav" extension)
// or an alternative (e.g., "bwf") or where the file format is not known. Specifying a file
// format besides the default WP_FORMAT_WAV will ensure that old decoders will not be able to
// see the non-wav wrapper provided with WavpackAddWrapper() (which they would end up putting
// on a file with a .wav extension).
void WavpackSetFileInformation (WavpackContext *wpc, char *file_extension, unsigned char file_format)
{
if (file_extension && strlen (file_extension) < sizeof (wpc->file_extension)) {
add_to_metadata (wpc, file_extension, (uint32_t) strlen (file_extension), ID_ALT_EXTENSION);
strcpy (wpc->file_extension, file_extension);
}
wpc->file_format = file_format;
}
// Set configuration for writing WavPack files. This must be done before
// sending any actual samples, however it is okay to send wrapper or other
// metadata before calling this. The "config" structure contains the following
// required information:
// config->bytes_per_sample see WavpackGetBytesPerSample() for info
// config->bits_per_sample see WavpackGetBitsPerSample() for info
// config->channel_mask Microsoft standard (mono = 4, stereo = 3)
// config->num_channels self evident
// config->sample_rate self evident
// In addition, the following fields and flags may be set:
// config->flags:
// --------------
// o CONFIG_HYBRID_FLAG select hybrid mode (must set bitrate)
// o CONFIG_JOINT_STEREO select joint stereo (must set override also)
// o CONFIG_JOINT_OVERRIDE override default joint stereo selection
// o CONFIG_HYBRID_SHAPE select hybrid noise shaping (set override &
// shaping_weight != 0.0)
// o CONFIG_SHAPE_OVERRIDE override default hybrid noise shaping
// (set CONFIG_HYBRID_SHAPE and shaping_weight)
// o CONFIG_FAST_FLAG "fast" compression mode
// o CONFIG_HIGH_FLAG "high" compression mode
// o CONFIG_BITRATE_KBPS hybrid bitrate is kbps, not bits / sample
// o CONFIG_CREATE_WVC create correction file
// o CONFIG_OPTIMIZE_WVC maximize bybrid compression (-cc option)
// o CONFIG_CALC_NOISE calc noise in hybrid mode
// o CONFIG_EXTRA_MODE extra processing mode (slow!)
// o CONFIG_SKIP_WVX no wvx stream for floats & large ints
// o CONFIG_MD5_CHECKSUM specify if you plan to store MD5 signature
// o CONFIG_CREATE_EXE specify if you plan to prepend sfx module
// o CONFIG_OPTIMIZE_MONO detect and optimize for mono files posing as
// stereo (uses a more recent stream format that
// is not compatible with decoders < 4.3)
// config->bitrate hybrid bitrate in either bits/sample or kbps
// config->shaping_weight hybrid noise shaping coefficient override
// config->block_samples force samples per WavPack block (0 = use deflt)
// config->float_norm_exp select floating-point data (127 for +/-1.0)
// config->xmode extra mode processing value override
// If the number of samples to be written is known then it should be passed
// here. If the duration is not known then pass -1. In the case that the size
// is not known (or the writing is terminated early) then it is suggested that
// the application retrieve the first block written and let the library update
// the total samples indication. A function is provided to do this update and
// it should be done to the "correction" file also. If this cannot be done
// (because a pipe is being used, for instance) then a valid WavPack will still
// be created, but when applications want to access that file they will have
// to seek all the way to the end to determine the actual duration. Also, if
// a RIFF header has been included then it should be updated as well or the
// WavPack file will not be directly unpackable to a valid wav file (although
// it will still be usable by itself). A return of FALSE indicates an error.
//
// The enhanced version of this function now allows setting the identities of
// any channels that are NOT standard Microsoft channels and are therefore not
// represented in the channel mask. WavPack files require that all the Microsoft
// channels come first (and in Microsoft order) and these are followed by any
// other channels (which can be in any order).
//
// The identities are provided in a NULL-terminated string (0x00 is not an allowed
// channel ID). The Microsoft channels may be provided as well (and will be checked)
// but it is really only necessary to provide the "unknown" channels. Any truly
// unknown channels are indicated with a 0xFF.
//
// The channel IDs so far reserved are listed here:
//
// 0: not allowed / terminator
// 1 - 18: Microsoft standard channels
// 30, 31: Stereo mix from RF64 (not really recommended, but RF64 specifies this)
// 33 - 44: Core Audio channels (see Core Audio specification)
// 127 - 128: Amio LeftHeight, Amio RightHeight
// 138 - 142: Amio BottomFrontLeft/Center/Right, Amio ProximityLeft/Right
// 200 - 207: Core Audio channels (see Core Audio specification)
// 221 - 224: Core Audio channels 301 - 305 (offset by 80)
// 255: Present but unknown or unused channel
//
// All other channel IDs are reserved. Ask if something you need is missing.
// Table of channels that will automatically "pair" into a single stereo stream
static const struct { unsigned char a, b; } stereo_pairs [] = {
{ 1, 2 }, // FL, FR
{ 5, 6 }, // BL, BR
{ 7, 8 }, // FLC, FRC
{ 10, 11 }, // SL, SR
{ 13, 15 }, // TFL, TFR
{ 16, 18 }, // TBL, TBR
{ 30, 31 }, // stereo mix L,R (RF64)
{ 33, 34 }, // Rls, Rrs
{ 35, 36 }, // Lw, Rw
{ 38, 39 }, // Lt, Rt
{ 127, 128 }, // Lh, Rh
{ 138, 140 }, // Bfl, Bfr
{ 141, 142 }, // Pl, Pr
{ 200, 201 }, // Amb_W, Amb_X
{ 202, 203 }, // Amb_Y, Amb_Z
{ 204, 205 }, // MS_Mid, MS_Side
{ 206, 207 }, // XY_X, XY_Y
{ 221, 222 }, // Hph_L, Hph_R
};
#define NUM_STEREO_PAIRS (sizeof (stereo_pairs) / sizeof (stereo_pairs [0]))
// Legacy version of this function for compatibility with existing applications. Note that this version
// also generates older streams to be compatible with all decoders back to 4.0, but of course cannot be
// used with > 2^32 samples or non-Microsoft channels. The older stream version only differs in that it
// does not support the "mono optimization" feature where stereo blocks containing identical audio data
// in both channels are encoded in mono for better efficiency.
int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples)
{
config->flags |= CONFIG_COMPATIBLE_WRITE; // write earlier version streams
if (total_samples == (uint32_t) -1)
return WavpackSetConfiguration64 (wpc, config, -1, NULL);
else
return WavpackSetConfiguration64 (wpc, config, total_samples, NULL);
}
int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids)
{
uint32_t flags, bps = 0;
uint32_t chan_mask = config->channel_mask;
int num_chans = config->num_channels;
int i;
wpc->stream_version = (config->flags & CONFIG_COMPATIBLE_WRITE) ? CUR_STREAM_VERS : MAX_STREAM_VERS;
if ((config->qmode & QMODE_DSD_AUDIO) && config->bytes_per_sample == 1 && config->bits_per_sample == 8) {
#ifdef ENABLE_DSD
wpc->dsd_multiplier = 1;
flags = DSD_FLAG;
for (i = 14; i >= 0; --i)
if (config->sample_rate % sample_rates [i] == 0) {
int divisor = config->sample_rate / sample_rates [i];
if (divisor && (divisor & (divisor - 1)) == 0) {
config->sample_rate /= divisor;
wpc->dsd_multiplier = divisor;
break;
}
}
// most options that don't apply to DSD we can simply ignore for now, but NOT hybrid mode!
if (config->flags & CONFIG_HYBRID_FLAG) {
strcpy (wpc->error_message, "hybrid mode not available for DSD!");
return FALSE;
}
// with DSD, very few PCM options work (or make sense), so only allow those that do
config->flags &= (CONFIG_HIGH_FLAG | CONFIG_MD5_CHECKSUM | CONFIG_PAIR_UNDEF_CHANS);
config->float_norm_exp = config->xmode = 0;
#else
strcpy (wpc->error_message, "libwavpack not configured for DSD!");
return FALSE;
#endif
}
else
flags = config->bytes_per_sample - 1;
wpc->total_samples = total_samples;
wpc->config.sample_rate = config->sample_rate;
wpc->config.num_channels = config->num_channels;
wpc->config.channel_mask = config->channel_mask;
wpc->config.bits_per_sample = config->bits_per_sample;
wpc->config.bytes_per_sample = config->bytes_per_sample;
wpc->config.block_samples = config->block_samples;
wpc->config.flags = config->flags;
wpc->config.qmode = config->qmode;
if (config->flags & CONFIG_VERY_HIGH_FLAG)
wpc->config.flags |= CONFIG_HIGH_FLAG;
for (i = 0; i < 15; ++i)
if (wpc->config.sample_rate == sample_rates [i])
break;
flags |= i << SRATE_LSB;
// all of this stuff only applies to PCM
if (!(flags & DSD_FLAG)) {
if (config->float_norm_exp) {
wpc->config.float_norm_exp = config->float_norm_exp;
wpc->config.flags |= CONFIG_FLOAT_DATA;
flags |= FLOAT_DATA;
}
else
flags |= ((config->bytes_per_sample * 8) - config->bits_per_sample) << SHIFT_LSB;
if (config->flags & CONFIG_HYBRID_FLAG) {
flags |= HYBRID_FLAG | HYBRID_BITRATE | HYBRID_BALANCE;
if (!(wpc->config.flags & CONFIG_SHAPE_OVERRIDE)) {
wpc->config.flags |= CONFIG_HYBRID_SHAPE | CONFIG_AUTO_SHAPING;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
else if (wpc->config.flags & CONFIG_HYBRID_SHAPE) {
wpc->config.shaping_weight = config->shaping_weight;
flags |= HYBRID_SHAPE | NEW_SHAPING;
}
if (wpc->config.flags & (CONFIG_CROSS_DECORR | CONFIG_OPTIMIZE_WVC))
flags |= CROSS_DECORR;
if (config->flags & CONFIG_BITRATE_KBPS) {
bps = (uint32_t) floor (config->bitrate * 256000.0 / config->sample_rate / config->num_channels + 0.5);
if (bps > (64 << 8))
bps = 64 << 8;
}
else
bps = (uint32_t) floor (config->bitrate * 256.0 + 0.5);
}
else
flags |= CROSS_DECORR;
if (!(config->flags & CONFIG_JOINT_OVERRIDE) || (config->flags & CONFIG_JOINT_STEREO))
flags |= JOINT_STEREO;
if (config->flags & CONFIG_CREATE_WVC)
wpc->wvc_flag = TRUE;
}
// if a channel-identities string was specified, process that here, otherwise all channels
// not present in the channel mask are considered "unassigned"
if (chan_ids) {
int lastchan = 0, mask_copy = chan_mask;
if ((int) strlen ((char *) chan_ids) > num_chans) { // can't be more than num channels!
strcpy (wpc->error_message, "chan_ids longer than num channels!");
return FALSE;
}
// skip past channels that are specified in the channel mask (no reason to store those)
while (*chan_ids)
if (*chan_ids <= 32 && *chan_ids > lastchan && (mask_copy & (1 << (*chan_ids-1)))) {
mask_copy &= ~(1 << (*chan_ids-1));
lastchan = *chan_ids++;
}
else
break;
// now scan the string for an actually defined channel (and don't store if there aren't any)
for (i = 0; chan_ids [i]; i++)
if (chan_ids [i] != 0xff) {
wpc->channel_identities = (unsigned char *) strdup ((char *) chan_ids);
break;
}
}
// This loop goes through all the channels and creates the Wavpack "streams" for them to go in.
// A stream can hold either one or two channels, so we have several rules to determine how many
// channels will go in each stream.
for (wpc->current_stream = 0; num_chans; wpc->current_stream++) {
WavpackStream *wps = malloc (sizeof (WavpackStream));
unsigned char left_chan_id = 0, right_chan_id = 0;
int pos, chans = 1;
// allocate the stream and initialize the pointer to it
wpc->streams = realloc (wpc->streams, (wpc->current_stream + 1) * sizeof (wpc->streams [0]));
wpc->streams [wpc->current_stream] = wps;
CLEAR (*wps);
// if there are any bits [still] set in the channel_mask, get the next one or two IDs from there
if (chan_mask)
for (pos = 0; pos < 32; ++pos)
if (chan_mask & (1 << pos)) {
if (left_chan_id) {
right_chan_id = pos + 1;
break;
}
else {
chan_mask &= ~(1 << pos);
left_chan_id = pos + 1;
}
}
// next check for any channels identified in the channel-identities string
while (!right_chan_id && chan_ids && *chan_ids)
if (left_chan_id)
right_chan_id = *chan_ids;
else
left_chan_id = *chan_ids++;
// assume anything we did not get is "unassigned"
if (!left_chan_id)
left_chan_id = right_chan_id = 0xff;
else if (!right_chan_id)
right_chan_id = 0xff;
// if we have 2 channels, this is where we decide if we can combine them into one stream:
// 1. they are "unassigned" and we've been told to combine unassigned pairs, or
// 2. they appear together in the valid "pairings" list
if (num_chans >= 2) {
if ((config->flags & CONFIG_PAIR_UNDEF_CHANS) && left_chan_id == 0xff && right_chan_id == 0xff)
chans = 2;
else
for (i = 0; i < NUM_STEREO_PAIRS; ++i)
if ((left_chan_id == stereo_pairs [i].a && right_chan_id == stereo_pairs [i].b) ||
(left_chan_id == stereo_pairs [i].b && right_chan_id == stereo_pairs [i].a)) {
if (right_chan_id <= 32 && (chan_mask & (1 << (right_chan_id-1))))
chan_mask &= ~(1 << (right_chan_id-1));
else if (chan_ids && *chan_ids == right_chan_id)
chan_ids++;
chans = 2;
break;
}
}
num_chans -= chans;
if (num_chans && wpc->current_stream == NEW_MAX_STREAMS - 1)
break;
memcpy (wps->wphdr.ckID, "wvpk", 4);
wps->wphdr.ckSize = sizeof (WavpackHeader) - 8;
SET_TOTAL_SAMPLES (wps->wphdr, wpc->total_samples);
wps->wphdr.version = wpc->stream_version;
wps->wphdr.flags = flags;
wps->bits = bps;
if (!wpc->current_stream)
wps->wphdr.flags |= INITIAL_BLOCK;
if (!num_chans)
wps->wphdr.flags |= FINAL_BLOCK;
if (chans == 1) {
wps->wphdr.flags &= ~(JOINT_STEREO | CROSS_DECORR | HYBRID_BALANCE);
wps->wphdr.flags |= MONO_FLAG;
}
}
wpc->num_streams = wpc->current_stream;
wpc->current_stream = 0;
if (num_chans) {
strcpy (wpc->error_message, "too many channels!");
return FALSE;
}
if (config->flags & CONFIG_EXTRA_MODE)
wpc->config.xmode = config->xmode ? config->xmode : 1;
return TRUE;
}
// This function allows setting the Core Audio File channel layout, many of which do not
// conform to the Microsoft ordering standard that Wavpack requires internally (at least for
// those channels present in the "channel mask"). In addition to the layout tag, this function
// allows a reordering string to be stored in the file to allow the unpacker to reorder the
// channels back to the specified layout (if it is aware of this feature and wants to restore
// the CAF order). The number of channels in the layout is specified in the lower nybble of
// the layout word, and if a reorder string is specified it must be that long. Note that all
// the reordering is actually done outside of this library, and that if reordering is done
// then the appropriate qmode bit must be set to ensure that any MD5 sum is stored with a new
// ID so that old decoders don't try to verify it (and to let the decoder know that a reorder
// might be required).
//
// Note: This function should only be used to encode Core Audio files in such a way that a
// verbatim archive can be created. Applications can just include the chan_ids parameter in
// the call to WavpackSetConfiguration64() if there are non-Microsoft channels to specify,
// or do nothing special if only Microsoft channels are present (the vast majority of cases).
int WavpackSetChannelLayout (WavpackContext *wpc, uint32_t layout_tag, const unsigned char *reorder)
{
int nchans = layout_tag & 0xff;
if ((layout_tag & 0xff00ff00) || nchans > wpc->config.num_channels)
return FALSE;
wpc->channel_layout = layout_tag;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
if (nchans && reorder) {
int min_index = 256, i;
for (i = 0; i < nchans; ++i)
if (reorder [i] < min_index)
min_index = reorder [i];
wpc->channel_reordering = malloc (nchans);
if (wpc->channel_reordering)
for (i = 0; i < nchans; ++i)
wpc->channel_reordering [i] = reorder [i] - min_index;
}
return TRUE;
}
// Prepare to actually pack samples by determining the size of the WavPack
// blocks and allocating sample buffers and initializing each stream. Call
// after WavpackSetConfiguration() and before WavpackPackSamples(). A return
// of FALSE indicates an error.
static int write_metadata_block (WavpackContext *wpc);
int WavpackPackInit (WavpackContext *wpc)
{
if (wpc->metabytes > 16384) // 16384 bytes still leaves plenty of room for audio
write_metadata_block (wpc); // in this block (otherwise write a special one)
// The default block size is a compromise. Longer blocks provide better encoding efficiency,
// but longer blocks adversely affect memory requirements and seeking performance. For WavPack
// version 5.0, the default block sizes have been reduced by half from the previous version,
// but the difference in encoding efficiency will generally be less than 0.1 percent.
if (wpc->dsd_multiplier) {
wpc->block_samples = (wpc->config.sample_rate % 7) ? 48000 : 44100;
if (wpc->config.flags & CONFIG_HIGH_FLAG)
wpc->block_samples /= 2;
if (wpc->config.num_channels == 1)
wpc->block_samples *= 2;
while (wpc->block_samples > 12000 && wpc->block_samples * wpc->config.num_channels > 300000)
wpc->block_samples /= 2;
}
else {
int divisor = (wpc->config.flags & CONFIG_HIGH_FLAG) ? 2 : 4;
while (wpc->config.sample_rate % divisor)
divisor--;
wpc->block_samples = wpc->config.sample_rate / divisor;
while (wpc->block_samples > 12000 && wpc->block_samples * wpc->config.num_channels > 75000)
wpc->block_samples /= 2;
while (wpc->block_samples * wpc->config.num_channels < 20000)
wpc->block_samples *= 2;
}
if (wpc->config.block_samples) {
if ((wpc->config.flags & CONFIG_MERGE_BLOCKS) &&
wpc->block_samples > (uint32_t) wpc->config.block_samples) {
wpc->block_boundary = wpc->config.block_samples;
wpc->block_samples /= wpc->config.block_samples;
wpc->block_samples *= wpc->config.block_samples;
}
else
wpc->block_samples = wpc->config.block_samples;
}
wpc->ave_block_samples = wpc->block_samples;
wpc->max_samples = wpc->block_samples + (wpc->block_samples >> 1);
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
wps->sample_buffer = malloc (wpc->max_samples * (wps->wphdr.flags & MONO_FLAG ? 4 : 8));
#ifdef ENABLE_DSD
if (wps->wphdr.flags & DSD_FLAG)
pack_dsd_init (wpc);
else
#endif
pack_init (wpc);
}
return TRUE;
}
// Pack the specified samples. Samples must be stored in longs in the native
// endian format of the executing processor. The number of samples specified
// indicates composite samples (sometimes called "frames"). So, the actual
// number of data points would be this "sample_count" times the number of
// channels. Note that samples are accumulated here until enough exist to
// create a complete WavPack block (or several blocks for multichannel audio).
// If an application wants to break a block at a specific sample, then it must
// simply call WavpackFlushSamples() to force an early termination. Completed
// WavPack blocks are send to the function provided in the initial call to
// WavpackOpenFileOutput(). A return of FALSE indicates an error.
static int pack_streams (WavpackContext *wpc, uint32_t block_samples);
static int create_riff_header (WavpackContext *wpc, int64_t total_samples, void *outbuffer);
int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count)
{
int nch = wpc->config.num_channels;
while (sample_count) {
int32_t *source_pointer = sample_buffer;
unsigned int samples_to_copy;
if (!wpc->riff_header_added && !wpc->riff_header_created && !wpc->file_format) {
char riff_header [128];
if (!add_to_metadata (wpc, riff_header, create_riff_header (wpc, wpc->total_samples, riff_header), ID_RIFF_HEADER))
return FALSE;
}
if (wpc->acc_samples + sample_count > wpc->max_samples)
samples_to_copy = wpc->max_samples - wpc->acc_samples;
else
samples_to_copy = sample_count;
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
int32_t *dptr, *sptr, cnt;
dptr = wps->sample_buffer + wpc->acc_samples * (wps->wphdr.flags & MONO_FLAG ? 1 : 2);
sptr = source_pointer;
cnt = samples_to_copy;
// This code used to just copy the 32-bit samples regardless of the actual size with the
// assumption that the caller had properly sign-extended the values (if they were smaller
// than 32 bits). However, several people have discovered that if the data isn't properly
// sign extended then ugly things happen (e.g. CRC errors that show up only on decode).
// To prevent this, we now explicitly sign-extend samples smaller than 32-bit when we
// copy, and the performance hit from doing this is very small (generally < 1%).
if (wps->wphdr.flags & MONO_FLAG) {
switch (wpc->config.bytes_per_sample) {
case 1:
while (cnt--) {
*dptr++ = (signed char) *sptr;
sptr += nch;
}
break;
case 2:
while (cnt--) {
*dptr++ = (int16_t) *sptr;
sptr += nch;
}
break;
case 3:
while (cnt--) {
*dptr++ = (*sptr << 8) >> 8;
sptr += nch;
}
break;
default:
while (cnt--) {
*dptr++ = *sptr;
sptr += nch;
}
}
source_pointer++;
}
else {
switch (wpc->config.bytes_per_sample) {
case 1:
while (cnt--) {
*dptr++ = (signed char) sptr [0];
*dptr++ = (signed char) sptr [1];
sptr += nch;
}
break;
case 2:
while (cnt--) {
*dptr++ = (int16_t) sptr [0];
*dptr++ = (int16_t) sptr [1];
sptr += nch;
}
break;
case 3:
while (cnt--) {
*dptr++ = (sptr [0] << 8) >> 8;
*dptr++ = (sptr [1] << 8) >> 8;
sptr += nch;
}
break;
default:
while (cnt--) {
*dptr++ = sptr [0];
*dptr++ = sptr [1];
sptr += nch;
}
}
source_pointer += 2;
}
}
sample_buffer += samples_to_copy * nch;
sample_count -= samples_to_copy;
if ((wpc->acc_samples += samples_to_copy) == wpc->max_samples &&
!pack_streams (wpc, wpc->block_samples))
return FALSE;
}
return TRUE;
}
// Flush all accumulated samples into WavPack blocks. This is normally called
// after all samples have been sent to WavpackPackSamples(), but can also be
// called to terminate a WavPack block at a specific sample (in other words it
// is possible to continue after this operation). This is also called to
// dump non-audio blocks like those holding metadata for various purposes.
// A return of FALSE indicates an error.
int WavpackFlushSamples (WavpackContext *wpc)
{
while (wpc->acc_samples) {
uint32_t block_samples;
if (wpc->acc_samples > wpc->block_samples)
block_samples = wpc->acc_samples / 2;
else
block_samples = wpc->acc_samples;
if (!pack_streams (wpc, block_samples))
return FALSE;
}
if (wpc->metacount)
write_metadata_block (wpc);
return TRUE;
}
// Note: The following function is no longer required because a proper wav
// header is now automatically generated for the application. However, if the
// application wants to generate its own header or wants to include additional
// chunks, then this function can still be used in which case the automatic
// wav header generation is suppressed.
// Add wrapper (currently RIFF only) to WavPack blocks. This should be called
// before sending any audio samples for the RIFF header or after all samples
// have been sent for any RIFF trailer. WavpackFlushSamples() should be called
// between sending the last samples and calling this for trailer data to make
// sure that headers and trailers don't get mixed up in very short files. If
// the exact contents of the RIFF header are not known because, for example,
// the file duration is uncertain or trailing chunks are possible, simply write
// a "dummy" header of the correct length. When all data has been written it
// will be possible to read the first block written and update the header
// directly. An example of this can be found in the Audition filter. A
// return of FALSE indicates an error.
int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount)
{
int64_t index = WavpackGetSampleIndex64 (wpc);
unsigned char meta_id;
if (!index || index == -1) {
wpc->riff_header_added = TRUE;
meta_id = wpc->file_format ? ID_ALT_HEADER : ID_RIFF_HEADER;
}
else {
wpc->riff_trailer_bytes += bcount;
meta_id = wpc->file_format ? ID_ALT_TRAILER : ID_RIFF_TRAILER;
}
return add_to_metadata (wpc, data, bcount, meta_id);
}
// Store computed MD5 sum in WavPack metadata. Note that the user must compute
// the 16 byte sum; it is not done here. A return of FALSE indicates an error.
// If any of the lower 8 bits of qmode are set, then this MD5 is stored with
// a metadata ID that old decoders do not recognize (because they would not
// interpret the qmode and would therefore fail the verification).
int WavpackStoreMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
return add_to_metadata (wpc, data, 16, (wpc->config.qmode & 0xff) ? ID_ALT_MD5_CHECKSUM : ID_MD5_CHECKSUM);
}
#pragma pack(push,4)
typedef struct {
char ckID [4];
uint64_t chunkSize64;
} CS64Chunk;
typedef struct {
uint64_t riffSize64, dataSize64, sampleCount64;
uint32_t tableLength;
} DS64Chunk;
typedef struct {
char ckID [4];
uint32_t ckSize;
char junk [28];
} JunkChunk;
#pragma pack(pop)
#define DS64ChunkFormat "DDDL"
static int create_riff_header (WavpackContext *wpc, int64_t total_samples, void *outbuffer)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
char *outptr = outbuffer;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
int64_t total_data_bytes, total_riff_bytes;
int32_t channel_mask = wpc->config.channel_mask;
int32_t sample_rate = wpc->config.sample_rate;
int bytes_per_sample = wpc->config.bytes_per_sample;
int bits_per_sample = wpc->config.bits_per_sample;
int format = (wpc->config.float_norm_exp) ? 3 : 1;
int num_channels = wpc->config.num_channels;
int wavhdrsize = 16;
wpc->riff_header_created = TRUE;
if (format == 3 && wpc->config.float_norm_exp != 127) {
strcpy (wpc->error_message, "can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
write_junk = 0;
do_rf64 = 1;
}
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + total_data_bytes + wpc->riff_trailer_bytes;
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
// write the RIFF chunks up to just before the data starts
outptr = (char *) memcpy (outptr, &riffhdr, sizeof (riffhdr)) + sizeof (riffhdr);
if (do_rf64) {
outptr = (char *) memcpy (outptr, &ds64hdr, sizeof (ds64hdr)) + sizeof (ds64hdr);
outptr = (char *) memcpy (outptr, &ds64_chunk, sizeof (ds64_chunk)) + sizeof (ds64_chunk);
}
if (write_junk)
outptr = (char *) memcpy (outptr, &junkchunk, sizeof (junkchunk)) + sizeof (junkchunk);
outptr = (char *) memcpy (outptr, &fmthdr, sizeof (fmthdr)) + sizeof (fmthdr);
outptr = (char *) memcpy (outptr, &wavhdr, wavhdrsize) + wavhdrsize;
outptr = (char *) memcpy (outptr, &datahdr, sizeof (datahdr)) + sizeof (datahdr);
return (int)(outptr - (char *) outbuffer);
}
static int block_add_checksum (unsigned char *buffer_start, unsigned char *buffer_end, int bytes);
static int pack_streams (WavpackContext *wpc, uint32_t block_samples)
{
uint32_t max_blocksize, max_chans = 1, bcount;
unsigned char *outbuff, *outend, *out2buff, *out2end;
int result = TRUE, i;
// for calculating output (block) buffer size, first see if any streams are stereo
for (i = 0; i < wpc->num_streams; i++)
if (!(wpc->streams [i]->wphdr.flags & MONO_FLAG)) {
max_chans = 2;
break;
}
// then calculate maximum size based on bytes / sample
max_blocksize = block_samples * max_chans * ((wpc->streams [0]->wphdr.flags & BYTES_STORED) + 1);
// add margin based on how much "negative" compression is possible with pathological audio
if ((wpc->config.flags & CONFIG_FLOAT_DATA) && !(wpc->config.flags & CONFIG_SKIP_WVX))
max_blocksize += max_blocksize; // 100% margin for lossless float data
else
max_blocksize += max_blocksize >> 2; // otherwise 25% margin for everything else
max_blocksize += wpc->metabytes + 1024; // finally, add metadata & another 1K margin
out2buff = (wpc->wvc_flag) ? malloc (max_blocksize) : NULL;
out2end = out2buff + max_blocksize;
outbuff = malloc (max_blocksize);
outend = outbuff + max_blocksize;
for (wpc->current_stream = 0; wpc->current_stream < wpc->num_streams; wpc->current_stream++) {
WavpackStream *wps = wpc->streams [wpc->current_stream];
uint32_t flags = wps->wphdr.flags;
flags &= ~MAG_MASK;
flags += (1 << MAG_LSB) * ((flags & BYTES_STORED) * 8 + 7);
SET_BLOCK_INDEX (wps->wphdr, wps->sample_index);
wps->wphdr.block_samples = block_samples;
wps->wphdr.flags = flags;
wps->block2buff = out2buff;
wps->block2end = out2end;
wps->blockbuff = outbuff;
wps->blockend = outend;
#ifdef ENABLE_DSD
if (flags & DSD_FLAG)
result = pack_dsd_block (wpc, wps->sample_buffer);
else
#endif
result = pack_block (wpc, wps->sample_buffer);
if (result) {
result = block_add_checksum (outbuff, outend, (flags & HYBRID_FLAG) ? 2 : 4);
if (result && out2buff)
result = block_add_checksum (out2buff, out2end, 2);
}
wps->blockbuff = wps->block2buff = NULL;
if (wps->wphdr.block_samples != block_samples)
block_samples = wps->wphdr.block_samples;
if (!result) {
strcpy (wpc->error_message, "output buffer overflowed!");
break;
}
bcount = ((WavpackHeader *) outbuff)->ckSize + 8;
WavpackNativeToLittleEndian ((WavpackHeader *) outbuff, WavpackHeaderFormat);
result = wpc->blockout (wpc->wv_out, outbuff, bcount);
if (!result) {
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
break;
}
wpc->filelen += bcount;
if (out2buff) {
bcount = ((WavpackHeader *) out2buff)->ckSize + 8;
WavpackNativeToLittleEndian ((WavpackHeader *) out2buff, WavpackHeaderFormat);
result = wpc->blockout (wpc->wvc_out, out2buff, bcount);
if (!result) {
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
break;
}
wpc->file2len += bcount;
}
if (wpc->acc_samples != block_samples)
memmove (wps->sample_buffer, wps->sample_buffer + block_samples * (flags & MONO_FLAG ? 1 : 2),
(wpc->acc_samples - block_samples) * sizeof (int32_t) * (flags & MONO_FLAG ? 1 : 2));
}
wpc->current_stream = 0;
wpc->ave_block_samples = (wpc->ave_block_samples * 0x7 + block_samples + 0x4) >> 3;
wpc->acc_samples -= block_samples;
free (outbuff);
if (out2buff)
free (out2buff);
return result;
}
// Given the pointer to the first block written (to either a .wv or .wvc file),
// update the block with the actual number of samples written. If the wav
// header was generated by the library, then it is updated also. This should
// be done if WavpackSetConfiguration() was called with an incorrect number
// of samples (or -1). It is the responsibility of the application to read and
// rewrite the block. An example of this can be found in the Audition filter.
static void block_update_checksum (unsigned char *buffer_start);
void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block)
{
uint32_t wrapper_size;
WavpackLittleEndianToNative (first_block, WavpackHeaderFormat);
SET_TOTAL_SAMPLES (* (WavpackHeader *) first_block, WavpackGetSampleIndex64 (wpc));
if (wpc->riff_header_created && WavpackGetWrapperLocation (first_block, &wrapper_size)) {
unsigned char riff_header [128];
if (wrapper_size == create_riff_header (wpc, WavpackGetSampleIndex64 (wpc), riff_header))
memcpy (WavpackGetWrapperLocation (first_block, NULL), riff_header, wrapper_size);
}
block_update_checksum (first_block);
WavpackNativeToLittleEndian (first_block, WavpackHeaderFormat);
}
// Note: The following function is no longer required because the wav header
// automatically generated for the application will also be updated by
// WavpackUpdateNumSamples (). However, if the application wants to generate
// its own header or wants to include additional chunks, then this function
// still must be used to update the application generated header.
// Given the pointer to the first block written to a WavPack file, this
// function returns the location of the stored RIFF header that was originally
// written with WavpackAddWrapper(). This would normally be used to update
// the wav header to indicate that a different number of samples was actually
// written or if additional RIFF chunks are written at the end of the file.
// The "size" parameter can be set to non-NULL to obtain the exact size of the
// RIFF header, and the function will return FALSE if the header is not found
// in the block's metadata (or it is not a valid WavPack block). It is the
// responsibility of the application to read and rewrite the block. An example
// of this can be found in the Audition filter.
static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size);
void *WavpackGetWrapperLocation (void *first_block, uint32_t *size)
{
void *loc;
WavpackLittleEndianToNative (first_block, WavpackHeaderFormat);
loc = find_metadata (first_block, ID_RIFF_HEADER, size);
if (!loc)
loc = find_metadata (first_block, ID_ALT_HEADER, size);
WavpackNativeToLittleEndian (first_block, WavpackHeaderFormat);
return loc;
}
static void *find_metadata (void *wavpack_block, int desired_id, uint32_t *size)
{
WavpackHeader *wphdr = wavpack_block;
unsigned char *dp, meta_id, c1, c2;
int32_t bcount, meta_bc;
if (strncmp (wphdr->ckID, "wvpk", 4))
return NULL;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
break;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if ((meta_id & ID_UNIQUE) == desired_id) {
if ((bcount - meta_bc) >= 0) {
if (size)
*size = meta_bc - ((meta_id & ID_ODD_SIZE) ? 1 : 0);
return dp;
}
else
return NULL;
}
bcount -= meta_bc;
dp += meta_bc;
}
return NULL;
}
int copy_metadata (WavpackMetadata *wpmd, unsigned char *buffer_start, unsigned char *buffer_end)
{
uint32_t mdsize = wpmd->byte_length + (wpmd->byte_length & 1);
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
mdsize += (wpmd->byte_length > 510) ? 4 : 2;
buffer_start += wphdr->ckSize + 8;
if (buffer_start + mdsize >= buffer_end)
return FALSE;
buffer_start [0] = wpmd->id | (wpmd->byte_length & 1 ? ID_ODD_SIZE : 0);
buffer_start [1] = (wpmd->byte_length + 1) >> 1;
if (wpmd->byte_length > 510) {
buffer_start [0] |= ID_LARGE;
buffer_start [2] = (wpmd->byte_length + 1) >> 9;
buffer_start [3] = (wpmd->byte_length + 1) >> 17;
}
if (wpmd->data && wpmd->byte_length) {
memcpy (buffer_start + (wpmd->byte_length > 510 ? 4 : 2), wpmd->data, wpmd->byte_length);
if (wpmd->byte_length & 1) // if size is odd, make sure pad byte is a zero
buffer_start [mdsize - 1] = 0;
}
wphdr->ckSize += mdsize;
return TRUE;
}
static int add_to_metadata (WavpackContext *wpc, void *data, uint32_t bcount, unsigned char id)
{
WavpackMetadata *mdp;
unsigned char *src = data;
while (bcount) {
if (wpc->metacount) {
uint32_t bc = bcount;
mdp = wpc->metadata + wpc->metacount - 1;
if (mdp->id == id) {
if (wpc->metabytes + bcount > 1000000)
bc = 1000000 - wpc->metabytes;
mdp->data = realloc (mdp->data, mdp->byte_length + bc);
memcpy ((char *) mdp->data + mdp->byte_length, src, bc);
mdp->byte_length += bc;
wpc->metabytes += bc;
bcount -= bc;
src += bc;
if (wpc->metabytes >= 1000000 && !write_metadata_block (wpc))
return FALSE;
}
}
if (bcount) {
wpc->metadata = realloc (wpc->metadata, (wpc->metacount + 1) * sizeof (WavpackMetadata));
mdp = wpc->metadata + wpc->metacount++;
mdp->byte_length = 0;
mdp->data = NULL;
mdp->id = id;
}
}
return TRUE;
}
static char *write_metadata (WavpackMetadata *wpmd, char *outdata)
{
unsigned char id = wpmd->id, wordlen [3];
wordlen [0] = (wpmd->byte_length + 1) >> 1;
wordlen [1] = (wpmd->byte_length + 1) >> 9;
wordlen [2] = (wpmd->byte_length + 1) >> 17;
if (wpmd->byte_length & 1)
id |= ID_ODD_SIZE;
if (wordlen [1] || wordlen [2])
id |= ID_LARGE;
*outdata++ = id;
*outdata++ = wordlen [0];
if (id & ID_LARGE) {
*outdata++ = wordlen [1];
*outdata++ = wordlen [2];
}
if (wpmd->data && wpmd->byte_length) {
memcpy (outdata, wpmd->data, wpmd->byte_length);
outdata += wpmd->byte_length;
if (wpmd->byte_length & 1)
*outdata++ = 0;
}
return outdata;
}
static int write_metadata_block (WavpackContext *wpc)
{
char *block_buff, *block_ptr;
WavpackHeader *wphdr;
if (wpc->metacount) {
int metacount = wpc->metacount, block_size = sizeof (WavpackHeader);
WavpackMetadata *wpmdp = wpc->metadata;
while (metacount--) {
block_size += wpmdp->byte_length + (wpmdp->byte_length & 1);
block_size += (wpmdp->byte_length > 510) ? 4 : 2;
wpmdp++;
}
// allocate 6 extra bytes for 4-byte checksum (which we add last)
wphdr = (WavpackHeader *) (block_buff = malloc (block_size + 6));
CLEAR (*wphdr);
memcpy (wphdr->ckID, "wvpk", 4);
SET_TOTAL_SAMPLES (*wphdr, wpc->total_samples);
wphdr->version = wpc->stream_version;
wphdr->ckSize = block_size - 8;
wphdr->block_samples = 0;
block_ptr = (char *)(wphdr + 1);
wpmdp = wpc->metadata;
while (wpc->metacount) {
block_ptr = write_metadata (wpmdp, block_ptr);
wpc->metabytes -= wpmdp->byte_length;
free_metadata (wpmdp++);
wpc->metacount--;
}
free (wpc->metadata);
wpc->metadata = NULL;
// add a 4-byte checksum here (increases block size by 6)
block_add_checksum ((unsigned char *) block_buff, (unsigned char *) block_buff + (block_size += 6), 4);
WavpackNativeToLittleEndian ((WavpackHeader *) block_buff, WavpackHeaderFormat);
if (!wpc->blockout (wpc->wv_out, block_buff, block_size)) {
free (block_buff);
strcpy (wpc->error_message, "can't write WavPack data, disk probably full!");
return FALSE;
}
free (block_buff);
}
return TRUE;
}
void free_metadata (WavpackMetadata *wpmd)
{
if (wpmd->data) {
free (wpmd->data);
wpmd->data = NULL;
}
}
// These two functions add or update the block checksums that were introduced in WavPack 5.0.
// The presence of the checksum is indicated by a flag in the wavpack header (HAS_CHECKSUM)
// and the actual metadata item should be the last one in the block, and can be either 2 or 4
// bytes. Of course, older versions of the decoder will simply ignore both of these.
static int block_add_checksum (unsigned char *buffer_start, unsigned char *buffer_end, int bytes)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer_start;
#else
unsigned char *csptr = buffer_start;
#endif
int bcount = wphdr->ckSize + 8, wcount;
uint32_t csum = (uint32_t) -1;
if (bytes != 2 && bytes != 4)
return FALSE;
if (bcount < sizeof (WavpackHeader) || (bcount & 1) || buffer_start + bcount + 2 + bytes > buffer_end)
return FALSE;
wphdr->flags |= HAS_CHECKSUM;
wphdr->ckSize += 2 + bytes;
wcount = bcount >> 1;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
#endif
buffer_start += bcount;
*buffer_start++ = ID_BLOCK_CHECKSUM;
*buffer_start++ = bytes >> 1;
if (bytes == 4) {
*buffer_start++ = csum;
*buffer_start++ = csum >> 8;
*buffer_start++ = csum >> 16;
*buffer_start++ = csum >> 24;
}
else {
csum ^= csum >> 16;
*buffer_start++ = csum;
*buffer_start++ = csum >> 8;
}
return TRUE;
}
static void block_update_checksum (unsigned char *buffer_start)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer_start;
unsigned char *dp, meta_id, c1, c2;
uint32_t bcount, meta_bc;
if (!(wphdr->flags & HAS_CHECKSUM))
return;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return;
if ((meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer_start;
#else
unsigned char *csptr = buffer_start;
#endif
int wcount = (int)(dp - 2 - buffer_start) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer_start, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
*dp++ = csum;
*dp++ = csum >> 8;
*dp++ = csum >> 16;
*dp++ = csum >> 24;
return;
}
else {
csum ^= csum >> 16;
*dp++ = csum;
*dp++ = csum >> 8;
return;
}
}
bcount -= meta_bc;
dp += meta_bc;
}
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_456_0 |
crossvul-cpp_data_bad_587_0 | /* $Id: table.c,v 1.58 2010/08/09 11:59:19 htrb Exp $ */
/*
* HTML table
*/
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "fm.h"
#include "html.h"
#include "parsetagx.h"
#include "Str.h"
#include "myctype.h"
int symbol_width = 0;
int symbol_width0 = 0;
#define RULE_WIDTH symbol_width
#define RULE(mode,n) (((mode) == BORDER_THICK) ? ((n) + 16) : (n))
#define TK_VERTICALBAR(mode) RULE(mode,5)
#define BORDERWIDTH 2
#define BORDERHEIGHT 1
#define NOBORDERWIDTH 1
#define NOBORDERHEIGHT 0
#define HTT_X 1
#define HTT_Y 2
#define HTT_ALIGN 0x30
#define HTT_LEFT 0x00
#define HTT_CENTER 0x10
#define HTT_RIGHT 0x20
#define HTT_TRSET 0x40
#define HTT_VALIGN 0x700
#define HTT_TOP 0x100
#define HTT_MIDDLE 0x200
#define HTT_BOTTOM 0x400
#define HTT_VTRSET 0x800
#ifdef NOWRAP
#define HTT_NOWRAP 4
#endif /* NOWRAP */
#define TAG_IS(s,tag,len) (strncasecmp(s,tag,len)==0&&(s[len] == '>' || IS_SPACE((int)s[len])))
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#endif /* not max */
#ifndef min
#define min(a,b) ((a) > (b) ? (b) : (a))
#endif /* not min */
#ifndef abs
#define abs(a) ((a) >= 0. ? (a) : -(a))
#endif /* not abs */
#define set_prevchar(x,y,n) Strcopy_charp_n((x),(y),(n))
#define set_space_to_prevchar(x) Strcopy_charp_n((x)," ",1)
#ifdef MATRIX
#ifndef MESCHACH
#include "matrix.c"
#endif /* not MESCHACH */
#endif /* MATRIX */
#ifdef MATRIX
int correct_table_matrix(struct table *, int, int, int, double);
void set_table_matrix(struct table *, int);
#endif /* MATRIX */
#ifdef MATRIX
static double
weight(int x)
{
if (x < COLS)
return (double)x;
else
return COLS * (log((double)x / COLS) + 1.);
}
static double
weight2(int a)
{
return (double)a / COLS * 4 + 1.;
}
#define sigma_td(a) (0.5*weight2(a)) /* <td width=...> */
#define sigma_td_nw(a) (32*weight2(a)) /* <td ...> */
#define sigma_table(a) (0.25*weight2(a)) /* <table width=...> */
#define sigma_table_nw(a) (2*weight2(a)) /* <table...> */
#else /* not MATRIX */
#define LOG_MIN 1.0
static double
weight3(int x)
{
if (x < 0.1)
return 0.1;
if (x < LOG_MIN)
return (double)x;
else
return LOG_MIN * (log((double)x / LOG_MIN) + 1.);
}
#endif /* not MATRIX */
static int
bsearch_2short(short e1, short *ent1, short e2, short *ent2, int base,
short *indexarray, int nent)
{
int n = nent;
int k = 0;
int e = e1 * base + e2;
while (n > 0) {
int nn = n / 2;
int idx = indexarray[k + nn];
int ne = ent1[idx] * base + ent2[idx];
if (ne == e) {
k += nn;
break;
}
else if (ne < e) {
n -= nn + 1;
k += nn + 1;
}
else {
n = nn;
}
}
return k;
}
static int
bsearch_double(double e, double *ent, short *indexarray, int nent)
{
int n = nent;
int k = 0;
while (n > 0) {
int nn = n / 2;
int idx = indexarray[k + nn];
double ne = ent[idx];
if (ne == e) {
k += nn;
break;
}
else if (ne > e) {
n -= nn + 1;
k += nn + 1;
}
else {
n = nn;
}
}
return k;
}
static int
ceil_at_intervals(int x, int step)
{
int mo = x % step;
if (mo > 0)
x += step - mo;
else if (mo < 0)
x -= mo;
return x;
}
static int
floor_at_intervals(int x, int step)
{
int mo = x % step;
if (mo > 0)
x -= mo;
else if (mo < 0)
x += step - mo;
return x;
}
#define round(x) ((int)floor((x)+0.5))
#ifndef MATRIX
static void
dv2sv(double *dv, short *iv, int size)
{
int i, k, iw;
short *indexarray;
double *edv;
double w = 0., x;
indexarray = NewAtom_N(short, size);
edv = NewAtom_N(double, size);
for (i = 0; i < size; i++) {
iv[i] = (short) ceil(dv[i]);
edv[i] = (double)iv[i] - dv[i];
}
w = 0.;
for (k = 0; k < size; k++) {
x = edv[k];
w += x;
i = bsearch_double(x, edv, indexarray, k);
if (k > i) {
int ii;
for (ii = k; ii > i; ii--)
indexarray[ii] = indexarray[ii - 1];
}
indexarray[i] = k;
}
iw = min((int)(w + 0.5), size);
if (iw <= 1)
return;
x = edv[(int)indexarray[iw - 1]];
for (i = 0; i < size; i++) {
k = indexarray[i];
if (i >= iw && abs(edv[k] - x) > 1e-6)
break;
iv[k]--;
}
}
#endif
static int
table_colspan(struct table *t, int row, int col)
{
int i;
for (i = col + 1; i <= t->maxcol && (t->tabattr[row][i] & HTT_X); i++) ;
return i - col;
}
static int
table_rowspan(struct table *t, int row, int col)
{
int i;
if (!t->tabattr[row])
return 0;
for (i = row + 1; i <= t->maxrow && t->tabattr[i] &&
(t->tabattr[i][col] & HTT_Y); i++) ;
return i - row;
}
static int
minimum_cellspacing(int border_mode)
{
switch (border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
return RULE_WIDTH;
case BORDER_NONE:
return 1;
default:
/* not reached */
return 0;
}
}
static int
table_border_width(struct table *t)
{
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
return t->maxcol * t->cellspacing + 2 * (RULE_WIDTH + t->cellpadding);
case BORDER_NOWIN:
case BORDER_NONE:
return t->maxcol * t->cellspacing;
default:
/* not reached */
return 0;
}
}
struct table *
newTable()
{
struct table *t;
int i, j;
t = New(struct table);
t->max_rowsize = MAXROW;
t->tabdata = New_N(GeneralList **, MAXROW);
t->tabattr = New_N(table_attr *, MAXROW);
t->tabheight = NewAtom_N(short, MAXROW);
#ifdef ID_EXT
t->tabidvalue = New_N(Str *, MAXROW);
t->tridvalue = New_N(Str, MAXROW);
#endif /* ID_EXT */
for (i = 0; i < MAXROW; i++) {
t->tabdata[i] = NULL;
t->tabattr[i] = 0;
t->tabheight[i] = 0;
#ifdef ID_EXT
t->tabidvalue[i] = NULL;
t->tridvalue[i] = NULL;
#endif /* ID_EXT */
}
for (j = 0; j < MAXCOL; j++) {
t->tabwidth[j] = 0;
t->minimum_width[j] = 0;
t->fixed_width[j] = 0;
}
t->cell.maxcell = -1;
t->cell.icell = -1;
t->ntable = 0;
t->tables_size = 0;
t->tables = NULL;
#ifdef MATRIX
t->matrix = NULL;
t->vector = NULL;
#endif /* MATRIX */
#if 0
t->tabcontentssize = 0;
t->indent = 0;
t->linfo.prev_ctype = PC_ASCII;
t->linfo.prev_spaces = -1;
#endif
t->linfo.prevchar = Strnew_size(8);
set_prevchar(t->linfo.prevchar, "", 0);
t->trattr = 0;
t->caption = Strnew();
t->suspended_data = NULL;
#ifdef ID_EXT
t->id = NULL;
#endif
return t;
}
static void
check_row(struct table *t, int row)
{
int i, r;
GeneralList ***tabdata;
table_attr **tabattr;
short *tabheight;
#ifdef ID_EXT
Str **tabidvalue;
Str *tridvalue;
#endif /* ID_EXT */
if (row >= t->max_rowsize) {
r = max(t->max_rowsize * 2, row + 1);
tabdata = New_N(GeneralList **, r);
tabattr = New_N(table_attr *, r);
tabheight = NewAtom_N(short, r);
#ifdef ID_EXT
tabidvalue = New_N(Str *, r);
tridvalue = New_N(Str, r);
#endif /* ID_EXT */
for (i = 0; i < t->max_rowsize; i++) {
tabdata[i] = t->tabdata[i];
tabattr[i] = t->tabattr[i];
tabheight[i] = t->tabheight[i];
#ifdef ID_EXT
tabidvalue[i] = t->tabidvalue[i];
tridvalue[i] = t->tridvalue[i];
#endif /* ID_EXT */
}
for (; i < r; i++) {
tabdata[i] = NULL;
tabattr[i] = NULL;
tabheight[i] = 0;
#ifdef ID_EXT
tabidvalue[i] = NULL;
tridvalue[i] = NULL;
#endif /* ID_EXT */
}
t->tabdata = tabdata;
t->tabattr = tabattr;
t->tabheight = tabheight;
#ifdef ID_EXT
t->tabidvalue = tabidvalue;
t->tridvalue = tridvalue;
#endif /* ID_EXT */
t->max_rowsize = r;
}
if (t->tabdata[row] == NULL) {
t->tabdata[row] = New_N(GeneralList *, MAXCOL);
t->tabattr[row] = NewAtom_N(table_attr, MAXCOL);
#ifdef ID_EXT
t->tabidvalue[row] = New_N(Str, MAXCOL);
#endif /* ID_EXT */
for (i = 0; i < MAXCOL; i++) {
t->tabdata[row][i] = NULL;
t->tabattr[row][i] = 0;
#ifdef ID_EXT
t->tabidvalue[row][i] = NULL;
#endif /* ID_EXT */
}
}
}
void
pushdata(struct table *t, int row, int col, char *data)
{
check_row(t, row);
if (t->tabdata[row][col] == NULL)
t->tabdata[row][col] = newGeneralList();
pushText(t->tabdata[row][col], data ? data : "");
}
void
suspend_or_pushdata(struct table *tbl, char *line)
{
if (tbl->flag & TBL_IN_COL)
pushdata(tbl, tbl->row, tbl->col, line);
else {
if (!tbl->suspended_data)
tbl->suspended_data = newTextList();
pushText(tbl->suspended_data, line ? line : "");
}
}
#ifdef USE_M17N
#define PUSH_TAG(str,n) Strcat_charp_n(tagbuf, str, n)
#else
#define PUSH_TAG(str,n) Strcat_char(tagbuf, *str)
#endif
int visible_length_offset = 0;
int
visible_length(char *str)
{
int len = 0, n, max_len = 0;
int status = R_ST_NORMAL;
int prev_status = status;
Str tagbuf = Strnew();
char *t, *r2;
int amp_len = 0;
while (*str) {
prev_status = status;
if (next_status(*str, &status)) {
#ifdef USE_M17N
len += get_mcwidth(str);
n = get_mclen(str);
}
else {
n = 1;
}
#else
len++;
}
#endif
if (status == R_ST_TAG0) {
Strclear(tagbuf);
PUSH_TAG(str, n);
}
else if (status == R_ST_TAG || status == R_ST_DQUOTE
|| status == R_ST_QUOTE || status == R_ST_EQL
|| status == R_ST_VALUE) {
PUSH_TAG(str, n);
}
else if (status == R_ST_AMP) {
if (prev_status == R_ST_NORMAL) {
Strclear(tagbuf);
len--;
amp_len = 0;
}
else {
PUSH_TAG(str, n);
amp_len++;
}
}
else if (status == R_ST_NORMAL && prev_status == R_ST_AMP) {
PUSH_TAG(str, n);
r2 = tagbuf->ptr;
t = getescapecmd(&r2);
if (!*r2 && (*t == '\r' || *t == '\n')) {
if (len > max_len)
max_len = len;
len = 0;
}
else
len += get_strwidth(t) + get_strwidth(r2);
}
else if (status == R_ST_NORMAL && ST_IS_REAL_TAG(prev_status)) {
;
}
else if (*str == '\t') {
len--;
do {
len++;
} while ((visible_length_offset + len) % Tabstop != 0);
}
else if (*str == '\r' || *str == '\n') {
len--;
if (len > max_len)
max_len = len;
len = 0;
}
#ifdef USE_M17N
str += n;
#else
str++;
#endif
}
if (status == R_ST_AMP) {
r2 = tagbuf->ptr;
t = getescapecmd(&r2);
if (*t != '\r' && *t != '\n')
len += get_strwidth(t) + get_strwidth(r2);
}
return len > max_len ? len : max_len;
}
int
visible_length_plain(char *str)
{
int len = 0, max_len = 0;
while (*str) {
if (*str == '\t') {
do {
len++;
} while ((visible_length_offset + len) % Tabstop != 0);
str++;
}
else if (*str == '\r' || *str == '\n') {
if (len > max_len)
max_len = len;
len = 0;
str++;
}
else {
#ifdef USE_M17N
len += get_mcwidth(str);
str += get_mclen(str);
#else
len++;
str++;
#endif
}
}
return len > max_len ? len : max_len;
}
static int
maximum_visible_length(char *str, int offset)
{
visible_length_offset = offset;
return visible_length(str);
}
static int
maximum_visible_length_plain(char *str, int offset)
{
visible_length_offset = offset;
return visible_length_plain(str);
}
void
align(TextLine *lbuf, int width, int mode)
{
int i, l, l1, l2;
Str buf, line = lbuf->line;
if (line->length == 0) {
for (i = 0; i < width; i++)
Strcat_char(line, ' ');
lbuf->pos = width;
return;
}
buf = Strnew();
l = width - lbuf->pos;
switch (mode) {
case ALIGN_CENTER:
l1 = l / 2;
l2 = l - l1;
for (i = 0; i < l1; i++)
Strcat_char(buf, ' ');
Strcat(buf, line);
for (i = 0; i < l2; i++)
Strcat_char(buf, ' ');
break;
case ALIGN_LEFT:
Strcat(buf, line);
for (i = 0; i < l; i++)
Strcat_char(buf, ' ');
break;
case ALIGN_RIGHT:
for (i = 0; i < l; i++)
Strcat_char(buf, ' ');
Strcat(buf, line);
break;
default:
return;
}
lbuf->line = buf;
if (lbuf->pos < width)
lbuf->pos = width;
}
void
print_item(struct table *t, int row, int col, int width, Str buf)
{
int alignment;
TextLine *lbuf;
if (t->tabdata[row])
lbuf = popTextLine(t->tabdata[row][col]);
else
lbuf = NULL;
if (lbuf != NULL) {
check_row(t, row);
alignment = ALIGN_CENTER;
if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_LEFT)
alignment = ALIGN_LEFT;
else if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_RIGHT)
alignment = ALIGN_RIGHT;
else if ((t->tabattr[row][col] & HTT_ALIGN) == HTT_CENTER)
alignment = ALIGN_CENTER;
align(lbuf, width, alignment);
Strcat(buf, lbuf->line);
}
else {
lbuf = newTextLine(NULL, 0);
align(lbuf, width, ALIGN_CENTER);
Strcat(buf, lbuf->line);
}
}
#define T_TOP 0
#define T_MIDDLE 1
#define T_BOTTOM 2
void
print_sep(struct table *t, int row, int type, int maxcol, Str buf)
{
int forbid;
int rule_mode;
int i, k, l, m;
if (row >= 0)
check_row(t, row);
check_row(t, row + 1);
if ((type == T_TOP || type == T_BOTTOM) && t->border_mode == BORDER_THICK) {
rule_mode = BORDER_THICK;
}
else {
rule_mode = BORDER_THIN;
}
forbid = 1;
if (type == T_TOP)
forbid |= 2;
else if (type == T_BOTTOM)
forbid |= 8;
else if (t->tabattr[row + 1][0] & HTT_Y) {
forbid |= 4;
}
if (t->border_mode != BORDER_NOWIN) {
push_symbol(buf, RULE(t->border_mode, forbid), symbol_width, 1);
}
for (i = 0; i <= maxcol; i++) {
forbid = 10;
if (type != T_BOTTOM && (t->tabattr[row + 1][i] & HTT_Y)) {
if (t->tabattr[row + 1][i] & HTT_X) {
goto do_last_sep;
}
else {
for (k = row;
k >= 0 && t->tabattr[k] && (t->tabattr[k][i] & HTT_Y);
k--) ;
m = t->tabwidth[i] + 2 * t->cellpadding;
for (l = i + 1; l <= t->maxcol && (t->tabattr[row][l] & HTT_X);
l++)
m += t->tabwidth[l] + t->cellspacing;
print_item(t, k, i, m, buf);
}
}
else {
int w = t->tabwidth[i] + 2 * t->cellpadding;
if (RULE_WIDTH == 2)
w = (w + 1) / RULE_WIDTH;
push_symbol(buf, RULE(rule_mode, forbid), symbol_width, w);
}
do_last_sep:
if (i < maxcol) {
forbid = 0;
if (type == T_TOP)
forbid |= 2;
else if (t->tabattr[row][i + 1] & HTT_X) {
forbid |= 2;
}
if (type == T_BOTTOM)
forbid |= 8;
else {
if (t->tabattr[row + 1][i + 1] & HTT_X) {
forbid |= 8;
}
if (t->tabattr[row + 1][i + 1] & HTT_Y) {
forbid |= 4;
}
if (t->tabattr[row + 1][i] & HTT_Y) {
forbid |= 1;
}
}
if (forbid != 15) /* forbid==15 means 'no rule at all' */
push_symbol(buf, RULE(rule_mode, forbid), symbol_width, 1);
}
}
forbid = 4;
if (type == T_TOP)
forbid |= 2;
if (type == T_BOTTOM)
forbid |= 8;
if (t->tabattr[row + 1][maxcol] & HTT_Y) {
forbid |= 1;
}
if (t->border_mode != BORDER_NOWIN)
push_symbol(buf, RULE(t->border_mode, forbid), symbol_width, 1);
}
static int
get_spec_cell_width(struct table *tbl, int row, int col)
{
int i, w;
w = tbl->tabwidth[col];
for (i = col + 1; i <= tbl->maxcol; i++) {
check_row(tbl, row);
if (tbl->tabattr[row][i] & HTT_X)
w += tbl->tabwidth[i] + tbl->cellspacing;
else
break;
}
return w;
}
void
do_refill(struct table *tbl, int row, int col, int maxlimit)
{
TextList *orgdata;
TextListItem *l;
struct readbuffer obuf;
struct html_feed_environ h_env;
struct environment envs[MAX_ENV_LEVEL];
int colspan, icell;
if (tbl->tabdata[row] == NULL || tbl->tabdata[row][col] == NULL)
return;
orgdata = (TextList *)tbl->tabdata[row][col];
tbl->tabdata[row][col] = newGeneralList();
init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL,
(TextLineList *)tbl->tabdata[row][col],
get_spec_cell_width(tbl, row, col), 0);
obuf.flag |= RB_INTABLE;
if (h_env.limit > maxlimit)
h_env.limit = maxlimit;
if (tbl->border_mode != BORDER_NONE && tbl->vcellpadding > 0)
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
for (l = orgdata->first; l != NULL; l = l->next) {
if (TAG_IS(l->ptr, "<table_alt", 10)) {
int id = -1;
char *p = l->ptr;
struct parsed_tag *tag;
if ((tag = parse_tag(&p, TRUE)) != NULL)
parsedtag_get_value(tag, ATTR_TID, &id);
if (id >= 0 && id < tbl->ntable && tbl->tables[id].ptr) {
int alignment;
TextLineListItem *ti;
struct table *t = tbl->tables[id].ptr;
int limit = tbl->tables[id].indent + t->total_width;
tbl->tables[id].ptr = NULL;
save_fonteffect(&h_env, h_env.obuf);
flushline(&h_env, &obuf, 0, 2, h_env.limit);
if (t->vspace > 0 && !(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
if (RB_GET_ALIGN(h_env.obuf) == RB_CENTER)
alignment = ALIGN_CENTER;
else if (RB_GET_ALIGN(h_env.obuf) == RB_RIGHT)
alignment = ALIGN_RIGHT;
else
alignment = ALIGN_LEFT;
if (alignment != ALIGN_LEFT) {
for (ti = tbl->tables[id].buf->first;
ti != NULL; ti = ti->next)
align(ti->ptr, h_env.limit, alignment);
}
appendTextLineList(h_env.buf, tbl->tables[id].buf);
if (h_env.maxlimit < limit)
h_env.maxlimit = limit;
restore_fonteffect(&h_env, h_env.obuf);
obuf.flag &= ~RB_IGNORE_P;
h_env.blank_lines = 0;
if (t->vspace > 0) {
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
obuf.flag |= RB_IGNORE_P;
}
}
}
else
HTMLlineproc1(l->ptr, &h_env);
}
if (obuf.status != R_ST_NORMAL) {
obuf.status = R_ST_EOL;
HTMLlineproc1("\n", &h_env);
}
completeHTMLstream(&h_env, &obuf);
flushline(&h_env, &obuf, 0, 2, h_env.limit);
if (tbl->border_mode == BORDER_NONE) {
int rowspan = table_rowspan(tbl, row, col);
if (row + rowspan <= tbl->maxrow) {
if (tbl->vcellpadding > 0 && !(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
}
else {
if (tbl->vspace > 0)
purgeline(&h_env);
}
}
else {
if (tbl->vcellpadding > 0) {
if (!(obuf.flag & RB_IGNORE_P))
do_blankline(&h_env, &obuf, 0, 0, h_env.limit);
}
else
purgeline(&h_env);
}
if ((colspan = table_colspan(tbl, row, col)) > 1) {
struct table_cell *cell = &tbl->cell;
int k;
k = bsearch_2short(colspan, cell->colspan, col, cell->col, MAXCOL,
cell->index, cell->maxcell + 1);
icell = cell->index[k];
if (cell->minimum_width[icell] < h_env.maxlimit)
cell->minimum_width[icell] = h_env.maxlimit;
}
else {
if (tbl->minimum_width[col] < h_env.maxlimit)
tbl->minimum_width[col] = h_env.maxlimit;
}
}
static int
table_rule_width(struct table *t)
{
if (t->border_mode == BORDER_NONE)
return 1;
return RULE_WIDTH;
}
static void
check_cell_width(short *tabwidth, short *cellwidth,
short *col, short *colspan, short maxcell,
short *indexarray, int space, int dir)
{
int i, j, k, bcol, ecol;
int swidth, width;
for (k = 0; k <= maxcell; k++) {
j = indexarray[k];
if (cellwidth[j] <= 0)
continue;
bcol = col[j];
ecol = bcol + colspan[j];
swidth = 0;
for (i = bcol; i < ecol; i++)
swidth += tabwidth[i];
width = cellwidth[j] - (colspan[j] - 1) * space;
if (width > swidth) {
int w = (width - swidth) / colspan[j];
int r = (width - swidth) % colspan[j];
for (i = bcol; i < ecol; i++)
tabwidth[i] += w;
/* dir {0: horizontal, 1: vertical} */
if (dir == 1 && r > 0)
r = colspan[j];
for (i = 1; i <= r; i++)
tabwidth[ecol - i]++;
}
}
}
void
check_minimum_width(struct table *t, short *tabwidth)
{
int i;
struct table_cell *cell = &t->cell;
for (i = 0; i <= t->maxcol; i++) {
if (tabwidth[i] < t->minimum_width[i])
tabwidth[i] = t->minimum_width[i];
}
check_cell_width(tabwidth, cell->minimum_width, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
void
check_maximum_width(struct table *t)
{
struct table_cell *cell = &t->cell;
#ifdef MATRIX
int i, j, bcol, ecol;
int swidth, width;
cell->necell = 0;
for (j = 0; j <= cell->maxcell; j++) {
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
swidth = 0;
for (i = bcol; i < ecol; i++)
swidth += t->tabwidth[i];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
if (width > swidth) {
cell->eindex[cell->necell] = j;
cell->necell++;
}
}
#else /* not MATRIX */
check_cell_width(t->tabwidth, cell->width, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
check_minimum_width(t, t->tabwidth);
#endif /* not MATRIX */
}
#ifdef MATRIX
static void
set_integered_width(struct table *t, double *dwidth, short *iwidth)
{
int i, j, k, n, bcol, ecol, step;
short *indexarray;
char *fixed;
double *mod;
double sum = 0., x = 0.;
struct table_cell *cell = &t->cell;
int rulewidth = table_rule_width(t);
indexarray = NewAtom_N(short, t->maxcol + 1);
mod = NewAtom_N(double, t->maxcol + 1);
for (i = 0; i <= t->maxcol; i++) {
iwidth[i] = ceil_at_intervals(ceil(dwidth[i]), rulewidth);
mod[i] = (double)iwidth[i] - dwidth[i];
}
sum = 0.;
for (k = 0; k <= t->maxcol; k++) {
x = mod[k];
sum += x;
i = bsearch_double(x, mod, indexarray, k);
if (k > i) {
int ii;
for (ii = k; ii > i; ii--)
indexarray[ii] = indexarray[ii - 1];
}
indexarray[i] = k;
}
fixed = NewAtom_N(char, t->maxcol + 1);
bzero(fixed, t->maxcol + 1);
for (step = 0; step < 2; step++) {
for (i = 0; i <= t->maxcol; i += n) {
int nn;
short *idx;
double nsum;
if (sum < 0.5)
return;
for (n = 0; i + n <= t->maxcol; n++) {
int ii = indexarray[i + n];
if (n == 0)
x = mod[ii];
else if (fabs(mod[ii] - x) > 1e-6)
break;
}
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] < 2 &&
iwidth[ii] - rulewidth < t->minimum_width[ii])
fixed[ii] = 2;
if (fixed[ii] < 1 &&
iwidth[ii] - rulewidth < t->tabwidth[ii] &&
(double)rulewidth - mod[ii] > 0.5)
fixed[ii] = 1;
}
idx = NewAtom_N(short, n);
for (k = 0; k < cell->maxcell; k++) {
int kk, w, width, m;
j = cell->index[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
m = 0;
for (kk = 0; kk < n; kk++) {
int ii = indexarray[i + kk];
if (ii >= bcol && ii < ecol) {
idx[m] = ii;
m++;
}
}
if (m == 0)
continue;
width = (cell->colspan[j] - 1) * t->cellspacing;
for (kk = bcol; kk < ecol; kk++)
width += iwidth[kk];
w = 0;
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 2)
w += rulewidth;
}
if (width - w < cell->minimum_width[j]) {
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 2)
fixed[(int)idx[kk]] = 2;
}
}
w = 0;
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 1 &&
(double)rulewidth - mod[(int)idx[kk]] > 0.5)
w += rulewidth;
}
if (width - w < cell->width[j]) {
for (kk = 0; kk < m; kk++) {
if (fixed[(int)idx[kk]] < 1 &&
(double)rulewidth - mod[(int)idx[kk]] > 0.5)
fixed[(int)idx[kk]] = 1;
}
}
}
nn = 0;
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] <= step)
nn++;
}
nsum = sum - (double)(nn * rulewidth);
if (nsum < 0. && fabs(sum) <= fabs(nsum))
return;
for (k = 0; k < n; k++) {
int ii = indexarray[i + k];
if (fixed[ii] <= step) {
iwidth[ii] -= rulewidth;
fixed[ii] = 3;
}
}
sum = nsum;
}
}
}
static double
correlation_coefficient(double sxx, double syy, double sxy)
{
double coe, tmp;
tmp = sxx * syy;
if (tmp < Tiny)
tmp = Tiny;
coe = sxy / sqrt(tmp);
if (coe > 1.)
return 1.;
if (coe < -1.)
return -1.;
return coe;
}
static double
correlation_coefficient2(double sxx, double syy, double sxy)
{
double coe, tmp;
tmp = (syy + sxx - 2 * sxy) * sxx;
if (tmp < Tiny)
tmp = Tiny;
coe = (sxx - sxy) / sqrt(tmp);
if (coe > 1.)
return 1.;
if (coe < -1.)
return -1.;
return coe;
}
static double
recalc_width(double old, double swidth, int cwidth,
double sxx, double syy, double sxy, int is_inclusive)
{
double delta = swidth - (double)cwidth;
double rat = sxy / sxx,
coe = correlation_coefficient(sxx, syy, sxy), w, ww;
if (old < 0.)
old = 0.;
if (fabs(coe) < 1e-5)
return old;
w = rat * old;
ww = delta;
if (w > 0.) {
double wmin = 5e-3 * sqrt(syy * (1. - coe * coe));
if (swidth < 0.2 && cwidth > 0 && is_inclusive) {
double coe1 = correlation_coefficient2(sxx, syy, sxy);
if (coe > 0.9 || coe1 > 0.9)
return 0.;
}
if (wmin > 0.05)
wmin = 0.05;
if (ww < 0.)
ww = 0.;
ww += wmin;
}
else {
double wmin = 5e-3 * sqrt(syy) * fabs(coe);
if (rat > -0.001)
return old;
if (wmin > 0.01)
wmin = 0.01;
if (ww > 0.)
ww = 0.;
ww -= wmin;
}
if (w > ww)
return ww / rat;
return old;
}
static int
check_compressible_cell(struct table *t, MAT * minv,
double *newwidth, double *swidth, short *cwidth,
double totalwidth, double *Sxx,
int icol, int icell, double sxx, int corr)
{
struct table_cell *cell = &t->cell;
int i, j, k, m, bcol, ecol, span;
double delta, owidth;
double dmax, dmin, sxy;
int rulewidth = table_rule_width(t);
if (sxx < 10.)
return corr;
if (icol >= 0) {
owidth = newwidth[icol];
delta = newwidth[icol] - (double)t->tabwidth[icol];
bcol = icol;
ecol = bcol + 1;
}
else if (icell >= 0) {
owidth = swidth[icell];
delta = swidth[icell] - (double)cwidth[icell];
bcol = cell->col[icell];
ecol = bcol + cell->colspan[icell];
}
else {
owidth = totalwidth;
delta = totalwidth;
bcol = 0;
ecol = t->maxcol + 1;
}
dmin = delta;
dmax = -1.;
for (k = 0; k <= cell->maxcell; k++) {
int bcol1, ecol1;
int is_inclusive = 0;
if (dmin <= 0.)
goto _end;
j = cell->index[k];
if (j == icell)
continue;
bcol1 = cell->col[j];
ecol1 = bcol1 + cell->colspan[j];
sxy = 0.;
for (m = bcol1; m < ecol1; m++) {
for (i = bcol; i < ecol; i++)
sxy += m_entry(minv, i, m);
}
if (bcol1 >= bcol && ecol1 <= ecol) {
is_inclusive = 1;
}
if (sxy > 0.)
dmin = recalc_width(dmin, swidth[j], cwidth[j],
sxx, Sxx[j], sxy, is_inclusive);
else
dmax = recalc_width(dmax, swidth[j], cwidth[j],
sxx, Sxx[j], sxy, is_inclusive);
}
for (m = 0; m <= t->maxcol; m++) {
int is_inclusive = 0;
if (dmin <= 0.)
goto _end;
if (m == icol)
continue;
sxy = 0.;
for (i = bcol; i < ecol; i++)
sxy += m_entry(minv, i, m);
if (m >= bcol && m < ecol) {
is_inclusive = 1;
}
if (sxy > 0.)
dmin = recalc_width(dmin, newwidth[m], t->tabwidth[m],
sxx, m_entry(minv, m, m), sxy, is_inclusive);
else
dmax = recalc_width(dmax, newwidth[m], t->tabwidth[m],
sxx, m_entry(minv, m, m), sxy, is_inclusive);
}
_end:
if (dmax > 0. && dmin > dmax)
dmin = dmax;
span = ecol - bcol;
if ((span == t->maxcol + 1 && dmin >= 0.) ||
(span != t->maxcol + 1 && dmin > rulewidth * 0.5)) {
int nwidth = ceil_at_intervals(round(owidth - dmin), rulewidth);
correct_table_matrix(t, bcol, ecol - bcol, nwidth, 1.);
corr++;
}
return corr;
}
#define MAX_ITERATION 10
int
check_table_width(struct table *t, double *newwidth, MAT * minv, int itr)
{
int i, j, k, m, bcol, ecol;
int corr = 0;
struct table_cell *cell = &t->cell;
#ifdef __GNUC__
short orgwidth[t->maxcol + 1], corwidth[t->maxcol + 1];
short cwidth[cell->maxcell + 1];
double swidth[cell->maxcell + 1];
#else /* __GNUC__ */
short orgwidth[MAXCOL], corwidth[MAXCOL];
short cwidth[MAXCELL];
double swidth[MAXCELL];
#endif /* __GNUC__ */
double twidth, sxy, *Sxx, stotal;
twidth = 0.;
stotal = 0.;
for (i = 0; i <= t->maxcol; i++) {
twidth += newwidth[i];
stotal += m_entry(minv, i, i);
for (m = 0; m < i; m++) {
stotal += 2 * m_entry(minv, i, m);
}
}
Sxx = NewAtom_N(double, cell->maxcell + 1);
for (k = 0; k <= cell->maxcell; k++) {
j = cell->index[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
swidth[j] = 0.;
for (i = bcol; i < ecol; i++)
swidth[j] += newwidth[i];
cwidth[j] = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
Sxx[j] = 0.;
for (i = bcol; i < ecol; i++) {
Sxx[j] += m_entry(minv, i, i);
for (m = bcol; m <= ecol; m++) {
if (m < i)
Sxx[j] += 2 * m_entry(minv, i, m);
}
}
}
/* compress table */
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx, -1, -1, stotal, corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
/* compress multicolumn cell */
for (k = cell->maxcell; k >= 0; k--) {
j = cell->index[k];
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx,
-1, j, Sxx[j], corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
}
/* compress single column cell */
for (i = 0; i <= t->maxcol; i++) {
corr = check_compressible_cell(t, minv, newwidth, swidth,
cwidth, twidth, Sxx,
i, -1, m_entry(minv, i, i), corr);
if (itr < MAX_ITERATION && corr > 0)
return corr;
}
for (i = 0; i <= t->maxcol; i++)
corwidth[i] = orgwidth[i] = round(newwidth[i]);
check_minimum_width(t, corwidth);
for (i = 0; i <= t->maxcol; i++) {
double sx = sqrt(m_entry(minv, i, i));
if (sx < 0.1)
continue;
if (orgwidth[i] < t->minimum_width[i] &&
corwidth[i] == t->minimum_width[i]) {
double w = (sx > 0.5) ? 0.5 : sx * 0.2;
sxy = 0.;
for (m = 0; m <= t->maxcol; m++) {
if (m == i)
continue;
sxy += m_entry(minv, i, m);
}
if (sxy <= 0.) {
correct_table_matrix(t, i, 1, t->minimum_width[i], w);
corr++;
}
}
}
for (k = 0; k <= cell->maxcell; k++) {
int nwidth = 0, mwidth;
double sx;
j = cell->index[k];
sx = sqrt(Sxx[j]);
if (sx < 0.1)
continue;
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
for (i = bcol; i < ecol; i++)
nwidth += corwidth[i];
mwidth =
cell->minimum_width[j] - (cell->colspan[j] - 1) * t->cellspacing;
if (mwidth > swidth[j] && mwidth == nwidth) {
double w = (sx > 0.5) ? 0.5 : sx * 0.2;
sxy = 0.;
for (i = bcol; i < ecol; i++) {
for (m = 0; m <= t->maxcol; m++) {
if (m >= bcol && m < ecol)
continue;
sxy += m_entry(minv, i, m);
}
}
if (sxy <= 0.) {
correct_table_matrix(t, bcol, cell->colspan[j], mwidth, w);
corr++;
}
}
}
if (itr >= MAX_ITERATION)
return 0;
else
return corr;
}
#else /* not MATRIX */
void
set_table_width(struct table *t, short *newwidth, int maxwidth)
{
int i, j, k, bcol, ecol;
struct table_cell *cell = &t->cell;
char *fixed;
int swidth, fwidth, width, nvar;
double s;
double *dwidth;
int try_again;
fixed = NewAtom_N(char, t->maxcol + 1);
bzero(fixed, t->maxcol + 1);
dwidth = NewAtom_N(double, t->maxcol + 1);
for (i = 0; i <= t->maxcol; i++) {
dwidth[i] = 0.0;
if (t->fixed_width[i] < 0) {
t->fixed_width[i] = -t->fixed_width[i] * maxwidth / 100;
}
if (t->fixed_width[i] > 0) {
newwidth[i] = t->fixed_width[i];
fixed[i] = 1;
}
else
newwidth[i] = 0;
if (newwidth[i] < t->minimum_width[i])
newwidth[i] = t->minimum_width[i];
}
for (k = 0; k <= cell->maxcell; k++) {
j = cell->indexarray[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
if (cell->fixed_width[j] < 0)
cell->fixed_width[j] = -cell->fixed_width[j] * maxwidth / 100;
swidth = 0;
fwidth = 0;
nvar = 0;
for (i = bcol; i < ecol; i++) {
if (fixed[i]) {
fwidth += newwidth[i];
}
else {
swidth += newwidth[i];
nvar++;
}
}
width = max(cell->fixed_width[j], cell->minimum_width[j])
- (cell->colspan[j] - 1) * t->cellspacing;
if (nvar > 0 && width > fwidth + swidth) {
s = 0.;
for (i = bcol; i < ecol; i++) {
if (!fixed[i])
s += weight3(t->tabwidth[i]);
}
for (i = bcol; i < ecol; i++) {
if (!fixed[i])
dwidth[i] = (width - fwidth) * weight3(t->tabwidth[i]) / s;
else
dwidth[i] = (double)newwidth[i];
}
dv2sv(dwidth, newwidth, cell->colspan[j]);
if (cell->fixed_width[j] > 0) {
for (i = bcol; i < ecol; i++)
fixed[i] = 1;
}
}
}
do {
nvar = 0;
swidth = 0;
fwidth = 0;
for (i = 0; i <= t->maxcol; i++) {
if (fixed[i]) {
fwidth += newwidth[i];
}
else {
swidth += newwidth[i];
nvar++;
}
}
width = maxwidth - t->maxcol * t->cellspacing;
if (nvar == 0 || width <= fwidth + swidth)
break;
s = 0.;
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i])
s += weight3(t->tabwidth[i]);
}
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i])
dwidth[i] = (width - fwidth) * weight3(t->tabwidth[i]) / s;
else
dwidth[i] = (double)newwidth[i];
}
dv2sv(dwidth, newwidth, t->maxcol + 1);
try_again = 0;
for (i = 0; i <= t->maxcol; i++) {
if (!fixed[i]) {
if (newwidth[i] > t->tabwidth[i]) {
newwidth[i] = t->tabwidth[i];
fixed[i] = 1;
try_again = 1;
}
else if (newwidth[i] < t->minimum_width[i]) {
newwidth[i] = t->minimum_width[i];
fixed[i] = 1;
try_again = 1;
}
}
}
} while (try_again);
}
#endif /* not MATRIX */
void
check_table_height(struct table *t)
{
int i, j, k;
struct {
short *row;
short *rowspan;
short *indexarray;
short maxcell;
short size;
short *height;
} cell;
int space = 0;
cell.size = 0;
cell.maxcell = -1;
for (j = 0; j <= t->maxrow; j++) {
if (!t->tabattr[j])
continue;
for (i = 0; i <= t->maxcol; i++) {
int t_dep, rowspan;
if (t->tabattr[j][i] & (HTT_X | HTT_Y))
continue;
if (t->tabdata[j][i] == NULL)
t_dep = 0;
else
t_dep = t->tabdata[j][i]->nitem;
rowspan = table_rowspan(t, j, i);
if (rowspan > 1) {
int c = cell.maxcell + 1;
k = bsearch_2short(rowspan, cell.rowspan,
j, cell.row, t->maxrow + 1, cell.indexarray,
c);
if (k <= cell.maxcell) {
int idx = cell.indexarray[k];
if (cell.row[idx] == j && cell.rowspan[idx] == rowspan)
c = idx;
}
if (c >= MAXROWCELL)
continue;
if (c >= cell.size) {
if (cell.size == 0) {
cell.size = max(MAXCELL, c + 1);
cell.row = NewAtom_N(short, cell.size);
cell.rowspan = NewAtom_N(short, cell.size);
cell.indexarray = NewAtom_N(short, cell.size);
cell.height = NewAtom_N(short, cell.size);
}
else {
cell.size = max(cell.size + MAXCELL, c + 1);
cell.row = New_Reuse(short, cell.row, cell.size);
cell.rowspan = New_Reuse(short, cell.rowspan,
cell.size);
cell.indexarray = New_Reuse(short, cell.indexarray,
cell.size);
cell.height = New_Reuse(short, cell.height, cell.size);
}
}
if (c > cell.maxcell) {
cell.maxcell++;
cell.row[cell.maxcell] = j;
cell.rowspan[cell.maxcell] = rowspan;
cell.height[cell.maxcell] = 0;
if (cell.maxcell > k) {
int ii;
for (ii = cell.maxcell; ii > k; ii--)
cell.indexarray[ii] = cell.indexarray[ii - 1];
}
cell.indexarray[k] = cell.maxcell;
}
if (cell.height[c] < t_dep)
cell.height[c] = t_dep;
continue;
}
if (t->tabheight[j] < t_dep)
t->tabheight[j] = t_dep;
}
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
space = 1;
break;
case BORDER_NONE:
space = 0;
}
check_cell_width(t->tabheight, cell.height, cell.row, cell.rowspan,
cell.maxcell, cell.indexarray, space, 1);
}
#define CHECK_MINIMUM 1
#define CHECK_FIXED 2
int
get_table_width(struct table *t, short *orgwidth, short *cellwidth, int flag)
{
#ifdef __GNUC__
short newwidth[t->maxcol + 1];
#else /* not __GNUC__ */
short newwidth[MAXCOL];
#endif /* not __GNUC__ */
int i;
int swidth;
struct table_cell *cell = &t->cell;
int rulewidth = table_rule_width(t);
for (i = 0; i <= t->maxcol; i++)
newwidth[i] = max(orgwidth[i], 0);
if (flag & CHECK_FIXED) {
#ifdef __GNUC__
short ccellwidth[cell->maxcell + 1];
#else /* not __GNUC__ */
short ccellwidth[MAXCELL];
#endif /* not __GNUC__ */
for (i = 0; i <= t->maxcol; i++) {
if (newwidth[i] < t->fixed_width[i])
newwidth[i] = t->fixed_width[i];
}
for (i = 0; i <= cell->maxcell; i++) {
ccellwidth[i] = cellwidth[i];
if (ccellwidth[i] < cell->fixed_width[i])
ccellwidth[i] = cell->fixed_width[i];
}
check_cell_width(newwidth, ccellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
else {
check_cell_width(newwidth, cellwidth, cell->col, cell->colspan,
cell->maxcell, cell->index, t->cellspacing, 0);
}
if (flag & CHECK_MINIMUM)
check_minimum_width(t, newwidth);
swidth = 0;
for (i = 0; i <= t->maxcol; i++) {
swidth += ceil_at_intervals(newwidth[i], rulewidth);
}
swidth += table_border_width(t);
return swidth;
}
#define minimum_table_width(t)\
(get_table_width(t,t->minimum_width,t->cell.minimum_width,0))
#define maximum_table_width(t)\
(get_table_width(t,t->tabwidth,t->cell.width,CHECK_FIXED))
#define fixed_table_width(t)\
(get_table_width(t,t->fixed_width,t->cell.fixed_width,CHECK_MINIMUM))
#define MAX_COTABLE_LEVEL 100
static int cotable_level;
void
initRenderTable(void)
{
cotable_level = 0;
}
void
renderCoTable(struct table *tbl, int maxlimit)
{
struct readbuffer obuf;
struct html_feed_environ h_env;
struct environment envs[MAX_ENV_LEVEL];
struct table *t;
int i, col, row;
int indent, maxwidth;
if (cotable_level >= MAX_COTABLE_LEVEL)
return; /* workaround to prevent infinite recursion */
cotable_level++;
for (i = 0; i < tbl->ntable; i++) {
t = tbl->tables[i].ptr;
if (t == NULL)
continue;
col = tbl->tables[i].col;
row = tbl->tables[i].row;
indent = tbl->tables[i].indent;
init_henv(&h_env, &obuf, envs, MAX_ENV_LEVEL, tbl->tables[i].buf,
get_spec_cell_width(tbl, row, col), indent);
check_row(tbl, row);
if (h_env.limit > maxlimit)
h_env.limit = maxlimit;
if (t->total_width == 0)
maxwidth = h_env.limit - indent;
else if (t->total_width > 0)
maxwidth = t->total_width;
else
maxwidth = t->total_width = -t->total_width * h_env.limit / 100;
renderTable(t, maxwidth, &h_env);
}
}
static void
make_caption(struct table *t, struct html_feed_environ *h_env)
{
struct html_feed_environ henv;
struct readbuffer obuf;
struct environment envs[MAX_ENV_LEVEL];
int limit;
if (t->caption->length <= 0)
return;
if (t->total_width > 0)
limit = t->total_width;
else
limit = h_env->limit;
init_henv(&henv, &obuf, envs, MAX_ENV_LEVEL, newTextLineList(),
limit, h_env->envs[h_env->envc].indent);
HTMLlineproc1("<center>", &henv);
HTMLlineproc0(t->caption->ptr, &henv, FALSE);
HTMLlineproc1("</center>", &henv);
if (t->total_width < henv.maxlimit)
t->total_width = henv.maxlimit;
limit = h_env->limit;
h_env->limit = t->total_width;
HTMLlineproc1("<center>", h_env);
HTMLlineproc0(t->caption->ptr, h_env, FALSE);
HTMLlineproc1("</center>", h_env);
h_env->limit = limit;
}
void
renderTable(struct table *t, int max_width, struct html_feed_environ *h_env)
{
int i, j, w, r, h;
Str renderbuf;
short new_tabwidth[MAXCOL] = { 0 };
#ifdef MATRIX
int itr;
VEC *newwidth;
MAT *mat, *minv;
PERM *pivot;
#endif /* MATRIX */
int width;
int rulewidth;
Str vrulea = NULL, vruleb = NULL, vrulec = NULL;
#ifdef ID_EXT
Str idtag;
#endif /* ID_EXT */
t->total_height = 0;
if (t->maxcol < 0) {
make_caption(t, h_env);
return;
}
if (t->sloppy_width > max_width)
max_width = t->sloppy_width;
rulewidth = table_rule_width(t);
max_width -= table_border_width(t);
if (rulewidth > 1)
max_width = floor_at_intervals(max_width, rulewidth);
if (max_width < rulewidth)
max_width = rulewidth;
#define MAX_TABWIDTH 10000
if (max_width > MAX_TABWIDTH)
max_width = MAX_TABWIDTH;
check_maximum_width(t);
#ifdef MATRIX
if (t->maxcol == 0) {
if (t->tabwidth[0] > max_width)
t->tabwidth[0] = max_width;
if (t->total_width > 0)
t->tabwidth[0] = max_width;
else if (t->fixed_width[0] > 0)
t->tabwidth[0] = t->fixed_width[0];
if (t->tabwidth[0] < t->minimum_width[0])
t->tabwidth[0] = t->minimum_width[0];
}
else {
set_table_matrix(t, max_width);
itr = 0;
mat = m_get(t->maxcol + 1, t->maxcol + 1);
pivot = px_get(t->maxcol + 1);
newwidth = v_get(t->maxcol + 1);
minv = m_get(t->maxcol + 1, t->maxcol + 1);
do {
m_copy(t->matrix, mat);
LUfactor(mat, pivot);
LUsolve(mat, pivot, t->vector, newwidth);
LUinverse(mat, pivot, minv);
#ifdef TABLE_DEBUG
set_integered_width(t, newwidth->ve, new_tabwidth);
fprintf(stderr, "itr=%d\n", itr);
fprintf(stderr, "max_width=%d\n", max_width);
fprintf(stderr, "minimum : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", t->minimum_width[i]);
fprintf(stderr, "\nfixed : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", t->fixed_width[i]);
fprintf(stderr, "\ndecided : ");
for (i = 0; i <= t->maxcol; i++)
fprintf(stderr, "%2d ", new_tabwidth[i]);
fprintf(stderr, "\n");
#endif /* TABLE_DEBUG */
itr++;
} while (check_table_width(t, newwidth->ve, minv, itr));
set_integered_width(t, newwidth->ve, new_tabwidth);
check_minimum_width(t, new_tabwidth);
v_free(newwidth);
px_free(pivot);
m_free(mat);
m_free(minv);
m_free(t->matrix);
v_free(t->vector);
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = new_tabwidth[i];
}
}
#else /* not MATRIX */
set_table_width(t, new_tabwidth, max_width);
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = new_tabwidth[i];
}
#endif /* not MATRIX */
check_minimum_width(t, t->tabwidth);
for (i = 0; i <= t->maxcol; i++)
t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);
renderCoTable(t, h_env->limit);
for (i = 0; i <= t->maxcol; i++) {
for (j = 0; j <= t->maxrow; j++) {
check_row(t, j);
if (t->tabattr[j][i] & HTT_Y)
continue;
do_refill(t, j, i, h_env->limit);
}
}
check_minimum_width(t, t->tabwidth);
t->total_width = 0;
for (i = 0; i <= t->maxcol; i++) {
t->tabwidth[i] = ceil_at_intervals(t->tabwidth[i], rulewidth);
t->total_width += t->tabwidth[i];
}
t->total_width += table_border_width(t);
check_table_height(t);
for (i = 0; i <= t->maxcol; i++) {
for (j = 0; j <= t->maxrow; j++) {
TextLineList *l;
int k;
if ((t->tabattr[j][i] & HTT_Y) ||
(t->tabattr[j][i] & HTT_TOP) || (t->tabdata[j][i] == NULL))
continue;
h = t->tabheight[j];
for (k = j + 1; k <= t->maxrow; k++) {
if (!(t->tabattr[k][i] & HTT_Y))
break;
h += t->tabheight[k];
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
h += 1;
break;
}
}
h -= t->tabdata[j][i]->nitem;
if (t->tabattr[j][i] & HTT_MIDDLE)
h /= 2;
if (h <= 0)
continue;
l = newTextLineList();
for (k = 0; k < h; k++)
pushTextLine(l, newTextLine(NULL, 0));
t->tabdata[j][i] = appendGeneralList((GeneralList *)l,
t->tabdata[j][i]);
}
}
/* table output */
width = t->total_width;
make_caption(t, h_env);
HTMLlineproc1("<pre for_table>", h_env);
#ifdef ID_EXT
if (t->id != NULL) {
idtag = Sprintf("<_id id=\"%s\">", html_quote((t->id)->ptr));
HTMLlineproc1(idtag->ptr, h_env);
}
#endif /* ID_EXT */
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
renderbuf = Strnew();
print_sep(t, -1, T_TOP, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
t->total_height += 1;
break;
}
vruleb = Strnew();
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
vrulea = Strnew();
vrulec = Strnew();
push_symbol(vrulea, TK_VERTICALBAR(t->border_mode), symbol_width, 1);
for (i = 0; i < t->cellpadding; i++) {
Strcat_char(vrulea, ' ');
Strcat_char(vruleb, ' ');
Strcat_char(vrulec, ' ');
}
push_symbol(vrulec, TK_VERTICALBAR(t->border_mode), symbol_width, 1);
case BORDER_NOWIN:
push_symbol(vruleb, TK_VERTICALBAR(BORDER_THIN), symbol_width, 1);
for (i = 0; i < t->cellpadding; i++)
Strcat_char(vruleb, ' ');
break;
case BORDER_NONE:
for (i = 0; i < t->cellspacing; i++)
Strcat_char(vruleb, ' ');
}
for (r = 0; r <= t->maxrow; r++) {
for (h = 0; h < t->tabheight[r]; h++) {
renderbuf = Strnew();
if (t->border_mode == BORDER_THIN
|| t->border_mode == BORDER_THICK)
Strcat(renderbuf, vrulea);
#ifdef ID_EXT
if (t->tridvalue[r] != NULL && h == 0) {
idtag = Sprintf("<_id id=\"%s\">",
html_quote((t->tridvalue[r])->ptr));
Strcat(renderbuf, idtag);
}
#endif /* ID_EXT */
for (i = 0; i <= t->maxcol; i++) {
check_row(t, r);
#ifdef ID_EXT
if (t->tabidvalue[r][i] != NULL && h == 0) {
idtag = Sprintf("<_id id=\"%s\">",
html_quote((t->tabidvalue[r][i])->ptr));
Strcat(renderbuf, idtag);
}
#endif /* ID_EXT */
if (!(t->tabattr[r][i] & HTT_X)) {
w = t->tabwidth[i];
for (j = i + 1;
j <= t->maxcol && (t->tabattr[r][j] & HTT_X); j++)
w += t->tabwidth[j] + t->cellspacing;
if (t->tabattr[r][i] & HTT_Y) {
for (j = r - 1; j >= 0 && t->tabattr[j]
&& (t->tabattr[j][i] & HTT_Y); j--) ;
print_item(t, j, i, w, renderbuf);
}
else
print_item(t, r, i, w, renderbuf);
}
if (i < t->maxcol && !(t->tabattr[r][i + 1] & HTT_X))
Strcat(renderbuf, vruleb);
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
Strcat(renderbuf, vrulec);
t->total_height += 1;
break;
}
push_render_image(renderbuf, width, t->total_width, h_env);
}
if (r < t->maxrow && t->border_mode != BORDER_NONE) {
renderbuf = Strnew();
print_sep(t, r, T_MIDDLE, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
}
t->total_height += t->tabheight[r];
}
switch (t->border_mode) {
case BORDER_THIN:
case BORDER_THICK:
renderbuf = Strnew();
print_sep(t, t->maxrow, T_BOTTOM, t->maxcol, renderbuf);
push_render_image(renderbuf, width, t->total_width, h_env);
t->total_height += 1;
break;
}
if (t->total_height == 0) {
renderbuf = Strnew_charp(" ");
t->total_height++;
t->total_width = 1;
push_render_image(renderbuf, 1, t->total_width, h_env);
}
HTMLlineproc1("</pre>", h_env);
}
#ifdef TABLE_NO_COMPACT
#define THR_PADDING 2
#else
#define THR_PADDING 4
#endif
struct table *
begin_table(int border, int spacing, int padding, int vspace)
{
struct table *t;
int mincell = minimum_cellspacing(border);
int rcellspacing;
int mincell_pixels = round(mincell * pixel_per_char);
int ppc = round(pixel_per_char);
t = newTable();
t->row = t->col = -1;
t->maxcol = -1;
t->maxrow = -1;
t->border_mode = border;
t->flag = 0;
if (border == BORDER_NOWIN)
t->flag |= TBL_EXPAND_OK;
rcellspacing = spacing + 2 * padding;
switch (border) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
t->cellpadding = padding - (mincell_pixels - 4) / 2;
break;
case BORDER_NONE:
t->cellpadding = rcellspacing - mincell_pixels;
}
if (t->cellpadding >= ppc)
t->cellpadding /= ppc;
else if (t->cellpadding > 0)
t->cellpadding = 1;
else
t->cellpadding = 0;
switch (border) {
case BORDER_THIN:
case BORDER_THICK:
case BORDER_NOWIN:
t->cellspacing = 2 * t->cellpadding + mincell;
break;
case BORDER_NONE:
t->cellspacing = t->cellpadding + mincell;
}
if (border == BORDER_NONE) {
if (rcellspacing / 2 + vspace <= 1)
t->vspace = 0;
else
t->vspace = 1;
}
else {
if (vspace < ppc)
t->vspace = 0;
else
t->vspace = 1;
}
if (border == BORDER_NONE) {
if (rcellspacing <= THR_PADDING)
t->vcellpadding = 0;
else
t->vcellpadding = 1;
}
else {
if (padding < 2 * ppc - 2)
t->vcellpadding = 0;
else
t->vcellpadding = 1;
}
return t;
}
void
end_table(struct table *tbl)
{
struct table_cell *cell = &tbl->cell;
int i, rulewidth = table_rule_width(tbl);
if (rulewidth > 1) {
if (tbl->total_width > 0)
tbl->total_width = ceil_at_intervals(tbl->total_width, rulewidth);
for (i = 0; i <= tbl->maxcol; i++) {
tbl->minimum_width[i] =
ceil_at_intervals(tbl->minimum_width[i], rulewidth);
tbl->tabwidth[i] = ceil_at_intervals(tbl->tabwidth[i], rulewidth);
if (tbl->fixed_width[i] > 0)
tbl->fixed_width[i] =
ceil_at_intervals(tbl->fixed_width[i], rulewidth);
}
for (i = 0; i <= cell->maxcell; i++) {
cell->minimum_width[i] =
ceil_at_intervals(cell->minimum_width[i], rulewidth);
cell->width[i] = ceil_at_intervals(cell->width[i], rulewidth);
if (cell->fixed_width[i] > 0)
cell->fixed_width[i] =
ceil_at_intervals(cell->fixed_width[i], rulewidth);
}
}
tbl->sloppy_width = fixed_table_width(tbl);
if (tbl->total_width > tbl->sloppy_width)
tbl->sloppy_width = tbl->total_width;
}
static void
check_minimum0(struct table *t, int min)
{
int i, w, ww;
struct table_cell *cell;
if (t->col < 0)
return;
if (t->tabwidth[t->col] < 0)
return;
check_row(t, t->row);
w = table_colspan(t, t->row, t->col);
min += t->indent;
if (w == 1)
ww = min;
else {
cell = &t->cell;
ww = 0;
if (cell->icell >= 0 && cell->minimum_width[cell->icell] < min)
cell->minimum_width[cell->icell] = min;
}
for (i = t->col;
i <= t->maxcol && (i == t->col || (t->tabattr[t->row][i] & HTT_X));
i++) {
if (t->minimum_width[i] < ww)
t->minimum_width[i] = ww;
}
}
static int
setwidth0(struct table *t, struct table_mode *mode)
{
int w;
int width = t->tabcontentssize;
struct table_cell *cell = &t->cell;
if (t->col < 0)
return -1;
if (t->tabwidth[t->col] < 0)
return -1;
check_row(t, t->row);
if (t->linfo.prev_spaces > 0)
width -= t->linfo.prev_spaces;
w = table_colspan(t, t->row, t->col);
if (w == 1) {
if (t->tabwidth[t->col] < width)
t->tabwidth[t->col] = width;
}
else if (cell->icell >= 0) {
if (cell->width[cell->icell] < width)
cell->width[cell->icell] = width;
}
return width;
}
static void
setwidth(struct table *t, struct table_mode *mode)
{
int width = setwidth0(t, mode);
if (width < 0)
return;
#ifdef NOWRAP
if (t->tabattr[t->row][t->col] & HTT_NOWRAP)
check_minimum0(t, width);
#endif /* NOWRAP */
if (mode->pre_mode & (TBLM_NOBR | TBLM_PRE | TBLM_PRE_INT) &&
mode->nobr_offset >= 0)
check_minimum0(t, width - mode->nobr_offset);
}
static void
addcontentssize(struct table *t, int width)
{
if (t->col < 0)
return;
if (t->tabwidth[t->col] < 0)
return;
check_row(t, t->row);
t->tabcontentssize += width;
}
static void table_close_anchor0(struct table *tbl, struct table_mode *mode);
static void
clearcontentssize(struct table *t, struct table_mode *mode)
{
table_close_anchor0(t, mode);
mode->nobr_offset = 0;
t->linfo.prev_spaces = -1;
set_space_to_prevchar(t->linfo.prevchar);
t->linfo.prev_ctype = PC_ASCII;
t->linfo.length = 0;
t->tabcontentssize = 0;
}
static void
begin_cell(struct table *t, struct table_mode *mode)
{
clearcontentssize(t, mode);
mode->indent_level = 0;
mode->nobr_level = 0;
mode->pre_mode = 0;
t->indent = 0;
t->flag |= TBL_IN_COL;
if (t->suspended_data) {
check_row(t, t->row);
if (t->tabdata[t->row][t->col] == NULL)
t->tabdata[t->row][t->col] = newGeneralList();
appendGeneralList(t->tabdata[t->row][t->col],
(GeneralList *)t->suspended_data);
t->suspended_data = NULL;
}
}
void
check_rowcol(struct table *tbl, struct table_mode *mode)
{
int row = tbl->row, col = tbl->col;
if (!(tbl->flag & TBL_IN_ROW)) {
tbl->flag |= TBL_IN_ROW;
tbl->row++;
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
tbl->col = -1;
}
if (tbl->row == -1)
tbl->row = 0;
if (tbl->col == -1)
tbl->col = 0;
for (;; tbl->row++) {
check_row(tbl, tbl->row);
for (; tbl->col < MAXCOL &&
tbl->tabattr[tbl->row][tbl->col] & (HTT_X | HTT_Y); tbl->col++) ;
if (tbl->col < MAXCOL)
break;
tbl->col = 0;
}
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
if (tbl->col > tbl->maxcol)
tbl->maxcol = tbl->col;
if (tbl->row != row || tbl->col != col)
begin_cell(tbl, mode);
tbl->flag |= TBL_IN_COL;
}
int
skip_space(struct table *t, char *line, struct table_linfo *linfo,
int checkminimum)
{
int skip = 0, s = linfo->prev_spaces;
Lineprop ctype, prev_ctype = linfo->prev_ctype;
Str prevchar = linfo->prevchar;
int w = linfo->length;
int min = 1;
if (*line == '<' && line[strlen(line) - 1] == '>') {
if (checkminimum)
check_minimum0(t, visible_length(line));
return 0;
}
while (*line) {
char *save = line, *c = line;
int ec, len, wlen, plen;
ctype = get_mctype(line);
len = get_mcwidth(line);
wlen = plen = get_mclen(line);
if (min < w)
min = w;
if (ctype == PC_ASCII && IS_SPACE(*c)) {
w = 0;
s++;
}
else {
if (*c == '&') {
ec = getescapechar(&line);
if (ec >= 0) {
c = conv_entity(ec);
ctype = get_mctype(c);
len = get_strwidth(c);
wlen = line - save;
plen = get_mclen(c);
}
}
if (prevchar->length && is_boundary((unsigned char *)prevchar->ptr,
(unsigned char *)c)) {
w = len;
}
else {
w += len;
}
if (s > 0) {
#ifdef USE_M17N
if (ctype == PC_KANJI1 && prev_ctype == PC_KANJI1)
skip += s;
else
#endif
skip += s - 1;
}
s = 0;
prev_ctype = ctype;
}
set_prevchar(prevchar, c, plen);
line = save + wlen;
}
if (s > 1) {
skip += s - 1;
linfo->prev_spaces = 1;
}
else {
linfo->prev_spaces = s;
}
linfo->prev_ctype = prev_ctype;
linfo->prevchar = prevchar;
if (checkminimum) {
if (min < w)
min = w;
linfo->length = w;
check_minimum0(t, min);
}
return skip;
}
static void
feed_table_inline_tag(struct table *tbl,
char *line, struct table_mode *mode, int width)
{
check_rowcol(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
if (width >= 0) {
check_minimum0(tbl, width);
addcontentssize(tbl, width);
setwidth(tbl, mode);
}
}
static void
feed_table_block_tag(struct table *tbl,
char *line, struct table_mode *mode, int indent, int cmd)
{
int offset;
if (mode->indent_level <= 0 && indent == -1)
return;
if (mode->indent_level >= CHAR_MAX && indent == 1)
return;
setwidth(tbl, mode);
feed_table_inline_tag(tbl, line, mode, -1);
clearcontentssize(tbl, mode);
if (indent == 1) {
mode->indent_level++;
if (mode->indent_level <= MAX_INDENT_LEVEL)
tbl->indent += INDENT_INCR;
}
else if (indent == -1) {
mode->indent_level--;
if (mode->indent_level < MAX_INDENT_LEVEL)
tbl->indent -= INDENT_INCR;
}
offset = tbl->indent;
if (cmd == HTML_DT) {
if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL)
offset -= INDENT_INCR;
}
if (tbl->indent > 0) {
check_minimum0(tbl, 0);
addcontentssize(tbl, offset);
}
}
static void
table_close_select(struct table *tbl, struct table_mode *mode, int width)
{
Str tmp = process_n_select();
mode->pre_mode &= ~TBLM_INSELECT;
mode->end_tag = 0;
feed_table1(tbl, tmp, mode, width);
}
static void
table_close_textarea(struct table *tbl, struct table_mode *mode, int width)
{
Str tmp = process_n_textarea();
mode->pre_mode &= ~TBLM_INTXTA;
mode->end_tag = 0;
feed_table1(tbl, tmp, mode, width);
}
static void
table_close_anchor0(struct table *tbl, struct table_mode *mode)
{
if (!(mode->pre_mode & TBLM_ANCHOR))
return;
mode->pre_mode &= ~TBLM_ANCHOR;
if (tbl->tabcontentssize == mode->anchor_offset) {
check_minimum0(tbl, 1);
addcontentssize(tbl, 1);
setwidth(tbl, mode);
}
else if (tbl->linfo.prev_spaces > 0 &&
tbl->tabcontentssize - 1 == mode->anchor_offset) {
if (tbl->linfo.prev_spaces > 0)
tbl->linfo.prev_spaces = -1;
}
}
#define TAG_ACTION_NONE 0
#define TAG_ACTION_FEED 1
#define TAG_ACTION_TABLE 2
#define TAG_ACTION_N_TABLE 3
#define TAG_ACTION_PLAIN 4
#define CASE_TABLE_TAG \
case HTML_TABLE:\
case HTML_N_TABLE:\
case HTML_TR:\
case HTML_N_TR:\
case HTML_TD:\
case HTML_N_TD:\
case HTML_TH:\
case HTML_N_TH:\
case HTML_THEAD:\
case HTML_N_THEAD:\
case HTML_TBODY:\
case HTML_N_TBODY:\
case HTML_TFOOT:\
case HTML_N_TFOOT:\
case HTML_COLGROUP:\
case HTML_N_COLGROUP:\
case HTML_COL
#define ATTR_ROWSPAN_MAX 32766
static int
feed_table_tag(struct table *tbl, char *line, struct table_mode *mode,
int width, struct parsed_tag *tag)
{
int cmd;
#ifdef ID_EXT
char *p;
#endif
struct table_cell *cell = &tbl->cell;
int colspan, rowspan;
int col, prev_col;
int i, j, k, v, v0, w, id;
Str tok, tmp, anchor;
table_attr align, valign;
cmd = tag->tagid;
if (mode->pre_mode & TBLM_PLAIN) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_PLAIN;
mode->end_tag = 0;
feed_table_block_tag(tbl, line, mode, 0, cmd);
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
if (mode->pre_mode & TBLM_INTXTA) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_TEXTAREA:
table_close_textarea(tbl, mode, width);
if (cmd == HTML_N_TEXTAREA)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->pre_mode & TBLM_SCRIPT) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_SCRIPT;
mode->end_tag = 0;
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
if (mode->pre_mode & TBLM_STYLE) {
if (mode->end_tag == cmd) {
mode->pre_mode &= ~TBLM_STYLE;
mode->end_tag = 0;
return TAG_ACTION_NONE;
}
return TAG_ACTION_PLAIN;
}
/* failsafe: a tag other than <option></option>and </select> in *
* <select> environment is regarded as the end of <select>. */
if (mode->pre_mode & TBLM_INSELECT) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_FORM:
case HTML_N_SELECT: /* mode->end_tag */
table_close_select(tbl, mode, width);
if (cmd == HTML_N_SELECT)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->caption) {
switch (cmd) {
CASE_TABLE_TAG:
case HTML_N_CAPTION:
mode->caption = 0;
if (cmd == HTML_N_CAPTION)
return TAG_ACTION_NONE;
break;
default:
return TAG_ACTION_FEED;
}
}
if (mode->pre_mode & TBLM_PRE) {
switch (cmd) {
case HTML_NOBR:
case HTML_N_NOBR:
case HTML_PRE_INT:
case HTML_N_PRE_INT:
return TAG_ACTION_NONE;
}
}
switch (cmd) {
case HTML_TABLE:
check_rowcol(tbl, mode);
return TAG_ACTION_TABLE;
case HTML_N_TABLE:
if (tbl->suspended_data)
check_rowcol(tbl, mode);
return TAG_ACTION_N_TABLE;
case HTML_TR:
if (tbl->col >= 0 && tbl->tabcontentssize > 0)
setwidth(tbl, mode);
tbl->col = -1;
tbl->row++;
tbl->flag |= TBL_IN_ROW;
tbl->flag &= ~TBL_IN_COL;
align = 0;
valign = 0;
if (parsedtag_get_value(tag, ATTR_ALIGN, &i)) {
switch (i) {
case ALIGN_LEFT:
align = (HTT_LEFT | HTT_TRSET);
break;
case ALIGN_RIGHT:
align = (HTT_RIGHT | HTT_TRSET);
break;
case ALIGN_CENTER:
align = (HTT_CENTER | HTT_TRSET);
break;
}
}
if (parsedtag_get_value(tag, ATTR_VALIGN, &i)) {
switch (i) {
case VALIGN_TOP:
valign = (HTT_TOP | HTT_VTRSET);
break;
case VALIGN_MIDDLE:
valign = (HTT_MIDDLE | HTT_VTRSET);
break;
case VALIGN_BOTTOM:
valign = (HTT_BOTTOM | HTT_VTRSET);
break;
}
}
#ifdef ID_EXT
if (parsedtag_get_value(tag, ATTR_ID, &p)) {
check_row(tbl, tbl->row);
tbl->tridvalue[tbl->row] = Strnew_charp(p);
}
#endif /* ID_EXT */
tbl->trattr = align | valign;
break;
case HTML_TH:
case HTML_TD:
prev_col = tbl->col;
if (tbl->col >= 0 && tbl->tabcontentssize > 0)
setwidth(tbl, mode);
if (tbl->row == -1) {
/* for broken HTML... */
tbl->row = -1;
tbl->col = -1;
tbl->maxrow = tbl->row;
}
if (tbl->col == -1) {
if (!(tbl->flag & TBL_IN_ROW)) {
tbl->row++;
tbl->flag |= TBL_IN_ROW;
}
if (tbl->row > tbl->maxrow)
tbl->maxrow = tbl->row;
}
tbl->col++;
check_row(tbl, tbl->row);
while (tbl->col < MAXCOL && tbl->tabattr[tbl->row][tbl->col]) {
tbl->col++;
}
if (tbl->col > MAXCOL - 1) {
tbl->col = prev_col;
return TAG_ACTION_NONE;
}
if (tbl->col > tbl->maxcol) {
tbl->maxcol = tbl->col;
}
colspan = rowspan = 1;
if (tbl->trattr & HTT_TRSET)
align = (tbl->trattr & HTT_ALIGN);
else if (cmd == HTML_TH)
align = HTT_CENTER;
else
align = HTT_LEFT;
if (tbl->trattr & HTT_VTRSET)
valign = (tbl->trattr & HTT_VALIGN);
else
valign = HTT_MIDDLE;
if (parsedtag_get_value(tag, ATTR_ROWSPAN, &rowspan)) {
if(rowspan > ATTR_ROWSPAN_MAX) {
rowspan = ATTR_ROWSPAN_MAX;
}
if ((tbl->row + rowspan) >= tbl->max_rowsize)
check_row(tbl, tbl->row + rowspan);
}
if (rowspan < 1)
rowspan = 1;
if (parsedtag_get_value(tag, ATTR_COLSPAN, &colspan)) {
if ((tbl->col + colspan) >= MAXCOL) {
/* Can't expand column */
colspan = MAXCOL - tbl->col;
}
}
if (colspan < 1)
colspan = 1;
if (parsedtag_get_value(tag, ATTR_ALIGN, &i)) {
switch (i) {
case ALIGN_LEFT:
align = HTT_LEFT;
break;
case ALIGN_RIGHT:
align = HTT_RIGHT;
break;
case ALIGN_CENTER:
align = HTT_CENTER;
break;
}
}
if (parsedtag_get_value(tag, ATTR_VALIGN, &i)) {
switch (i) {
case VALIGN_TOP:
valign = HTT_TOP;
break;
case VALIGN_MIDDLE:
valign = HTT_MIDDLE;
break;
case VALIGN_BOTTOM:
valign = HTT_BOTTOM;
break;
}
}
#ifdef NOWRAP
if (parsedtag_exists(tag, ATTR_NOWRAP))
tbl->tabattr[tbl->row][tbl->col] |= HTT_NOWRAP;
#endif /* NOWRAP */
v = 0;
if (parsedtag_get_value(tag, ATTR_WIDTH, &v)) {
#ifdef TABLE_EXPAND
if (v > 0) {
if (tbl->real_width > 0)
v = -(v * 100) / (tbl->real_width * pixel_per_char);
else
v = (int)(v / pixel_per_char);
}
#else
v = RELATIVE_WIDTH(v);
#endif /* not TABLE_EXPAND */
}
#ifdef ID_EXT
if (parsedtag_get_value(tag, ATTR_ID, &p))
tbl->tabidvalue[tbl->row][tbl->col] = Strnew_charp(p);
#endif /* ID_EXT */
#ifdef NOWRAP
if (v != 0) {
/* NOWRAP and WIDTH= conflicts each other */
tbl->tabattr[tbl->row][tbl->col] &= ~HTT_NOWRAP;
}
#endif /* NOWRAP */
tbl->tabattr[tbl->row][tbl->col] &= ~(HTT_ALIGN | HTT_VALIGN);
tbl->tabattr[tbl->row][tbl->col] |= (align | valign);
if (colspan > 1) {
col = tbl->col;
cell->icell = cell->maxcell + 1;
k = bsearch_2short(colspan, cell->colspan, col, cell->col, MAXCOL,
cell->index, cell->icell);
if (k <= cell->maxcell) {
i = cell->index[k];
if (cell->col[i] == col && cell->colspan[i] == colspan)
cell->icell = i;
}
if (cell->icell > cell->maxcell && cell->icell < MAXCELL) {
cell->maxcell++;
cell->col[cell->maxcell] = col;
cell->colspan[cell->maxcell] = colspan;
cell->width[cell->maxcell] = 0;
cell->minimum_width[cell->maxcell] = 0;
cell->fixed_width[cell->maxcell] = 0;
if (cell->maxcell > k) {
int ii;
for (ii = cell->maxcell; ii > k; ii--)
cell->index[ii] = cell->index[ii - 1];
}
cell->index[k] = cell->maxcell;
}
if (cell->icell > cell->maxcell)
cell->icell = -1;
}
if (v != 0) {
if (colspan == 1) {
v0 = tbl->fixed_width[tbl->col];
if (v0 == 0 || (v0 > 0 && v > v0) || (v0 < 0 && v < v0)) {
#ifdef FEED_TABLE_DEBUG
fprintf(stderr, "width(%d) = %d\n", tbl->col, v);
#endif /* TABLE_DEBUG */
tbl->fixed_width[tbl->col] = v;
}
}
else if (cell->icell >= 0) {
v0 = cell->fixed_width[cell->icell];
if (v0 == 0 || (v0 > 0 && v > v0) || (v0 < 0 && v < v0))
cell->fixed_width[cell->icell] = v;
}
}
for (i = 0; i < rowspan; i++) {
check_row(tbl, tbl->row + i);
for (j = 0; j < colspan; j++) {
#if 0
tbl->tabattr[tbl->row + i][tbl->col + j] &= ~(HTT_X | HTT_Y);
#endif
if (!(tbl->tabattr[tbl->row + i][tbl->col + j] &
(HTT_X | HTT_Y))) {
tbl->tabattr[tbl->row + i][tbl->col + j] |=
((i > 0) ? HTT_Y : 0) | ((j > 0) ? HTT_X : 0);
}
if (tbl->col + j > tbl->maxcol) {
tbl->maxcol = tbl->col + j;
}
}
if (tbl->row + i > tbl->maxrow) {
tbl->maxrow = tbl->row + i;
}
}
begin_cell(tbl, mode);
break;
case HTML_N_TR:
setwidth(tbl, mode);
tbl->col = -1;
tbl->flag &= ~(TBL_IN_ROW | TBL_IN_COL);
return TAG_ACTION_NONE;
case HTML_N_TH:
case HTML_N_TD:
setwidth(tbl, mode);
tbl->flag &= ~TBL_IN_COL;
#ifdef FEED_TABLE_DEBUG
{
TextListItem *it;
int i = tbl->col, j = tbl->row;
fprintf(stderr, "(a) row,col: %d, %d\n", j, i);
if (tbl->tabdata[j] && tbl->tabdata[j][i]) {
for (it = ((TextList *)tbl->tabdata[j][i])->first;
it; it = it->next)
fprintf(stderr, " [%s] \n", it->ptr);
}
}
#endif
return TAG_ACTION_NONE;
case HTML_P:
case HTML_BR:
case HTML_CENTER:
case HTML_N_CENTER:
case HTML_DIV:
case HTML_N_DIV:
if (!(tbl->flag & TBL_IN_ROW))
break;
case HTML_DT:
case HTML_DD:
case HTML_H:
case HTML_N_H:
case HTML_LI:
case HTML_PRE:
case HTML_N_PRE:
case HTML_HR:
case HTML_LISTING:
case HTML_XMP:
case HTML_PLAINTEXT:
case HTML_PRE_PLAIN:
case HTML_N_PRE_PLAIN:
feed_table_block_tag(tbl, line, mode, 0, cmd);
switch (cmd) {
case HTML_PRE:
case HTML_PRE_PLAIN:
mode->pre_mode |= TBLM_PRE;
break;
case HTML_N_PRE:
case HTML_N_PRE_PLAIN:
mode->pre_mode &= ~TBLM_PRE;
break;
case HTML_LISTING:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = HTML_N_LISTING;
break;
case HTML_XMP:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = HTML_N_XMP;
break;
case HTML_PLAINTEXT:
mode->pre_mode |= TBLM_PLAIN;
mode->end_tag = MAX_HTMLTAG;
break;
}
break;
case HTML_DL:
case HTML_BLQ:
case HTML_OL:
case HTML_UL:
feed_table_block_tag(tbl, line, mode, 1, cmd);
break;
case HTML_N_DL:
case HTML_N_BLQ:
case HTML_N_OL:
case HTML_N_UL:
feed_table_block_tag(tbl, line, mode, -1, cmd);
break;
case HTML_NOBR:
case HTML_WBR:
if (!(tbl->flag & TBL_IN_ROW))
break;
case HTML_PRE_INT:
feed_table_inline_tag(tbl, line, mode, -1);
switch (cmd) {
case HTML_NOBR:
mode->nobr_level++;
if (mode->pre_mode & TBLM_NOBR)
return TAG_ACTION_NONE;
mode->pre_mode |= TBLM_NOBR;
break;
case HTML_PRE_INT:
if (mode->pre_mode & TBLM_PRE_INT)
return TAG_ACTION_NONE;
mode->pre_mode |= TBLM_PRE_INT;
tbl->linfo.prev_spaces = 0;
break;
}
mode->nobr_offset = -1;
if (tbl->linfo.length > 0) {
check_minimum0(tbl, tbl->linfo.length);
tbl->linfo.length = 0;
}
break;
case HTML_N_NOBR:
if (!(tbl->flag & TBL_IN_ROW))
break;
feed_table_inline_tag(tbl, line, mode, -1);
if (mode->nobr_level > 0)
mode->nobr_level--;
if (mode->nobr_level == 0)
mode->pre_mode &= ~TBLM_NOBR;
break;
case HTML_N_PRE_INT:
feed_table_inline_tag(tbl, line, mode, -1);
mode->pre_mode &= ~TBLM_PRE_INT;
break;
case HTML_IMG:
check_rowcol(tbl, mode);
w = tbl->fixed_width[tbl->col];
if (w < 0) {
if (tbl->total_width > 0)
w = -tbl->total_width * w / 100;
else if (width > 0)
w = -width * w / 100;
else
w = 0;
}
else if (w == 0) {
if (tbl->total_width > 0)
w = tbl->total_width;
else if (width > 0)
w = width;
}
tok = process_img(tag, w);
feed_table1(tbl, tok, mode, width);
break;
case HTML_FORM:
feed_table_block_tag(tbl, "", mode, 0, cmd);
tmp = process_form(tag);
if (tmp)
feed_table1(tbl, tmp, mode, width);
break;
case HTML_N_FORM:
feed_table_block_tag(tbl, "", mode, 0, cmd);
process_n_form();
break;
case HTML_INPUT:
tmp = process_input(tag);
feed_table1(tbl, tmp, mode, width);
break;
case HTML_BUTTON:
tmp = process_button(tag);
feed_table1(tbl, tmp, mode, width);
break;
case HTML_N_BUTTON:
tmp = process_n_button();
feed_table1(tbl, tmp, mode, width);
break;
case HTML_SELECT:
tmp = process_select(tag);
if (tmp)
feed_table1(tbl, tmp, mode, width);
mode->pre_mode |= TBLM_INSELECT;
mode->end_tag = HTML_N_SELECT;
break;
case HTML_N_SELECT:
case HTML_OPTION:
/* nothing */
break;
case HTML_TEXTAREA:
w = 0;
check_rowcol(tbl, mode);
if (tbl->col + 1 <= tbl->maxcol &&
tbl->tabattr[tbl->row][tbl->col + 1] & HTT_X) {
if (cell->icell >= 0 && cell->fixed_width[cell->icell] > 0)
w = cell->fixed_width[cell->icell];
}
else {
if (tbl->fixed_width[tbl->col] > 0)
w = tbl->fixed_width[tbl->col];
}
tmp = process_textarea(tag, w);
if (tmp)
feed_table1(tbl, tmp, mode, width);
mode->pre_mode |= TBLM_INTXTA;
mode->end_tag = HTML_N_TEXTAREA;
break;
case HTML_A:
table_close_anchor0(tbl, mode);
anchor = NULL;
i = 0;
parsedtag_get_value(tag, ATTR_HREF, &anchor);
parsedtag_get_value(tag, ATTR_HSEQ, &i);
if (anchor) {
check_rowcol(tbl, mode);
if (i == 0) {
Str tmp = process_anchor(tag, line);
if (displayLinkNumber)
{
Str t = getLinkNumberStr(-1);
feed_table_inline_tag(tbl, NULL, mode, t->length);
Strcat(tmp, t);
}
pushdata(tbl, tbl->row, tbl->col, tmp->ptr);
}
else
pushdata(tbl, tbl->row, tbl->col, line);
if (i >= 0) {
mode->pre_mode |= TBLM_ANCHOR;
mode->anchor_offset = tbl->tabcontentssize;
}
}
else
suspend_or_pushdata(tbl, line);
break;
case HTML_DEL:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode |= TBLM_DEL;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* [DEL: */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_N_DEL:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode &= ~TBLM_DEL;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* :DEL] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_S:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode |= TBLM_S;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 3); /* [S: */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_N_S:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
mode->pre_mode &= ~TBLM_S;
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 3); /* :S] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_INS:
case HTML_N_INS:
switch (displayInsDel) {
case DISPLAY_INS_DEL_SIMPLE:
break;
case DISPLAY_INS_DEL_NORMAL:
feed_table_inline_tag(tbl, line, mode, 5); /* [INS:, :INS] */
break;
case DISPLAY_INS_DEL_FONTIFY:
feed_table_inline_tag(tbl, line, mode, -1);
break;
}
break;
case HTML_SUP:
case HTML_SUB:
case HTML_N_SUB:
if (!(mode->pre_mode & (TBLM_DEL | TBLM_S)))
feed_table_inline_tag(tbl, line, mode, 1); /* ^, [, ] */
break;
case HTML_N_SUP:
break;
case HTML_TABLE_ALT:
id = -1;
parsedtag_get_value(tag, ATTR_TID, &id);
if (id >= 0 && id < tbl->ntable) {
struct table *tbl1 = tbl->tables[id].ptr;
feed_table_block_tag(tbl, line, mode, 0, cmd);
addcontentssize(tbl, maximum_table_width(tbl1));
check_minimum0(tbl, tbl1->sloppy_width);
#ifdef TABLE_EXPAND
w = tbl1->total_width;
v = 0;
colspan = table_colspan(tbl, tbl->row, tbl->col);
if (colspan > 1) {
if (cell->icell >= 0)
v = cell->fixed_width[cell->icell];
}
else
v = tbl->fixed_width[tbl->col];
if (v < 0 && tbl->real_width > 0 && tbl1->real_width > 0)
w = -(tbl1->real_width * 100) / tbl->real_width;
else
w = tbl1->real_width;
if (w > 0)
check_minimum0(tbl, w);
else if (w < 0 && v < w) {
if (colspan > 1) {
if (cell->icell >= 0)
cell->fixed_width[cell->icell] = w;
}
else
tbl->fixed_width[tbl->col] = w;
}
#endif
setwidth0(tbl, mode);
clearcontentssize(tbl, mode);
}
break;
case HTML_CAPTION:
mode->caption = 1;
break;
case HTML_N_CAPTION:
case HTML_THEAD:
case HTML_N_THEAD:
case HTML_TBODY:
case HTML_N_TBODY:
case HTML_TFOOT:
case HTML_N_TFOOT:
case HTML_COLGROUP:
case HTML_N_COLGROUP:
case HTML_COL:
break;
case HTML_SCRIPT:
mode->pre_mode |= TBLM_SCRIPT;
mode->end_tag = HTML_N_SCRIPT;
break;
case HTML_STYLE:
mode->pre_mode |= TBLM_STYLE;
mode->end_tag = HTML_N_STYLE;
break;
case HTML_N_A:
table_close_anchor0(tbl, mode);
case HTML_FONT:
case HTML_N_FONT:
case HTML_NOP:
suspend_or_pushdata(tbl, line);
break;
case HTML_INTERNAL:
case HTML_N_INTERNAL:
case HTML_FORM_INT:
case HTML_N_FORM_INT:
case HTML_INPUT_ALT:
case HTML_N_INPUT_ALT:
case HTML_SELECT_INT:
case HTML_N_SELECT_INT:
case HTML_OPTION_INT:
case HTML_TEXTAREA_INT:
case HTML_N_TEXTAREA_INT:
case HTML_IMG_ALT:
case HTML_SYMBOL:
case HTML_N_SYMBOL:
default:
/* unknown tag: put into table */
return TAG_ACTION_FEED;
}
return TAG_ACTION_NONE;
}
int
feed_table(struct table *tbl, char *line, struct table_mode *mode,
int width, int internal)
{
int i;
char *p;
Str tmp;
struct table_linfo *linfo = &tbl->linfo;
if (*line == '<' && line[1] && REALLY_THE_BEGINNING_OF_A_TAG(line)) {
struct parsed_tag *tag;
p = line;
tag = parse_tag(&p, internal);
if (tag) {
switch (feed_table_tag(tbl, line, mode, width, tag)) {
case TAG_ACTION_NONE:
return -1;
case TAG_ACTION_N_TABLE:
return 0;
case TAG_ACTION_TABLE:
return 1;
case TAG_ACTION_PLAIN:
break;
case TAG_ACTION_FEED:
default:
if (parsedtag_need_reconstruct(tag))
line = parsedtag2str(tag)->ptr;
}
}
else {
if (!(mode->pre_mode & (TBLM_PLAIN | TBLM_INTXTA | TBLM_INSELECT |
TBLM_SCRIPT | TBLM_STYLE)))
return -1;
}
}
else {
if (mode->pre_mode & (TBLM_DEL | TBLM_S))
return -1;
}
if (mode->caption) {
Strcat_charp(tbl->caption, line);
return -1;
}
if (mode->pre_mode & TBLM_SCRIPT)
return -1;
if (mode->pre_mode & TBLM_STYLE)
return -1;
if (mode->pre_mode & TBLM_INTXTA) {
feed_textarea(line);
return -1;
}
if (mode->pre_mode & TBLM_INSELECT) {
feed_select(line);
return -1;
}
if (!(mode->pre_mode & TBLM_PLAIN) &&
!(*line == '<' && line[strlen(line) - 1] == '>') &&
strchr(line, '&') != NULL) {
tmp = Strnew();
for (p = line; *p;) {
char *q, *r;
if (*p == '&') {
if (!strncasecmp(p, "&", 5) ||
!strncasecmp(p, ">", 4) || !strncasecmp(p, "<", 4)) {
/* do not convert */
Strcat_char(tmp, *p);
p++;
}
else {
int ec;
q = p;
switch (ec = getescapechar(&p)) {
case '<':
Strcat_charp(tmp, "<");
break;
case '>':
Strcat_charp(tmp, ">");
break;
case '&':
Strcat_charp(tmp, "&");
break;
case '\r':
Strcat_char(tmp, '\n');
break;
default:
r = conv_entity(ec);
if (r != NULL && strlen(r) == 1 &&
ec == (unsigned char)*r) {
Strcat_char(tmp, *r);
break;
}
case -1:
Strcat_char(tmp, *q);
p = q + 1;
break;
}
}
}
else {
Strcat_char(tmp, *p);
p++;
}
}
line = tmp->ptr;
}
if (!(mode->pre_mode & (TBLM_SPECIAL & ~TBLM_NOBR))) {
if (!(tbl->flag & TBL_IN_COL) || linfo->prev_spaces != 0)
while (IS_SPACE(*line))
line++;
if (*line == '\0')
return -1;
check_rowcol(tbl, mode);
if (mode->pre_mode & TBLM_NOBR && mode->nobr_offset < 0)
mode->nobr_offset = tbl->tabcontentssize;
/* count of number of spaces skipped in normal mode */
i = skip_space(tbl, line, linfo, !(mode->pre_mode & TBLM_NOBR));
addcontentssize(tbl, visible_length(line) - i);
setwidth(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
}
else if (mode->pre_mode & TBLM_PRE_INT) {
check_rowcol(tbl, mode);
if (mode->nobr_offset < 0)
mode->nobr_offset = tbl->tabcontentssize;
addcontentssize(tbl, maximum_visible_length(line, tbl->tabcontentssize));
setwidth(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, line);
}
else {
/* <pre> mode or something like it */
check_rowcol(tbl, mode);
while (*line) {
int nl = FALSE;
if ((p = strchr(line, '\r')) || (p = strchr(line, '\n'))) {
if (*p == '\r' && p[1] == '\n')
p++;
if (p[1]) {
p++;
tmp = Strnew_charp_n(line, p - line);
line = p;
p = tmp->ptr;
}
else {
p = line;
line = "";
}
nl = TRUE;
}
else {
p = line;
line = "";
}
if (mode->pre_mode & TBLM_PLAIN)
i = maximum_visible_length_plain(p, tbl->tabcontentssize);
else
i = maximum_visible_length(p, tbl->tabcontentssize);
addcontentssize(tbl, i);
setwidth(tbl, mode);
if (nl)
clearcontentssize(tbl, mode);
pushdata(tbl, tbl->row, tbl->col, p);
}
}
return -1;
}
void
feed_table1(struct table *tbl, Str tok, struct table_mode *mode, int width)
{
Str tokbuf;
int status;
char *line;
if (!tok)
return;
tokbuf = Strnew();
status = R_ST_NORMAL;
line = tok->ptr;
while (read_token
(tokbuf, &line, &status, mode->pre_mode & TBLM_PREMODE, 0))
feed_table(tbl, tokbuf->ptr, mode, width, TRUE);
}
void
pushTable(struct table *tbl, struct table *tbl1)
{
int col;
int row;
col = tbl->col;
row = tbl->row;
if (tbl->ntable >= tbl->tables_size) {
struct table_in *tmp;
tbl->tables_size += MAX_TABLE_N;
tmp = New_N(struct table_in, tbl->tables_size);
if (tbl->tables)
bcopy(tbl->tables, tmp, tbl->ntable * sizeof(struct table_in));
tbl->tables = tmp;
}
tbl->tables[tbl->ntable].ptr = tbl1;
tbl->tables[tbl->ntable].col = col;
tbl->tables[tbl->ntable].row = row;
tbl->tables[tbl->ntable].indent = tbl->indent;
tbl->tables[tbl->ntable].buf = newTextLineList();
check_row(tbl, row);
if (col + 1 <= tbl->maxcol && tbl->tabattr[row][col + 1] & HTT_X)
tbl->tables[tbl->ntable].cell = tbl->cell.icell;
else
tbl->tables[tbl->ntable].cell = -1;
tbl->ntable++;
}
#ifdef MATRIX
int
correct_table_matrix(struct table *t, int col, int cspan, int a, double b)
{
int i, j;
int ecol = col + cspan;
double w = 1. / (b * b);
for (i = col; i < ecol; i++) {
v_add_val(t->vector, i, w * a);
for (j = i; j < ecol; j++) {
m_add_val(t->matrix, i, j, w);
m_set_val(t->matrix, j, i, m_entry(t->matrix, i, j));
}
}
return i;
}
static void
correct_table_matrix2(struct table *t, int col, int cspan, double s, double b)
{
int i, j;
int ecol = col + cspan;
int size = t->maxcol + 1;
double w = 1. / (b * b);
double ss;
for (i = 0; i < size; i++) {
for (j = i; j < size; j++) {
if (i >= col && i < ecol && j >= col && j < ecol)
ss = (1. - s) * (1. - s);
else if ((i >= col && i < ecol) || (j >= col && j < ecol))
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
correct_table_matrix3(struct table *t, int col, char *flags, double s,
double b)
{
int i, j;
double ss;
int size = t->maxcol + 1;
double w = 1. / (b * b);
int flg = (flags[col] == 0);
for (i = 0; i < size; i++) {
if (!((flg && flags[i] == 0) || (!flg && flags[i] != 0)))
continue;
for (j = i; j < size; j++) {
if (!((flg && flags[j] == 0) || (!flg && flags[j] != 0)))
continue;
if (i == col && j == col)
ss = (1. - s) * (1. - s);
else if (i == col || j == col)
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
correct_table_matrix4(struct table *t, int col, int cspan, char *flags,
double s, double b)
{
int i, j;
double ss;
int ecol = col + cspan;
int size = t->maxcol + 1;
double w = 1. / (b * b);
for (i = 0; i < size; i++) {
if (flags[i] && !(i >= col && i < ecol))
continue;
for (j = i; j < size; j++) {
if (flags[j] && !(j >= col && j < ecol))
continue;
if (i >= col && i < ecol && j >= col && j < ecol)
ss = (1. - s) * (1. - s);
else if ((i >= col && i < ecol) || (j >= col && j < ecol))
ss = -(1. - s) * s;
else
ss = s * s;
m_add_val(t->matrix, i, j, w * ss);
}
}
}
static void
set_table_matrix0(struct table *t, int maxwidth)
{
int size = t->maxcol + 1;
int i, j, k, bcol, ecol;
int width;
double w0, w1, w, s, b;
#ifdef __GNUC__
double we[size];
char expand[size];
#else /* not __GNUC__ */
double we[MAXCOL];
char expand[MAXCOL];
#endif /* not __GNUC__ */
struct table_cell *cell = &t->cell;
w0 = 0.;
for (i = 0; i < size; i++) {
we[i] = weight(t->tabwidth[i]);
w0 += we[i];
}
if (w0 <= 0.)
w0 = 1.;
if (cell->necell == 0) {
for (i = 0; i < size; i++) {
s = we[i] / w0;
b = sigma_td_nw((int)(s * maxwidth));
correct_table_matrix2(t, i, 1, s, b);
}
return;
}
bzero(expand, size);
for (k = 0; k < cell->necell; k++) {
j = cell->eindex[k];
bcol = cell->col[j];
ecol = bcol + cell->colspan[j];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
w1 = 0.;
for (i = bcol; i < ecol; i++) {
w1 += t->tabwidth[i] + 0.1;
expand[i]++;
}
for (i = bcol; i < ecol; i++) {
w = weight(width * (t->tabwidth[i] + 0.1) / w1);
if (w > we[i])
we[i] = w;
}
}
w0 = 0.;
w1 = 0.;
for (i = 0; i < size; i++) {
w0 += we[i];
if (expand[i] == 0)
w1 += we[i];
}
if (w0 <= 0.)
w0 = 1.;
for (k = 0; k < cell->necell; k++) {
j = cell->eindex[k];
bcol = cell->col[j];
width = cell->width[j] - (cell->colspan[j] - 1) * t->cellspacing;
w = weight(width);
s = w / (w1 + w);
b = sigma_td_nw((int)(s * maxwidth));
correct_table_matrix4(t, bcol, cell->colspan[j], expand, s, b);
}
for (i = 0; i < size; i++) {
if (expand[i] == 0) {
s = we[i] / max(w1, 1.);
b = sigma_td_nw((int)(s * maxwidth));
}
else {
s = we[i] / max(w0 - w1, 1.);
b = sigma_td_nw(maxwidth);
}
correct_table_matrix3(t, i, expand, s, b);
}
}
void
check_relative_width(struct table *t, int maxwidth)
{
int i;
double rel_total = 0;
int size = t->maxcol + 1;
double *rcolwidth = New_N(double, size);
struct table_cell *cell = &t->cell;
int n_leftcol = 0;
for (i = 0; i < size; i++)
rcolwidth[i] = 0;
for (i = 0; i < size; i++) {
if (t->fixed_width[i] < 0)
rcolwidth[i] = -(double)t->fixed_width[i] / 100.0;
else if (t->fixed_width[i] > 0)
rcolwidth[i] = (double)t->fixed_width[i] / maxwidth;
else
n_leftcol++;
}
for (i = 0; i <= cell->maxcell; i++) {
if (cell->fixed_width[i] < 0) {
double w = -(double)cell->fixed_width[i] / 100.0;
double r;
int j, k;
int n_leftcell = 0;
k = cell->col[i];
r = 0.0;
for (j = 0; j < cell->colspan[i]; j++) {
if (rcolwidth[j + k] > 0)
r += rcolwidth[j + k];
else
n_leftcell++;
}
if (n_leftcell == 0) {
/* w must be identical to r */
if (w != r)
cell->fixed_width[i] = -100 * r;
}
else {
if (w <= r) {
/* make room for the left(width-unspecified) cell */
/* the next formula is an estimation of required width */
w = r * cell->colspan[i] / (cell->colspan[i] - n_leftcell);
cell->fixed_width[i] = -100 * w;
}
for (j = 0; j < cell->colspan[i]; j++) {
if (rcolwidth[j + k] == 0)
rcolwidth[j + k] = (w - r) / n_leftcell;
}
}
}
else if (cell->fixed_width[i] > 0) {
/* todo */
}
}
/* sanity check */
for (i = 0; i < size; i++)
rel_total += rcolwidth[i];
if ((n_leftcol == 0 && rel_total < 0.9) || 1.1 < rel_total) {
for (i = 0; i < size; i++) {
rcolwidth[i] /= rel_total;
}
for (i = 0; i < size; i++) {
if (t->fixed_width[i] < 0)
t->fixed_width[i] = -rcolwidth[i] * 100;
}
for (i = 0; i <= cell->maxcell; i++) {
if (cell->fixed_width[i] < 0) {
double r;
int j, k;
k = cell->col[i];
r = 0.0;
for (j = 0; j < cell->colspan[i]; j++)
r += rcolwidth[j + k];
cell->fixed_width[i] = -r * 100;
}
}
}
}
void
set_table_matrix(struct table *t, int width)
{
int size = t->maxcol + 1;
int i, j;
double b, s;
int a;
struct table_cell *cell = &t->cell;
if (size < 1)
return;
t->matrix = m_get(size, size);
t->vector = v_get(size);
for (i = 0; i < size; i++) {
for (j = i; j < size; j++)
m_set_val(t->matrix, i, j, 0.);
v_set_val(t->vector, i, 0.);
}
check_relative_width(t, width);
for (i = 0; i < size; i++) {
if (t->fixed_width[i] > 0) {
a = max(t->fixed_width[i], t->minimum_width[i]);
b = sigma_td(a);
correct_table_matrix(t, i, 1, a, b);
}
else if (t->fixed_width[i] < 0) {
s = -(double)t->fixed_width[i] / 100.;
b = sigma_td((int)(s * width));
correct_table_matrix2(t, i, 1, s, b);
}
}
for (j = 0; j <= cell->maxcell; j++) {
if (cell->fixed_width[j] > 0) {
a = max(cell->fixed_width[j], cell->minimum_width[j]);
b = sigma_td(a);
correct_table_matrix(t, cell->col[j], cell->colspan[j], a, b);
}
else if (cell->fixed_width[j] < 0) {
s = -(double)cell->fixed_width[j] / 100.;
b = sigma_td((int)(s * width));
correct_table_matrix2(t, cell->col[j], cell->colspan[j], s, b);
}
}
set_table_matrix0(t, width);
if (t->total_width > 0) {
b = sigma_table(width);
}
else {
b = sigma_table_nw(width);
}
correct_table_matrix(t, 0, size, width, b);
}
#endif /* MATRIX */
/* Local Variables: */
/* c-basic-offset: 4 */
/* tab-width: 8 */
/* End: */
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_587_0 |
crossvul-cpp_data_good_319_0 | /*
* Copyright © 2013 Ran Benita <ran234@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*/
/******************************************************************
Copyright 1992 by Oki Technosystems Laboratory, Inc.
Copyright 1992 by Fuji Xerox Co., Ltd.
Permission to use, copy, modify, distribute, and sell this software
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear
in supporting documentation, and that the name of Oki Technosystems
Laboratory and Fuji Xerox not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.
Oki Technosystems Laboratory and Fuji Xerox make no representations
about the suitability of this software for any purpose. It is provided
"as is" without express or implied warranty.
OKI TECHNOSYSTEMS LABORATORY AND FUJI XEROX DISCLAIM ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL OKI TECHNOSYSTEMS
LABORATORY AND FUJI XEROX BE LIABLE FOR 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.
Author: Yasuhiro Kawai Oki Technosystems Laboratory
Author: Kazunori Nishihara Fuji Xerox
******************************************************************/
#include <errno.h>
#include "utils.h"
#include "scanner-utils.h"
#include "table.h"
#include "paths.h"
#include "utf8.h"
#include "parser.h"
#define MAX_LHS_LEN 10
#define MAX_INCLUDE_DEPTH 5
/*
* Grammar adapted from libX11/modules/im/ximcp/imLcPrs.c.
* See also the XCompose(5) manpage.
*
* FILE ::= { [PRODUCTION] [COMMENT] "\n" | INCLUDE }
* INCLUDE ::= "include" '"' INCLUDE_STRING '"'
* PRODUCTION ::= LHS ":" RHS [ COMMENT ]
* COMMENT ::= "#" {<any character except null or newline>}
* LHS ::= EVENT { EVENT }
* EVENT ::= [MODIFIER_LIST] "<" keysym ">"
* MODIFIER_LIST ::= (["!"] {MODIFIER} ) | "None"
* MODIFIER ::= ["~"] MODIFIER_NAME
* MODIFIER_NAME ::= ("Ctrl"|"Lock"|"Caps"|"Shift"|"Alt"|"Meta")
* RHS ::= ( STRING | keysym | STRING keysym )
* STRING ::= '"' { CHAR } '"'
* CHAR ::= GRAPHIC_CHAR | ESCAPED_CHAR
* GRAPHIC_CHAR ::= locale (codeset) dependent code
* ESCAPED_CHAR ::= ('\\' | '\"' | OCTAL | HEX )
* OCTAL ::= '\' OCTAL_CHAR [OCTAL_CHAR [OCTAL_CHAR]]
* OCTAL_CHAR ::= (0|1|2|3|4|5|6|7)
* HEX ::= '\' (x|X) HEX_CHAR [HEX_CHAR]]
* HEX_CHAR ::= (0|1|2|3|4|5|6|7|8|9|A|B|C|D|E|F|a|b|c|d|e|f)
*
* INCLUDE_STRING is a filesystem path, with the following %-expansions:
* %% - '%'.
* %H - The user's home directory (the $HOME environment variable).
* %L - The name of the locale specific Compose file (e.g.,
* "/usr/share/X11/locale/<localename>/Compose").
* %S - The name of the system directory for Compose files (e.g.,
* "/usr/share/X11/locale").
*/
enum rules_token {
TOK_END_OF_FILE = 0,
TOK_END_OF_LINE,
TOK_INCLUDE,
TOK_INCLUDE_STRING,
TOK_LHS_KEYSYM,
TOK_COLON,
TOK_BANG,
TOK_TILDE,
TOK_STRING,
TOK_IDENT,
TOK_ERROR
};
/* Values returned with some tokens, like yylval. */
union lvalue {
struct {
/* Still \0-terminated. */
const char *str;
size_t len;
} string;
};
static enum rules_token
lex(struct scanner *s, union lvalue *val)
{
skip_more_whitespace_and_comments:
/* Skip spaces. */
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
/* Skip comments. */
if (chr(s, '#')) {
skip_to_eol(s);
goto skip_more_whitespace_and_comments;
}
/* See if we're done. */
if (eof(s)) return TOK_END_OF_FILE;
/* New token. */
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
/* LHS Keysym. */
if (chr(s, '<')) {
while (peek(s) != '>' && !eol(s) && !eof(s))
buf_append(s, next(s));
if (!chr(s, '>')) {
scanner_err(s, "unterminated keysym literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "keysym literal is too long");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_LHS_KEYSYM;
}
/* Colon. */
if (chr(s, ':'))
return TOK_COLON;
if (chr(s, '!'))
return TOK_BANG;
if (chr(s, '~'))
return TOK_TILDE;
/* String literal. */
if (chr(s, '\"')) {
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '\\')) {
uint8_t o;
if (chr(s, '\\')) {
buf_append(s, '\\');
}
else if (chr(s, '"')) {
buf_append(s, '"');
}
else if (chr(s, 'x') || chr(s, 'X')) {
if (hex(s, &o))
buf_append(s, (char) o);
else
scanner_warn(s, "illegal hexadecimal escape sequence in string literal");
}
else if (oct(s, &o)) {
buf_append(s, (char) o);
}
else {
scanner_warn(s, "unknown escape sequence (%c) in string literal", peek(s));
/* Ignore. */
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated string literal");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "string literal is too long");
return TOK_ERROR;
}
if (!is_valid_utf8(s->buf, s->buf_pos - 1)) {
scanner_err(s, "string literal is not a valid UTF-8 string");
return TOK_ERROR;
}
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_STRING;
}
/* Identifier or include. */
if (is_alpha(peek(s)) || peek(s) == '_') {
s->buf_pos = 0;
while (is_alnum(peek(s)) || peek(s) == '_')
buf_append(s, next(s));
if (!buf_append(s, '\0')) {
scanner_err(s, "identifier is too long");
return TOK_ERROR;
}
if (streq(s->buf, "include"))
return TOK_INCLUDE;
val->string.str = s->buf;
val->string.len = s->buf_pos;
return TOK_IDENT;
}
/* Discard rest of line. */
skip_to_eol(s);
scanner_err(s, "unrecognized token");
return TOK_ERROR;
}
static enum rules_token
lex_include_string(struct scanner *s, struct xkb_compose_table *table,
union lvalue *val_out)
{
while (is_space(peek(s)))
if (next(s) == '\n')
return TOK_END_OF_LINE;
s->token_line = s->line;
s->token_column = s->column;
s->buf_pos = 0;
if (!chr(s, '\"')) {
scanner_err(s, "include statement must be followed by a path");
return TOK_ERROR;
}
while (!eof(s) && !eol(s) && peek(s) != '\"') {
if (chr(s, '%')) {
if (chr(s, '%')) {
buf_append(s, '%');
}
else if (chr(s, 'H')) {
const char *home = secure_getenv("HOME");
if (!home) {
scanner_err(s, "%%H was used in an include statement, but the HOME environment variable is not set");
return TOK_ERROR;
}
if (!buf_appends(s, home)) {
scanner_err(s, "include path after expanding %%H is too long");
return TOK_ERROR;
}
}
else if (chr(s, 'L')) {
char *path = get_locale_compose_file_path(table->locale);
if (!path) {
scanner_err(s, "failed to expand %%L to the locale Compose file");
return TOK_ERROR;
}
if (!buf_appends(s, path)) {
free(path);
scanner_err(s, "include path after expanding %%L is too long");
return TOK_ERROR;
}
free(path);
}
else if (chr(s, 'S')) {
const char *xlocaledir = get_xlocaledir_path();
if (!buf_appends(s, xlocaledir)) {
scanner_err(s, "include path after expanding %%S is too long");
return TOK_ERROR;
}
}
else {
scanner_err(s, "unknown %% format (%c) in include statement", peek(s));
return TOK_ERROR;
}
} else {
buf_append(s, next(s));
}
}
if (!chr(s, '\"')) {
scanner_err(s, "unterminated include statement");
return TOK_ERROR;
}
if (!buf_append(s, '\0')) {
scanner_err(s, "include path is too long");
return TOK_ERROR;
}
val_out->string.str = s->buf;
val_out->string.len = s->buf_pos;
return TOK_INCLUDE_STRING;
}
struct production {
xkb_keysym_t lhs[MAX_LHS_LEN];
unsigned int len;
xkb_keysym_t keysym;
char string[256];
/* At least one of these is true. */
bool has_keysym;
bool has_string;
/* The matching is as follows: (active_mods & modmask) == mods. */
xkb_mod_mask_t modmask;
xkb_mod_mask_t mods;
};
static uint32_t
add_node(struct xkb_compose_table *table, xkb_keysym_t keysym)
{
struct compose_node new = {
.keysym = keysym,
.next = 0,
.is_leaf = true,
};
darray_append(table->nodes, new);
return darray_size(table->nodes) - 1;
}
static void
add_production(struct xkb_compose_table *table, struct scanner *s,
const struct production *production)
{
unsigned lhs_pos;
uint32_t curr;
struct compose_node *node;
curr = 0;
node = &darray_item(table->nodes, curr);
/*
* Insert the sequence to the trie, creating new nodes as needed.
*
* TODO: This can be sped up a bit by first trying the path that the
* previous production took, and only then doing the linear search
* through the trie levels. This will work because sequences in the
* Compose files are often clustered by a common prefix; especially
* in the 1st and 2nd keysyms, which is where the largest variation
* (thus, longest search) is.
*/
for (lhs_pos = 0; lhs_pos < production->len; lhs_pos++) {
while (production->lhs[lhs_pos] != node->keysym) {
if (node->next == 0) {
uint32_t next = add_node(table, production->lhs[lhs_pos]);
/* Refetch since add_node could have realloc()ed. */
node = &darray_item(table->nodes, curr);
node->next = next;
}
curr = node->next;
node = &darray_item(table->nodes, curr);
}
if (lhs_pos + 1 == production->len)
break;
if (node->is_leaf) {
if (node->u.leaf.utf8 != 0 ||
node->u.leaf.keysym != XKB_KEY_NoSymbol) {
scanner_warn(s, "a sequence already exists which is a prefix of this sequence; overriding");
node->u.leaf.utf8 = 0;
node->u.leaf.keysym = XKB_KEY_NoSymbol;
}
{
uint32_t successor = add_node(table, production->lhs[lhs_pos + 1]);
/* Refetch since add_node could have realloc()ed. */
node = &darray_item(table->nodes, curr);
node->is_leaf = false;
node->u.successor = successor;
}
}
curr = node->u.successor;
node = &darray_item(table->nodes, curr);
}
if (!node->is_leaf) {
scanner_warn(s, "this compose sequence is a prefix of another; skipping line");
return;
}
if (node->u.leaf.utf8 != 0 || node->u.leaf.keysym != XKB_KEY_NoSymbol) {
bool same_string =
(node->u.leaf.utf8 == 0 && !production->has_string) ||
(
node->u.leaf.utf8 != 0 && production->has_string &&
streq(&darray_item(table->utf8, node->u.leaf.utf8),
production->string)
);
bool same_keysym =
(node->u.leaf.keysym == XKB_KEY_NoSymbol && !production->has_keysym) ||
(
node->u.leaf.keysym != XKB_KEY_NoSymbol && production->has_keysym &&
node->u.leaf.keysym == production->keysym
);
if (same_string && same_keysym) {
scanner_warn(s, "this compose sequence is a duplicate of another; skipping line");
return;
}
scanner_warn(s, "this compose sequence already exists; overriding");
}
if (production->has_string) {
node->u.leaf.utf8 = darray_size(table->utf8);
darray_append_items(table->utf8, production->string,
strlen(production->string) + 1);
}
if (production->has_keysym) {
node->u.leaf.keysym = production->keysym;
}
}
/* Should match resolve_modifier(). */
#define ALL_MODS_MASK ((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3))
static xkb_mod_index_t
resolve_modifier(const char *name)
{
static const struct {
const char *name;
xkb_mod_index_t mod;
} mods[] = {
{ "Shift", 0 },
{ "Ctrl", 2 },
{ "Alt", 3 },
{ "Meta", 3 },
{ "Lock", 1 },
{ "Caps", 1 },
};
for (unsigned i = 0; i < ARRAY_SIZE(mods); i++)
if (streq(name, mods[i].name))
return mods[i].mod;
return XKB_MOD_INVALID;
}
static bool
parse(struct xkb_compose_table *table, struct scanner *s,
unsigned include_depth);
static bool
do_include(struct xkb_compose_table *table, struct scanner *s,
const char *path, unsigned include_depth)
{
FILE *file;
bool ok;
char *string;
size_t size;
struct scanner new_s;
if (include_depth >= MAX_INCLUDE_DEPTH) {
scanner_err(s, "maximum include depth (%d) exceeded; maybe there is an include loop?",
MAX_INCLUDE_DEPTH);
return false;
}
file = fopen(path, "r");
if (!file) {
scanner_err(s, "failed to open included Compose file \"%s\": %s",
path, strerror(errno));
return false;
}
ok = map_file(file, &string, &size);
if (!ok) {
scanner_err(s, "failed to read included Compose file \"%s\": %s",
path, strerror(errno));
goto err_file;
}
scanner_init(&new_s, table->ctx, string, size, path, s->priv);
ok = parse(table, &new_s, include_depth + 1);
if (!ok)
goto err_unmap;
err_unmap:
unmap_file(string, size);
err_file:
fclose(file);
return ok;
}
static bool
parse(struct xkb_compose_table *table, struct scanner *s,
unsigned include_depth)
{
enum rules_token tok;
union lvalue val;
xkb_keysym_t keysym;
struct production production;
enum { MAX_ERRORS = 10 };
int num_errors = 0;
initial:
production.len = 0;
production.has_keysym = false;
production.has_string = false;
production.mods = 0;
production.modmask = 0;
/* fallthrough */
initial_eol:
switch (tok = lex(s, &val)) {
case TOK_END_OF_LINE:
goto initial_eol;
case TOK_END_OF_FILE:
goto finished;
case TOK_INCLUDE:
goto include;
default:
goto lhs_tok;
}
include:
switch (tok = lex_include_string(s, table, &val)) {
case TOK_INCLUDE_STRING:
goto include_eol;
default:
goto unexpected;
}
include_eol:
switch (tok = lex(s, &val)) {
case TOK_END_OF_LINE:
if (!do_include(table, s, val.string.str, include_depth))
goto fail;
goto initial;
default:
goto unexpected;
}
lhs:
tok = lex(s, &val);
lhs_tok:
switch (tok) {
case TOK_COLON:
if (production.len <= 0) {
scanner_warn(s, "expected at least one keysym on left-hand side; skipping line");
goto skip;
}
goto rhs;
case TOK_IDENT:
if (streq(val.string.str, "None")) {
production.mods = 0;
production.modmask = ALL_MODS_MASK;
goto lhs_keysym;
}
goto lhs_mod_list_tok;
case TOK_TILDE:
goto lhs_mod_list_tok;
case TOK_BANG:
production.modmask = ALL_MODS_MASK;
goto lhs_mod_list;
default:
goto lhs_keysym_tok;
}
lhs_keysym:
tok = lex(s, &val);
lhs_keysym_tok:
switch (tok) {
case TOK_LHS_KEYSYM:
keysym = xkb_keysym_from_name(val.string.str, XKB_KEYSYM_NO_FLAGS);
if (keysym == XKB_KEY_NoSymbol) {
scanner_err(s, "unrecognized keysym \"%s\" on left-hand side",
val.string.str);
goto error;
}
if (production.len + 1 > MAX_LHS_LEN) {
scanner_warn(s, "too many keysyms (%d) on left-hand side; skipping line",
MAX_LHS_LEN + 1);
goto skip;
}
production.lhs[production.len++] = keysym;
production.mods = 0;
production.modmask = 0;
goto lhs;
default:
goto unexpected;
}
lhs_mod_list:
tok = lex(s, &val);
lhs_mod_list_tok: {
bool tilde = false;
xkb_mod_index_t mod;
if (tok != TOK_TILDE && tok != TOK_IDENT)
goto lhs_keysym_tok;
if (tok == TOK_TILDE) {
tilde = true;
tok = lex(s, &val);
}
if (tok != TOK_IDENT)
goto unexpected;
mod = resolve_modifier(val.string.str);
if (mod == XKB_MOD_INVALID) {
scanner_err(s, "unrecognized modifier \"%s\"",
val.string.str);
goto error;
}
production.modmask |= 1 << mod;
if (tilde)
production.mods &= ~(1 << mod);
else
production.mods |= 1 << mod;
goto lhs_mod_list;
}
rhs:
switch (tok = lex(s, &val)) {
case TOK_STRING:
if (production.has_string) {
scanner_warn(s, "right-hand side can have at most one string; skipping line");
goto skip;
}
if (val.string.len <= 0) {
scanner_warn(s, "right-hand side string must not be empty; skipping line");
goto skip;
}
if (val.string.len >= sizeof(production.string)) {
scanner_warn(s, "right-hand side string is too long; skipping line");
goto skip;
}
strcpy(production.string, val.string.str);
production.has_string = true;
goto rhs;
case TOK_IDENT:
keysym = xkb_keysym_from_name(val.string.str, XKB_KEYSYM_NO_FLAGS);
if (keysym == XKB_KEY_NoSymbol) {
scanner_err(s, "unrecognized keysym \"%s\" on right-hand side",
val.string.str);
goto error;
}
if (production.has_keysym) {
scanner_warn(s, "right-hand side can have at most one keysym; skipping line");
goto skip;
}
production.keysym = keysym;
production.has_keysym = true;
/* fallthrough */
case TOK_END_OF_LINE:
if (!production.has_string && !production.has_keysym) {
scanner_warn(s, "right-hand side must have at least one of string or keysym; skipping line");
goto skip;
}
add_production(table, s, &production);
goto initial;
default:
goto unexpected;
}
unexpected:
if (tok != TOK_ERROR)
scanner_err(s, "unexpected token");
error:
num_errors++;
if (num_errors <= MAX_ERRORS)
goto skip;
scanner_err(s, "too many errors");
goto fail;
fail:
scanner_err(s, "failed to parse file");
return false;
skip:
while (tok != TOK_END_OF_LINE && tok != TOK_END_OF_FILE)
tok = lex(s, &val);
goto initial;
finished:
return true;
}
bool
parse_string(struct xkb_compose_table *table, const char *string, size_t len,
const char *file_name)
{
struct scanner s;
scanner_init(&s, table->ctx, string, len, file_name, NULL);
if (!parse(table, &s, 0))
return false;
/* Maybe the allocator can use the excess space. */
darray_shrink(table->nodes);
darray_shrink(table->utf8);
return true;
}
bool
parse_file(struct xkb_compose_table *table, FILE *file, const char *file_name)
{
bool ok;
char *string;
size_t size;
ok = map_file(file, &string, &size);
if (!ok) {
log_err(table->ctx, "Couldn't read Compose file %s: %s\n",
file_name, strerror(errno));
return false;
}
ok = parse_string(table, string, size, file_name);
unmap_file(string, size);
return ok;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_319_0 |
crossvul-cpp_data_bad_465_0 | /*
* TechnoTrend PVA (.pva) demuxer
* Copyright (c) 2007, 2008 Ivo van Poorten
*
* 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 "avformat.h"
#include "internal.h"
#include "mpeg.h"
#define PVA_MAX_PAYLOAD_LENGTH 0x17f8
#define PVA_VIDEO_PAYLOAD 0x01
#define PVA_AUDIO_PAYLOAD 0x02
#define PVA_MAGIC (('A' << 8) + 'V')
typedef struct PVAContext {
int continue_pes;
} PVAContext;
static int pva_check(const uint8_t *p) {
int length = AV_RB16(p + 6);
if (AV_RB16(p) != PVA_MAGIC || !p[2] || p[2] > 2 || p[4] != 0x55 ||
(p[5] & 0xe0) || length > PVA_MAX_PAYLOAD_LENGTH)
return -1;
return length + 8;
}
static int pva_probe(AVProbeData * pd) {
const unsigned char *buf = pd->buf;
int len = pva_check(buf);
if (len < 0)
return 0;
if (pd->buf_size >= len + 8 &&
pva_check(buf + len) >= 0)
return AVPROBE_SCORE_EXTENSION;
return AVPROBE_SCORE_MAX / 4;
}
static int pva_read_header(AVFormatContext *s) {
AVStream *st;
if (!(st = avformat_new_stream(s, NULL)))
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
st->codecpar->codec_id = AV_CODEC_ID_MPEG2VIDEO;
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(st, 32, 1, 90000);
av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
if (!(st = avformat_new_stream(s, NULL)))
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = AV_CODEC_ID_MP2;
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(st, 33, 1, 90000);
av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
/* the parameters will be extracted from the compressed bitstream */
return 0;
}
#define pva_log if (read_packet) av_log
static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
AVIOContext *pb = s->pb;
int64_t pva_pts;
int ret, length, streamid;
if (read_part_of_packet(s, &pva_pts, &length, &streamid, 1) < 0 ||
(ret = av_get_packet(pb, pkt, length)) <= 0)
return AVERROR(EIO);
pkt->stream_index = streamid - 1;
pkt->pts = pva_pts;
return ret;
}
static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
int64_t *pos, int64_t pos_limit) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int length, streamid;
int64_t res = AV_NOPTS_VALUE;
pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit);
while (*pos < pos_limit) {
res = AV_NOPTS_VALUE;
avio_seek(pb, *pos, SEEK_SET);
pvactx->continue_pes = 0;
if (read_part_of_packet(s, &res, &length, &streamid, 0)) {
(*pos)++;
continue;
}
if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {
*pos = avio_tell(pb) + length;
continue;
}
break;
}
pvactx->continue_pes = 0;
return res;
}
AVInputFormat ff_pva_demuxer = {
.name = "pva",
.long_name = NULL_IF_CONFIG_SMALL("TechnoTrend PVA"),
.priv_data_size = sizeof(PVAContext),
.read_probe = pva_probe,
.read_header = pva_read_header,
.read_packet = pva_read_packet,
.read_timestamp = pva_read_timestamp,
};
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_465_0 |
crossvul-cpp_data_bad_3278_0 | /*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static. These functions are needed by GSO/GRO implementation.
*/
#include <linux/export.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/addrconf.h>
#include <net/secure_seq.h>
#include <linux/netfilter.h>
static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
/* This function exists only for tap drivers that must support broken
* clients requesting UFO without specifying an IPv6 fragment ID.
*
* This is similar to ipv6_select_ident() but we use an independent hash
* seed to limit information leakage.
*
* The network header must be set before calling this.
*/
void ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
skb_shinfo(skb)->ip6_frag_id = htonl(id);
}
EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);
__be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
EXPORT_SYMBOL(ipv6_select_ident);
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset <= packet_len) {
struct ipv6_opt_hdr *exthdr;
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
if (offset + sizeof(struct ipv6_opt_hdr) > packet_len)
return -EINVAL;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
}
return -EINVAL;
}
EXPORT_SYMBOL(ip6_find_1stfragopt);
#if IS_ENABLED(CONFIG_IPV6)
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
#endif
int __ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out(sk, skb);
if (unlikely(!skb))
return 0;
skb->protocol = htons(ETH_P_IPV6);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, sk, skb, NULL, skb_dst(skb)->dev,
dst_output);
}
EXPORT_SYMBOL_GPL(__ip6_local_out);
int ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int err;
err = __ip6_local_out(net, sk, skb);
if (likely(err == 1))
err = dst_output(net, sk, skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_3278_0 |
crossvul-cpp_data_good_2564_1 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2007 Novell, Inc.
* Copyright (C) 2008 Red Hat, Inc.
* Copyright (C) 2008 William Jon McCann <jmccann@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <glib-object.h>
#include <X11/ICE/ICElib.h>
#include <X11/ICE/ICEutil.h>
#include <X11/ICE/ICEconn.h>
#include <X11/SM/SMlib.h>
#ifdef HAVE_X11_XTRANS_XTRANS_H
/* Get the proto for _IceTransNoListen */
#define ICE_t
#define TRANS_SERVER
#include <X11/Xtrans/Xtrans.h>
#undef ICE_t
#undef TRANS_SERVER
#endif /* HAVE_X11_XTRANS_XTRANS_H */
#include "gsm-xsmp-server.h"
#include "gsm-xsmp-client.h"
#include "gsm-util.h"
/* ICEauthority stuff */
/* Various magic numbers stolen from iceauth.c */
#define GSM_ICE_AUTH_RETRIES 10
#define GSM_ICE_AUTH_INTERVAL 2 /* 2 seconds */
#define GSM_ICE_AUTH_LOCK_TIMEOUT 600 /* 10 minutes */
#define GSM_ICE_MAGIC_COOKIE_AUTH_NAME "MIT-MAGIC-COOKIE-1"
#define GSM_ICE_MAGIC_COOKIE_LEN 16
#define GSM_XSMP_SERVER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSM_TYPE_XSMP_SERVER, GsmXsmpServerPrivate))
struct GsmXsmpServerPrivate
{
GsmStore *client_store;
IceListenObj *xsmp_sockets;
int num_xsmp_sockets;
int num_local_xsmp_sockets;
};
enum {
PROP_0,
PROP_CLIENT_STORE
};
static void gsm_xsmp_server_class_init (GsmXsmpServerClass *klass);
static void gsm_xsmp_server_init (GsmXsmpServer *xsmp_server);
static void gsm_xsmp_server_finalize (GObject *object);
static gpointer xsmp_server_object = NULL;
G_DEFINE_TYPE (GsmXsmpServer, gsm_xsmp_server, G_TYPE_OBJECT)
typedef struct {
GsmXsmpServer *server;
IceListenObj listener;
} GsmIceConnectionData;
typedef struct {
guint watch_id;
guint protocol_timeout;
} GsmIceConnectionWatch;
static void
disconnect_ice_connection (IceConn ice_conn)
{
IceSetShutdownNegotiation (ice_conn, FALSE);
IceCloseConnection (ice_conn);
}
static void
free_ice_connection_watch (GsmIceConnectionWatch *data)
{
if (data->watch_id) {
g_source_remove (data->watch_id);
data->watch_id = 0;
}
if (data->protocol_timeout) {
g_source_remove (data->protocol_timeout);
data->protocol_timeout = 0;
}
g_free (data);
}
static gboolean
ice_protocol_timeout (IceConn ice_conn)
{
GsmIceConnectionWatch *data;
g_debug ("GsmXsmpServer: ice_protocol_timeout for IceConn %p with status %d",
ice_conn, IceConnectionStatus (ice_conn));
data = ice_conn->context;
free_ice_connection_watch (data);
disconnect_ice_connection (ice_conn);
return FALSE;
}
static gboolean
auth_iochannel_watch (GIOChannel *source,
GIOCondition condition,
IceConn ice_conn)
{
GsmIceConnectionWatch *data;
gboolean keep_going;
data = ice_conn->context;
switch (IceProcessMessages (ice_conn, NULL, NULL)) {
case IceProcessMessagesSuccess:
keep_going = TRUE;
break;
case IceProcessMessagesIOError:
g_debug ("GsmXsmpServer: IceProcessMessages returned IceProcessMessagesIOError");
free_ice_connection_watch (data);
disconnect_ice_connection (ice_conn);
keep_going = FALSE;
break;
case IceProcessMessagesConnectionClosed:
g_debug ("GsmXsmpServer: IceProcessMessages returned IceProcessMessagesConnectionClosed");
free_ice_connection_watch (data);
keep_going = FALSE;
break;
default:
g_assert_not_reached ();
}
return keep_going;
}
/* IceAcceptConnection returns a new ICE connection that is in a "pending" state,
* this is because authentification may be necessary.
* So we've to authenticate it, before accept_xsmp_connection() is called.
* Then each GsmXSMPClient will have its own IceConn watcher
*/
static void
auth_ice_connection (IceConn ice_conn)
{
GIOChannel *channel;
GsmIceConnectionWatch *data;
int fd;
g_debug ("GsmXsmpServer: auth_ice_connection()");
fd = IceConnectionNumber (ice_conn);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
data = g_new0 (GsmIceConnectionWatch, 1);
ice_conn->context = data;
data->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)ice_protocol_timeout,
ice_conn);
data->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)auth_iochannel_watch,
ice_conn);
g_io_channel_unref (channel);
}
/* This is called (by glib via xsmp->ice_connection_watch) when a
* connection is first received on the ICE listening socket.
*/
static gboolean
accept_ice_connection (GIOChannel *source,
GIOCondition condition,
GsmIceConnectionData *data)
{
IceConn ice_conn;
IceAcceptStatus status;
g_debug ("GsmXsmpServer: accept_ice_connection()");
ice_conn = IceAcceptConnection (data->listener, &status);
if (status != IceAcceptSuccess) {
g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status);
return TRUE;
}
auth_ice_connection (ice_conn);
return TRUE;
}
void
gsm_xsmp_server_start (GsmXsmpServer *server)
{
GIOChannel *channel;
int i;
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
GsmIceConnectionData *data;
data = g_new0 (GsmIceConnectionData, 1);
data->server = server;
data->listener = server->priv->xsmp_sockets[i];
channel = g_io_channel_unix_new (IceGetListenConnectionNumber (server->priv->xsmp_sockets[i]));
g_io_add_watch_full (channel,
G_PRIORITY_DEFAULT,
G_IO_IN | G_IO_HUP | G_IO_ERR,
(GIOFunc)accept_ice_connection,
data,
(GDestroyNotify)g_free);
g_io_channel_unref (channel);
}
}
static void
gsm_xsmp_server_set_client_store (GsmXsmpServer *xsmp_server,
GsmStore *store)
{
g_return_if_fail (GSM_IS_XSMP_SERVER (xsmp_server));
if (store != NULL) {
g_object_ref (store);
}
if (xsmp_server->priv->client_store != NULL) {
g_object_unref (xsmp_server->priv->client_store);
}
xsmp_server->priv->client_store = store;
}
static void
gsm_xsmp_server_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsmXsmpServer *self;
self = GSM_XSMP_SERVER (object);
switch (prop_id) {
case PROP_CLIENT_STORE:
gsm_xsmp_server_set_client_store (self, g_value_get_object (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_server_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GsmXsmpServer *self;
self = GSM_XSMP_SERVER (object);
switch (prop_id) {
case PROP_CLIENT_STORE:
g_value_set_object (value, self->priv->client_store);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* This is called (by libSM) when XSMP is initiated on an ICE
* connection that was already accepted by accept_ice_connection.
*/
static Status
accept_xsmp_connection (SmsConn sms_conn,
GsmXsmpServer *server,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret,
char **failure_reason_ret)
{
IceConn ice_conn;
GsmClient *client;
GsmIceConnectionWatch *data;
/* FIXME: what about during shutdown but before gsm_xsmp_shutdown? */
if (server->priv->xsmp_sockets == NULL) {
g_debug ("GsmXsmpServer: In shutdown, rejecting new client");
*failure_reason_ret = strdup (_("Refusing new client connection because the session is currently being shut down\n"));
return FALSE;
}
ice_conn = SmsGetIceConnection (sms_conn);
data = ice_conn->context;
/* Each GsmXSMPClient has its own IceConn watcher */
free_ice_connection_watch (data);
client = gsm_xsmp_client_new (ice_conn);
gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client));
/* the store will own the ref */
g_object_unref (client);
gsm_xsmp_client_connect (GSM_XSMP_CLIENT (client), sms_conn, mask_ret, callbacks_ret);
return TRUE;
}
static void
ice_error_handler (IceConn conn,
Bool swap,
int offending_minor_opcode,
unsigned long offending_sequence,
int error_class,
int severity,
IcePointer values)
{
g_debug ("GsmXsmpServer: ice_error_handler (%p, %s, %d, %lx, %d, %d)",
conn, swap ? "TRUE" : "FALSE", offending_minor_opcode,
offending_sequence, error_class, severity);
if (severity == IceCanContinue) {
return;
}
/* FIXME: the ICElib docs are completely vague about what we're
* supposed to do in this case. Need to verify that calling
* IceCloseConnection() here is guaranteed to cause neither
* free-memory-reads nor leaks.
*/
IceCloseConnection (conn);
}
static void
ice_io_error_handler (IceConn conn)
{
g_debug ("GsmXsmpServer: ice_io_error_handler (%p)", conn);
/* We don't need to do anything here; the next call to
* IceProcessMessages() for this connection will receive
* IceProcessMessagesIOError and we can handle the error there.
*/
}
static void
sms_error_handler (SmsConn conn,
Bool swap,
int offending_minor_opcode,
unsigned long offending_sequence_num,
int error_class,
int severity,
IcePointer values)
{
g_debug ("GsmXsmpServer: sms_error_handler (%p, %s, %d, %lx, %d, %d)",
conn, swap ? "TRUE" : "FALSE", offending_minor_opcode,
offending_sequence_num, error_class, severity);
/* We don't need to do anything here; if the connection needs to be
* closed, libSM will do that itself.
*/
}
static IceAuthFileEntry *
auth_entry_new (const char *protocol,
const char *network_id)
{
IceAuthFileEntry *file_entry;
IceAuthDataEntry data_entry;
file_entry = malloc (sizeof (IceAuthFileEntry));
file_entry->protocol_name = strdup (protocol);
file_entry->protocol_data = NULL;
file_entry->protocol_data_length = 0;
file_entry->network_id = strdup (network_id);
file_entry->auth_name = strdup (GSM_ICE_MAGIC_COOKIE_AUTH_NAME);
file_entry->auth_data = IceGenerateMagicCookie (GSM_ICE_MAGIC_COOKIE_LEN);
file_entry->auth_data_length = GSM_ICE_MAGIC_COOKIE_LEN;
/* Also create an in-memory copy, which is what the server will
* actually use for checking client auth.
*/
data_entry.protocol_name = file_entry->protocol_name;
data_entry.network_id = file_entry->network_id;
data_entry.auth_name = file_entry->auth_name;
data_entry.auth_data = file_entry->auth_data;
data_entry.auth_data_length = file_entry->auth_data_length;
IceSetPaAuthData (1, &data_entry);
return file_entry;
}
static gboolean
update_iceauthority (GsmXsmpServer *server,
gboolean adding)
{
char *filename;
char **our_network_ids;
FILE *fp;
IceAuthFileEntry *auth_entry;
GSList *entries;
GSList *e;
int i;
gboolean ok = FALSE;
filename = IceAuthFileName ();
if (IceLockAuthFile (filename,
GSM_ICE_AUTH_RETRIES,
GSM_ICE_AUTH_INTERVAL,
GSM_ICE_AUTH_LOCK_TIMEOUT) != IceAuthLockSuccess) {
return FALSE;
}
our_network_ids = g_malloc (server->priv->num_local_xsmp_sockets * sizeof (char *));
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
our_network_ids[i] = IceGetListenConnectionString (server->priv->xsmp_sockets[i]);
}
entries = NULL;
fp = fopen (filename, "r+");
if (fp != NULL) {
while ((auth_entry = IceReadAuthFileEntry (fp)) != NULL) {
/* Skip/delete entries with no network ID (invalid), or with
* our network ID; if we're starting up, an entry with our
* ID must be a stale entry left behind by an old process,
* and if we're shutting down, it won't be valid in the
* future, so either way we want to remove it from the list.
*/
if (!auth_entry->network_id) {
IceFreeAuthFileEntry (auth_entry);
continue;
}
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
if (!strcmp (auth_entry->network_id, our_network_ids[i])) {
IceFreeAuthFileEntry (auth_entry);
break;
}
}
if (i != server->priv->num_local_xsmp_sockets) {
continue;
}
entries = g_slist_prepend (entries, auth_entry);
}
rewind (fp);
} else {
int fd;
if (g_file_test (filename, G_FILE_TEST_EXISTS)) {
g_warning ("Unable to read ICE authority file: %s", filename);
goto cleanup;
}
fd = open (filename, O_CREAT | O_WRONLY, 0600);
fp = fdopen (fd, "w");
if (!fp) {
g_warning ("Unable to write to ICE authority file: %s", filename);
if (fd != -1) {
close (fd);
}
goto cleanup;
}
}
if (adding) {
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
entries = g_slist_append (entries,
auth_entry_new ("ICE", our_network_ids[i]));
entries = g_slist_prepend (entries,
auth_entry_new ("XSMP", our_network_ids[i]));
}
}
for (e = entries; e; e = e->next) {
IceAuthFileEntry *auth_entry = e->data;
IceWriteAuthFileEntry (fp, auth_entry);
IceFreeAuthFileEntry (auth_entry);
}
g_slist_free (entries);
fclose (fp);
ok = TRUE;
cleanup:
IceUnlockAuthFile (filename);
for (i = 0; i < server->priv->num_local_xsmp_sockets; i++) {
free (our_network_ids[i]);
}
g_free (our_network_ids);
return ok;
}
static void
setup_listener (GsmXsmpServer *server)
{
char error[256];
mode_t saved_umask;
char *network_id_list;
int i;
int res;
/* Set up sane error handlers */
IceSetErrorHandler (ice_error_handler);
IceSetIOErrorHandler (ice_io_error_handler);
SmsSetErrorHandler (sms_error_handler);
/* Initialize libSM; we pass NULL for hostBasedAuthProc to disable
* host-based authentication.
*/
res = SmsInitialize (PACKAGE,
VERSION,
(SmsNewClientProc)accept_xsmp_connection,
server,
NULL,
sizeof (error),
error);
if (! res) {
gsm_util_init_error (TRUE, "Could not initialize libSM: %s", error);
}
#ifdef HAVE_X11_XTRANS_XTRANS_H
/* By default, IceListenForConnections will open one socket for each
* transport type known to X. We don't want connections from remote
* hosts, so for security reasons it would be best if ICE didn't
* even open any non-local sockets. So we use an internal ICElib
* method to disable them here. Unfortunately, there is no way to
* ask X what transport types it knows about, so we're forced to
* guess.
*/
_IceTransNoListen ("tcp");
#endif
/* Create the XSMP socket. Older versions of IceListenForConnections
* have a bug which causes the umask to be set to 0 on certain types
* of failures. Probably not an issue on any modern systems, but
* we'll play it safe.
*/
saved_umask = umask (0);
umask (saved_umask);
res = IceListenForConnections (&server->priv->num_xsmp_sockets,
&server->priv->xsmp_sockets,
sizeof (error),
error);
if (! res) {
gsm_util_init_error (TRUE, _("Could not create ICE listening socket: %s"), error);
}
umask (saved_umask);
/* Find the local sockets in the returned socket list and move them
* to the start of the list.
*/
for (i = server->priv->num_local_xsmp_sockets = 0; i < server->priv->num_xsmp_sockets; i++) {
char *id = IceGetListenConnectionString (server->priv->xsmp_sockets[i]);
if (!strncmp (id, "local/", sizeof ("local/") - 1) ||
!strncmp (id, "unix/", sizeof ("unix/") - 1)) {
if (i > server->priv->num_local_xsmp_sockets) {
IceListenObj tmp;
tmp = server->priv->xsmp_sockets[i];
server->priv->xsmp_sockets[i] = server->priv->xsmp_sockets[server->priv->num_local_xsmp_sockets];
server->priv->xsmp_sockets[server->priv->num_local_xsmp_sockets] = tmp;
}
server->priv->num_local_xsmp_sockets++;
}
free (id);
}
if (server->priv->num_local_xsmp_sockets == 0) {
gsm_util_init_error (TRUE, "IceListenForConnections did not return a local listener!");
}
#ifdef HAVE_X11_XTRANS_XTRANS_H
if (server->priv->num_local_xsmp_sockets != server->priv->num_xsmp_sockets) {
/* Xtrans was apparently compiled with support for some
* non-local transport besides TCP (which we disabled above); we
* won't create IO watches on those extra sockets, so
* connections to them will never be noticed, but they're still
* there, which is inelegant.
*
* If the g_warning below is triggering for you and you want to
* stop it, the fix is to add additional _IceTransNoListen()
* calls above.
*/
network_id_list = IceComposeNetworkIdList (server->priv->num_xsmp_sockets - server->priv->num_local_xsmp_sockets,
server->priv->xsmp_sockets + server->priv->num_local_xsmp_sockets);
g_warning ("IceListenForConnections returned %d non-local listeners: %s",
server->priv->num_xsmp_sockets - server->priv->num_local_xsmp_sockets,
network_id_list);
free (network_id_list);
}
#endif
/* Update .ICEauthority with new auth entries for our socket */
if (!update_iceauthority (server, TRUE)) {
/* FIXME: is this really fatal? Hm... */
gsm_util_init_error (TRUE,
"Could not update ICEauthority file %s",
IceAuthFileName ());
}
network_id_list = IceComposeNetworkIdList (server->priv->num_local_xsmp_sockets,
server->priv->xsmp_sockets);
gsm_util_setenv ("SESSION_MANAGER", network_id_list);
g_debug ("GsmXsmpServer: SESSION_MANAGER=%s\n", network_id_list);
free (network_id_list);
}
static GObject *
gsm_xsmp_server_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_properties)
{
GsmXsmpServer *xsmp_server;
xsmp_server = GSM_XSMP_SERVER (G_OBJECT_CLASS (gsm_xsmp_server_parent_class)->constructor (type,
n_construct_properties,
construct_properties));
setup_listener (xsmp_server);
return G_OBJECT (xsmp_server);
}
static void
gsm_xsmp_server_class_init (GsmXsmpServerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->get_property = gsm_xsmp_server_get_property;
object_class->set_property = gsm_xsmp_server_set_property;
object_class->constructor = gsm_xsmp_server_constructor;
object_class->finalize = gsm_xsmp_server_finalize;
g_object_class_install_property (object_class,
PROP_CLIENT_STORE,
g_param_spec_object ("client-store",
NULL,
NULL,
GSM_TYPE_STORE,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
g_type_class_add_private (klass, sizeof (GsmXsmpServerPrivate));
}
static void
gsm_xsmp_server_init (GsmXsmpServer *xsmp_server)
{
xsmp_server->priv = GSM_XSMP_SERVER_GET_PRIVATE (xsmp_server);
}
static void
gsm_xsmp_server_finalize (GObject *object)
{
GsmXsmpServer *xsmp_server;
g_return_if_fail (object != NULL);
g_return_if_fail (GSM_IS_XSMP_SERVER (object));
xsmp_server = GSM_XSMP_SERVER (object);
g_return_if_fail (xsmp_server->priv != NULL);
IceFreeListenObjs (xsmp_server->priv->num_xsmp_sockets,
xsmp_server->priv->xsmp_sockets);
if (xsmp_server->priv->client_store != NULL) {
g_object_unref (xsmp_server->priv->client_store);
}
G_OBJECT_CLASS (gsm_xsmp_server_parent_class)->finalize (object);
}
GsmXsmpServer *
gsm_xsmp_server_new (GsmStore *client_store)
{
if (xsmp_server_object != NULL) {
g_object_ref (xsmp_server_object);
} else {
xsmp_server_object = g_object_new (GSM_TYPE_XSMP_SERVER,
"client-store", client_store,
NULL);
g_object_add_weak_pointer (xsmp_server_object,
(gpointer *) &xsmp_server_object);
}
return GSM_XSMP_SERVER (xsmp_server_object);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2564_1 |
crossvul-cpp_data_good_2663_0 | /*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* The functions from print-esp.c used in this file are only defined when both
* OpenSSL and evp.h are detected. Employ the same preprocessor device here.
*/
#ifndef HAVE_OPENSSL_EVP_H
#undef HAVE_LIBCRYPTO
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
/* refer to RFC 2408 */
typedef u_char cookie_t[8];
typedef u_char msgid_t[4];
#define PORT_ISAKMP 500
/* 3.1 ISAKMP Header Format (IKEv1 and IKEv2)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Initiator !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Responder !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Message ID !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp {
cookie_t i_ck; /* Initiator Cookie */
cookie_t r_ck; /* Responder Cookie */
uint8_t np; /* Next Payload Type */
uint8_t vers;
#define ISAKMP_VERS_MAJOR 0xf0
#define ISAKMP_VERS_MAJOR_SHIFT 4
#define ISAKMP_VERS_MINOR 0x0f
#define ISAKMP_VERS_MINOR_SHIFT 0
uint8_t etype; /* Exchange Type */
uint8_t flags; /* Flags */
msgid_t msgid;
uint32_t len; /* Length */
};
/* Next Payload Type */
#define ISAKMP_NPTYPE_NONE 0 /* NONE*/
#define ISAKMP_NPTYPE_SA 1 /* Security Association */
#define ISAKMP_NPTYPE_P 2 /* Proposal */
#define ISAKMP_NPTYPE_T 3 /* Transform */
#define ISAKMP_NPTYPE_KE 4 /* Key Exchange */
#define ISAKMP_NPTYPE_ID 5 /* Identification */
#define ISAKMP_NPTYPE_CERT 6 /* Certificate */
#define ISAKMP_NPTYPE_CR 7 /* Certificate Request */
#define ISAKMP_NPTYPE_HASH 8 /* Hash */
#define ISAKMP_NPTYPE_SIG 9 /* Signature */
#define ISAKMP_NPTYPE_NONCE 10 /* Nonce */
#define ISAKMP_NPTYPE_N 11 /* Notification */
#define ISAKMP_NPTYPE_D 12 /* Delete */
#define ISAKMP_NPTYPE_VID 13 /* Vendor ID */
#define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */
#define IKEv1_MAJOR_VERSION 1
#define IKEv1_MINOR_VERSION 0
#define IKEv2_MAJOR_VERSION 2
#define IKEv2_MINOR_VERSION 0
/* Flags */
#define ISAKMP_FLAG_E 0x01 /* Encryption Bit */
#define ISAKMP_FLAG_C 0x02 /* Commit Bit */
#define ISAKMP_FLAG_extra 0x04
/* IKEv2 */
#define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */
#define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */
#define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */
/* 3.2 Payload Generic Header
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! RESERVED ! Payload Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_gen {
uint8_t np; /* Next Payload */
uint8_t critical; /* bit 7 - critical, rest is RESERVED */
uint16_t len; /* Payload Length */
};
/* 3.3 Data Attributes
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
!A! Attribute Type ! AF=0 Attribute Length !
!F! ! AF=1 Attribute Value !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. AF=0 Attribute Value .
. AF=1 Not Transmitted .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_data {
uint16_t type; /* defined by DOI-spec, and Attribute Format */
uint16_t lorv; /* if f equal 1, Attribute Length */
/* if f equal 0, Attribute Value */
/* if f equal 1, Attribute Value */
};
/* 3.4 Security Association Payload */
/* MAY NOT be used, because of being defined in ipsec-doi. */
/*
If the current payload is the last in the message,
then the value of the next payload field will be 0.
This field MUST NOT contain the
values for the Proposal or Transform payloads as they are considered
part of the security association negotiation. For example, this
field would contain the value "10" (Nonce payload) in the first
message of a Base Exchange (see Section 4.4) and the value "0" in the
first message of an Identity Protect Exchange (see Section 4.5).
*/
struct ikev1_pl_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
/* 3.5 Proposal Payload */
/*
The value of the next payload field MUST only contain the value "2"
or "0". If there are additional Proposal payloads in the message,
then this field will be 2. If the current Proposal payload is the
last within the security association proposal, then this field will
be 0.
*/
struct ikev1_pl_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
/* SPI */
};
/* 3.6 Transform Payload */
/*
The value of the next payload field MUST only contain the value "3"
or "0". If there are additional Transform payloads in the proposal,
then this field will be 3. If the current Transform payload is the
last within the proposal, then this field will be 0.
*/
struct ikev1_pl_t {
struct isakmp_gen h;
uint8_t t_no; /* Transform # */
uint8_t t_id; /* Transform-Id */
uint16_t reserved; /* RESERVED2 */
/* SA Attributes */
};
/* 3.7 Key Exchange Payload */
struct ikev1_pl_ke {
struct isakmp_gen h;
/* Key Exchange Data */
};
/* 3.8 Identification Payload */
/* MUST NOT to be used, because of being defined in ipsec-doi. */
struct ikev1_pl_id {
struct isakmp_gen h;
union {
uint8_t id_type; /* ID Type */
uint32_t doi_data; /* DOI Specific ID Data */
} d;
/* Identification Data */
};
/* 3.9 Certificate Payload */
struct ikev1_pl_cert {
struct isakmp_gen h;
uint8_t encode; /* Cert Encoding */
char cert; /* Certificate Data */
/*
This field indicates the type of
certificate or certificate-related information contained in the
Certificate Data field.
*/
};
/* 3.10 Certificate Request Payload */
struct ikev1_pl_cr {
struct isakmp_gen h;
uint8_t num_cert; /* # Cert. Types */
/*
Certificate Types (variable length)
-- Contains a list of the types of certificates requested,
sorted in order of preference. Each individual certificate
type is 1 octet. This field is NOT requiredo
*/
/* # Certificate Authorities (1 octet) */
/* Certificate Authorities (variable length) */
};
/* 3.11 Hash Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_hash {
struct isakmp_gen h;
/* Hash Data */
};
/* 3.12 Signature Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_sig {
struct isakmp_gen h;
/* Signature Data */
};
/* 3.13 Nonce Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_nonce {
struct isakmp_gen h;
/* Nonce Data */
};
/* 3.14 Notification Payload */
struct ikev1_pl_n {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
/* SPI */
/* Notification Data */
};
/* 3.14.1 Notify Message Types */
/* NOTIFY MESSAGES - ERROR TYPES */
#define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1
#define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2
#define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3
#define ISAKMP_NTYPE_INVALID_COOKIE 4
#define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5
#define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6
#define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7
#define ISAKMP_NTYPE_INVALID_FLAGS 8
#define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9
#define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10
#define ISAKMP_NTYPE_INVALID_SPI 11
#define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12
#define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13
#define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14
#define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15
#define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16
#define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17
#define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18
#define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19
#define ISAKMP_NTYPE_INVALID_CERTIFICATE 20
#define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21
#define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22
#define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23
#define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24
#define ISAKMP_NTYPE_INVALID_SIGNATURE 25
#define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26
/* 3.15 Delete Payload */
struct ikev1_pl_d {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-Id */
uint8_t spi_size; /* SPI Size */
uint16_t num_spi; /* # of SPIs */
/* SPI(es) */
};
struct ikev1_ph1tab {
struct ikev1_ph1 *head;
struct ikev1_ph1 *tail;
int len;
};
struct isakmp_ph2tab {
struct ikev1_ph2 *head;
struct ikev1_ph2 *tail;
int len;
};
/* IKEv2 (RFC4306) */
/* 3.3 Security Association Payload -- generic header */
/* 3.3.1. Proposal Substructure */
struct ikev2_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
};
/* 3.3.2. Transform Substructure */
struct ikev2_t {
struct isakmp_gen h;
uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/
uint8_t res2; /* reserved byte */
uint16_t t_id; /* Transform ID */
};
enum ikev2_t_type {
IV2_T_ENCR = 1,
IV2_T_PRF = 2,
IV2_T_INTEG= 3,
IV2_T_DH = 4,
IV2_T_ESN = 5
};
/* 3.4. Key Exchange Payload */
struct ikev2_ke {
struct isakmp_gen h;
uint16_t ke_group;
uint16_t ke_res1;
/* KE data */
};
/* 3.5. Identification Payloads */
enum ikev2_id_type {
ID_IPV4_ADDR=1,
ID_FQDN=2,
ID_RFC822_ADDR=3,
ID_IPV6_ADDR=5,
ID_DER_ASN1_DN=9,
ID_DER_ASN1_GN=10,
ID_KEY_ID=11
};
struct ikev2_id {
struct isakmp_gen h;
uint8_t type; /* ID type */
uint8_t res1;
uint16_t res2;
/* SPI */
/* Notification Data */
};
/* 3.10 Notification Payload */
struct ikev2_n {
struct isakmp_gen h;
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
};
enum ikev2_n_type {
IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1,
IV2_NOTIFY_INVALID_IKE_SPI = 4,
IV2_NOTIFY_INVALID_MAJOR_VERSION = 5,
IV2_NOTIFY_INVALID_SYNTAX = 7,
IV2_NOTIFY_INVALID_MESSAGE_ID = 9,
IV2_NOTIFY_INVALID_SPI =11,
IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14,
IV2_NOTIFY_INVALID_KE_PAYLOAD =17,
IV2_NOTIFY_AUTHENTICATION_FAILED =24,
IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34,
IV2_NOTIFY_NO_ADDITIONAL_SAS =35,
IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36,
IV2_NOTIFY_FAILED_CP_REQUIRED =37,
IV2_NOTIFY_INVALID_SELECTORS =39,
IV2_NOTIFY_INITIAL_CONTACT =16384,
IV2_NOTIFY_SET_WINDOW_SIZE =16385,
IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386,
IV2_NOTIFY_IPCOMP_SUPPORTED =16387,
IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388,
IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389,
IV2_NOTIFY_COOKIE =16390,
IV2_NOTIFY_USE_TRANSPORT_MODE =16391,
IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392,
IV2_NOTIFY_REKEY_SA =16393,
IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394,
IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395
};
struct notify_messages {
uint16_t type;
char *msg;
};
/* 3.8 Authentication Payload */
struct ikev2_auth {
struct isakmp_gen h;
uint8_t auth_method; /* Protocol-ID */
uint8_t reserved[3];
/* authentication data */
};
enum ikev2_auth_type {
IV2_RSA_SIG = 1,
IV2_SHARED = 2,
IV2_DSS_SIG = 3
};
/* refer to RFC 2409 */
#if 0
/* isakmp sa structure */
struct oakley_sa {
uint8_t proto_id; /* OAKLEY */
vchar_t *spi; /* spi */
uint8_t dhgrp; /* DH; group */
uint8_t auth_t; /* method of authentication */
uint8_t prf_t; /* type of prf */
uint8_t hash_t; /* type of hash */
uint8_t enc_t; /* type of cipher */
uint8_t life_t; /* type of duration of lifetime */
uint32_t ldur; /* life duration */
};
#endif
/* refer to RFC 2407 */
#define IPSEC_DOI 1
/* 4.2 IPSEC Situation Definition */
#define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001
#define IPSECDOI_SIT_SECRECY 0x00000002
#define IPSECDOI_SIT_INTEGRITY 0x00000004
/* 4.4.1 IPSEC Security Protocol Identifiers */
/* 4.4.2 IPSEC ISAKMP Transform Values */
#define IPSECDOI_PROTO_ISAKMP 1
#define IPSECDOI_KEY_IKE 1
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_AH 2
/* 4.4.3 IPSEC AH Transform Values */
#define IPSECDOI_AH_MD5 2
#define IPSECDOI_AH_SHA 3
#define IPSECDOI_AH_DES 4
#define IPSECDOI_AH_SHA2_256 5
#define IPSECDOI_AH_SHA2_384 6
#define IPSECDOI_AH_SHA2_512 7
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_ESP 3
/* 4.4.4 IPSEC ESP Transform Identifiers */
#define IPSECDOI_ESP_DES_IV64 1
#define IPSECDOI_ESP_DES 2
#define IPSECDOI_ESP_3DES 3
#define IPSECDOI_ESP_RC5 4
#define IPSECDOI_ESP_IDEA 5
#define IPSECDOI_ESP_CAST 6
#define IPSECDOI_ESP_BLOWFISH 7
#define IPSECDOI_ESP_3IDEA 8
#define IPSECDOI_ESP_DES_IV32 9
#define IPSECDOI_ESP_RC4 10
#define IPSECDOI_ESP_NULL 11
#define IPSECDOI_ESP_RIJNDAEL 12
#define IPSECDOI_ESP_AES 12
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPCOMP 4
/* 4.4.5 IPSEC IPCOMP Transform Identifiers */
#define IPSECDOI_IPCOMP_OUI 1
#define IPSECDOI_IPCOMP_DEFLATE 2
#define IPSECDOI_IPCOMP_LZS 3
/* 4.5 IPSEC Security Association Attributes */
#define IPSECDOI_ATTR_SA_LTYPE 1 /* B */
#define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1
#define IPSECDOI_ATTR_SA_LTYPE_SEC 1
#define IPSECDOI_ATTR_SA_LTYPE_KB 2
#define IPSECDOI_ATTR_SA_LDUR 2 /* V */
#define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */
#define IPSECDOI_ATTR_GRP_DESC 3 /* B */
#define IPSECDOI_ATTR_ENC_MODE 4 /* B */
/* default value: host dependent */
#define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1
#define IPSECDOI_ATTR_ENC_MODE_TRNS 2
#define IPSECDOI_ATTR_AUTH 5 /* B */
/* 0 means not to use authentication. */
#define IPSECDOI_ATTR_AUTH_HMAC_MD5 1
#define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2
#define IPSECDOI_ATTR_AUTH_DES_MAC 3
#define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/
/*
* When negotiating ESP without authentication, the Auth
* Algorithm attribute MUST NOT be included in the proposal.
* When negotiating ESP without confidentiality, the Auth
* Algorithm attribute MUST be included in the proposal and
* the ESP transform ID must be ESP_NULL.
*/
#define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */
#define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */
#define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */
#define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */
/* 4.6.1 Security Association Payload */
struct ipsecdoi_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
struct ipsecdoi_secrecy_h {
uint16_t len;
uint16_t reserved;
};
/* 4.6.2.1 Identification Type Values */
struct ipsecdoi_id {
struct isakmp_gen h;
uint8_t type; /* ID Type */
uint8_t proto_id; /* Protocol ID */
uint16_t port; /* Port */
/* Identification Data */
};
#define IPSECDOI_ID_IPV4_ADDR 1
#define IPSECDOI_ID_FQDN 2
#define IPSECDOI_ID_USER_FQDN 3
#define IPSECDOI_ID_IPV4_ADDR_SUBNET 4
#define IPSECDOI_ID_IPV6_ADDR 5
#define IPSECDOI_ID_IPV6_ADDR_SUBNET 6
#define IPSECDOI_ID_IPV4_ADDR_RANGE 7
#define IPSECDOI_ID_IPV6_ADDR_RANGE 8
#define IPSECDOI_ID_DER_ASN1_DN 9
#define IPSECDOI_ID_DER_ASN1_GN 10
#define IPSECDOI_ID_KEY_ID 11
/* 4.6.3 IPSEC DOI Notify Message Types */
/* Notify Messages - Status Types */
#define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576
#define IPSECDOI_NTYPE_REPLAY_STATUS 24577
#define IPSECDOI_NTYPE_INITIAL_CONTACT 24578
#define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \
netdissect_options *ndo, u_char tpay, \
const struct isakmp_gen *ext, \
u_int item_len, \
const u_char *end_pointer, \
uint32_t phase,\
uint32_t doi0, \
uint32_t proto0, int depth)
DECLARE_PRINTER(v1_sa);
DECLARE_PRINTER(v1_p);
DECLARE_PRINTER(v1_t);
DECLARE_PRINTER(v1_ke);
DECLARE_PRINTER(v1_id);
DECLARE_PRINTER(v1_cert);
DECLARE_PRINTER(v1_cr);
DECLARE_PRINTER(v1_sig);
DECLARE_PRINTER(v1_hash);
DECLARE_PRINTER(v1_nonce);
DECLARE_PRINTER(v1_n);
DECLARE_PRINTER(v1_d);
DECLARE_PRINTER(v1_vid);
DECLARE_PRINTER(v2_sa);
DECLARE_PRINTER(v2_ke);
DECLARE_PRINTER(v2_ID);
DECLARE_PRINTER(v2_cert);
DECLARE_PRINTER(v2_cr);
DECLARE_PRINTER(v2_auth);
DECLARE_PRINTER(v2_nonce);
DECLARE_PRINTER(v2_n);
DECLARE_PRINTER(v2_d);
DECLARE_PRINTER(v2_vid);
DECLARE_PRINTER(v2_TS);
DECLARE_PRINTER(v2_cp);
DECLARE_PRINTER(v2_eap);
static const u_char *ikev2_e_print(netdissect_options *ndo,
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth);
static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext,
const u_char *ep, uint32_t phase,
uint32_t doi, uint32_t proto,
int depth);
static char *numstr(int);
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base);
#define MAXINITIATORS 20
static int ninitiator = 0;
union inaddr_u {
struct in_addr in4;
struct in6_addr in6;
};
static struct {
cookie_t initiator;
u_int version;
union inaddr_u iaddr;
union inaddr_u raddr;
} cookiecache[MAXINITIATORS];
/* protocol id */
static const char *protoidstr[] = {
NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp",
};
/* isakmp->np */
static const char *npstr[] = {
"none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */
"sig", "nonce", "n", "d", "vid", /* 9 - 13 */
"pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */
"pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */
"pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */
"pay29", "pay30", "pay31", "pay32", /* 29- 32 */
"v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */
"v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */
"v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */
"v2eap", /* 48 */
};
/* isakmp->np */
static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth) = {
NULL,
ikev1_sa_print,
ikev1_p_print,
ikev1_t_print,
ikev1_ke_print,
ikev1_id_print,
ikev1_cert_print,
ikev1_cr_print,
ikev1_hash_print,
ikev1_sig_print,
ikev1_nonce_print,
ikev1_n_print,
ikev1_d_print,
ikev1_vid_print, /* 13 */
NULL, NULL, NULL, NULL, NULL, /* 14- 18 */
NULL, NULL, NULL, NULL, NULL, /* 19- 23 */
NULL, NULL, NULL, NULL, NULL, /* 24- 28 */
NULL, NULL, NULL, NULL, /* 29- 32 */
ikev2_sa_print, /* 33 */
ikev2_ke_print, /* 34 */
ikev2_ID_print, /* 35 */
ikev2_ID_print, /* 36 */
ikev2_cert_print, /* 37 */
ikev2_cr_print, /* 38 */
ikev2_auth_print, /* 39 */
ikev2_nonce_print, /* 40 */
ikev2_n_print, /* 41 */
ikev2_d_print, /* 42 */
ikev2_vid_print, /* 43 */
ikev2_TS_print, /* 44 */
ikev2_TS_print, /* 45 */
NULL, /* ikev2_e_print,*/ /* 46 - special */
ikev2_cp_print, /* 47 */
ikev2_eap_print, /* 48 */
};
/* isakmp->etype */
static const char *etypestr[] = {
/* IKEv1 exchange types */
"none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */
"oakley-quick", "oakley-newgroup", /* 32-33 */
/* IKEv2 exchange types */
"ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
#define PROTOIDSTR(x) STR_OR_ID(x, protoidstr)
#define NPSTR(x) STR_OR_ID(x, npstr)
#define ETYPESTR(x) STR_OR_ID(x, etypestr)
#define CHECKLEN(p, np) \
if (ep < (const u_char *)(p)) { \
ND_PRINT((ndo," [|%s]", NPSTR(np))); \
goto done; \
}
#define NPFUNC(x) \
(((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \
? npfunc[(x)] : NULL)
static int
iszero(const u_char *p, size_t l)
{
while (l--) {
if (*p++)
return 0;
}
return 1;
}
/* find cookie from initiator cache */
static int
cookie_find(cookie_t *in)
{
int i;
for (i = 0; i < MAXINITIATORS; i++) {
if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0)
return i;
}
return -1;
}
/* record initiator */
static void
cookie_record(cookie_t *in, const u_char *bp2)
{
int i;
const struct ip *ip;
const struct ip6_hdr *ip6;
i = cookie_find(in);
if (0 <= i) {
ninitiator = (i + 1) % MAXINITIATORS;
return;
}
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
cookiecache[ninitiator].version = 4;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp2;
cookiecache[ninitiator].version = 6;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr));
break;
default:
return;
}
UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in));
ninitiator = (ninitiator + 1) % MAXINITIATORS;
}
#define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1)
#define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0)
static int
cookie_sidecheck(int i, const u_char *bp2, int initiator)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
if (cookiecache[i].version != 4)
return 0;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0)
return 1;
}
break;
case 6:
if (cookiecache[i].version != 6)
return 0;
ip6 = (const struct ip6_hdr *)bp2;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
}
break;
default:
break;
}
return 0;
}
static void
hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
const uint8_t *p;
size_t i;
p = loc;
for (i = 0; i < len; i++)
ND_PRINT((ndo,"%02x", p[i] & 0xff));
}
static int
rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
ND_TCHECK2(*loc, len);
hexprint(ndo, loc, len);
return 1;
trunc:
return 0;
}
/*
* returns false if we run out of data buffer
*/
static int ike_show_somedata(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
/* there is too much data, just show some of it */
const u_char *end = ep - 20;
int elen = 20;
int len = ep - cp;
if(len > 10) {
len = 10;
}
/* really shouldn't happen because of above */
if(end < cp + len) {
end = cp+len;
elen = ep - end;
}
ND_PRINT((ndo," data=("));
if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc;
ND_PRINT((ndo, "..."));
if(elen) {
if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc;
}
ND_PRINT((ndo,")"));
return 1;
trunc:
return 0;
}
struct attrmap {
const char *type;
u_int nvalue;
const char *value[30]; /*XXX*/
};
static const u_char *
ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
static const u_char *
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
{
int totlen;
uint32_t t;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
static const u_char *
ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0, int depth)
{
const struct ikev1_pl_sa *p;
struct ikev1_pl_sa sa;
uint32_t doi, sit, ident;
const u_char *cp, *np;
int t;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA)));
p = (const struct ikev1_pl_sa *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&sa, ext, sizeof(sa));
doi = ntohl(sa.doi);
sit = ntohl(sa.sit);
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit)));
return (const u_char *)(p + 1);
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," situation="));
t = 0;
if (sit & 0x01) {
ND_PRINT((ndo,"identity"));
t++;
}
if (sit & 0x02) {
ND_PRINT((ndo,"%ssecrecy", t ? "+" : ""));
t++;
}
if (sit & 0x04)
ND_PRINT((ndo,"%sintegrity", t ? "+" : ""));
np = (const u_char *)ext + sizeof(sa);
if (sit != 0x01) {
ND_TCHECK2(*(ext + 1), sizeof(ident));
UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident));
ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident)));
np += sizeof(ident);
}
ext = (const struct isakmp_gen *)np;
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0,
depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA)));
return NULL;
}
static const u_char *
ikev1_p_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_p *p;
struct ikev1_pl_p prop;
const u_char *cp;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P)));
p = (const struct ikev1_pl_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ND_PRINT((ndo," #%d protoid=%s transform=%d",
prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t));
if (prop.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size))
goto trunc;
}
ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size);
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0,
prop.prot_id, depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const char *ikev1_p_map[] = {
NULL, "ike",
};
static const char *ikev2_t_type_map[]={
NULL, "encr", "prf", "integ", "dh", "esn"
};
static const char *ah_p_map[] = {
NULL, "(reserved)", "md5", "sha", "1des",
"sha2-256", "sha2-384", "sha2-512",
};
static const char *prf_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "hmac-tiger",
"aes128_xcbc"
};
static const char *integ_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "dec-mac",
"kpdk-md5", "aes-xcbc"
};
static const char *esn_p_map[] = {
"no-esn", "esn"
};
static const char *dh_p_map[] = {
NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
};
static const char *esp_p_map[] = {
NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast",
"blowfish", "3idea", "1des-iv32", "rc4", "null", "aes"
};
static const char *ipcomp_p_map[] = {
NULL, "oui", "deflate", "lzs",
};
static const struct attrmap ipsec_t_map[] = {
{ NULL, 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "life", 0, { NULL } },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "enc mode", 3, { NULL, "tunnel", "transport", }, },
{ "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, },
{ "keylen", 0, { NULL } },
{ "rounds", 0, { NULL } },
{ "dictsize", 0, { NULL } },
{ "privalg", 0, { NULL } },
};
static const struct attrmap encr_t_map[] = {
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/
{ "keylen", 14, { NULL }},
};
static const struct attrmap oakley_t_map[] = {
{ NULL, 0, { NULL } },
{ "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5",
"3des", "cast", "aes", }, },
{ "hash", 7, { NULL, "md5", "sha1", "tiger",
"sha2-256", "sha2-384", "sha2-512", }, },
{ "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc",
"rsa enc revised", }, },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, },
{ "group prime", 0, { NULL } },
{ "group gen1", 0, { NULL } },
{ "group gen2", 0, { NULL } },
{ "group curve A", 0, { NULL } },
{ "group curve B", 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "lifeduration", 0, { NULL } },
{ "prf", 0, { NULL } },
{ "keylen", 0, { NULL } },
{ "field", 0, { NULL } },
{ "order", 0, { NULL } },
};
static const u_char *
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
static const u_char *
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 20)
ND_PRINT((ndo," len=%d [bad: < 20]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
static const u_char *
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
static const u_char *
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
static const u_char *
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
static const u_char *
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
static const u_char *
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4));
if (ntohs(e.len) > 4) {
if (ndo->ndo_vflag > 2) {
ND_PRINT((ndo, " "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " "));
if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep))
goto trunc;
}
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
static const u_char *
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev1_d_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_d *p;
struct ikev1_pl_d d;
const uint8_t *q;
uint32_t doi;
uint32_t proto;
int i;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D)));
p = (const struct ikev1_pl_d *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&d, ext, sizeof(d));
doi = ntohl(d.doi);
proto = d.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%u", doi));
ND_PRINT((ndo," proto=%u", proto));
} else {
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
}
ND_PRINT((ndo," spilen=%u", d.spi_size));
ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi)));
ND_PRINT((ndo," spi="));
q = (const uint8_t *)(p + 1);
for (i = 0; i < ntohs(d.num_spi); i++) {
if (i != 0)
ND_PRINT((ndo,","));
if (!rawprint(ndo, (const uint8_t *)q, d.spi_size))
goto trunc;
q += d.spi_size;
}
return q;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D)));
return NULL;
}
static const u_char *
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
/************************************************************/
/* */
/* IKE v2 - rfc4306 - dissector */
/* */
/************************************************************/
static void
ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical)
{
ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : ""));
}
static const u_char *
ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_t_print(netdissect_options *ndo, int tcount,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep)
{
const struct ikev2_t *p;
struct ikev2_t t;
uint16_t t_id;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
p = (const struct ikev2_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical);
t_id = ntohs(t.t_id);
map = NULL;
nmap = 0;
switch (t.t_type) {
case IV2_T_ENCR:
idstr = STR_OR_ID(t_id, esp_p_map);
map = encr_t_map;
nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]);
break;
case IV2_T_PRF:
idstr = STR_OR_ID(t_id, prf_p_map);
break;
case IV2_T_INTEG:
idstr = STR_OR_ID(t_id, integ_p_map);
break;
case IV2_T_DH:
idstr = STR_OR_ID(t_id, dh_p_map);
break;
case IV2_T_ESN:
idstr = STR_OR_ID(t_id, esn_p_map);
break;
default:
idstr = NULL;
break;
}
if (idstr)
ND_PRINT((ndo," #%u type=%s id=%s ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
idstr));
else
ND_PRINT((ndo," #%u type=%s id=%u ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const u_char *
ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_ke ke;
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));
if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
goto trunc;
}
return (const u_char *)ext + ntohs(ke.h.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cert_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_cr_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_nonce_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, "nonce", e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," nonce=("));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < ntohs(e.len)) {
if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
/* notify payloads */
static const u_char *
ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if (cp < ep) {
if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if (showsomedata) {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev2_d_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_e_print(netdissect_options *ndo,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t phase,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t doi,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t proto,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
int depth)
{
struct isakmp_gen e;
const u_char *dat;
volatile int dlen;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
dlen = ntohs(e.len)-4;
ND_PRINT((ndo," len=%d", dlen));
if (2 < ndo->ndo_vflag && 4 < dlen) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen))
goto trunc;
}
dat = (const u_char *)(ext+1);
ND_TCHECK2(*dat, dlen);
#ifdef HAVE_LIBCRYPTO
/* try to decypt it! */
if(esp_print_decrypt_buffer_by_ikev2(ndo,
base->flags & ISAKMP_FLAG_I,
base->i_ck, base->r_ck,
dat, dat+dlen)) {
ext = (const struct isakmp_gen *)ndo->ndo_packetp;
/* got it decrypted, print stuff inside. */
ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend,
phase, doi, proto, depth+1);
}
#endif
/* always return NULL, because E must be at end, and NP refers
* to what was inside.
*/
return NULL;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cp_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_eap_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ike_sub0_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "#%d", x);
return buf;
}
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int i;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo," phase %d", phase));
else
ND_PRINT((ndo," phase %d/others", phase));
i = cookie_find(&base->i_ck);
if (i < 0) {
if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) {
/* the first packet */
ND_PRINT((ndo," I"));
if (bp2)
cookie_record(&base->i_ck, bp2);
} else
ND_PRINT((ndo," ?"));
} else {
if (bp2 && cookie_isinitiator(i, bp2))
ND_PRINT((ndo," I"));
else if (bp2 && cookie_isresponder(i, bp2))
ND_PRINT((ndo," R"));
else
ND_PRINT((ndo," ?"));
}
ND_PRINT((ndo," %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "",
base->flags & ISAKMP_FLAG_C ? "C" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo,":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np);
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
static const u_char *
ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base,
u_char np,
const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (np == ISAKMP_NPTYPE_v2E) {
cp = ikev2_e_print(ndo, base, np, ext, item_len,
ep, phase, doi, proto, depth);
} else if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len,
ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static void
ikev2_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2 _U_, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo, " parent_sa"));
else
ND_PRINT((ndo, " child_sa "));
ND_PRINT((ndo, " %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo, "[%s%s%s]",
base->flags & ISAKMP_FLAG_I ? "I" : "",
base->flags & ISAKMP_FLAG_V ? "V" : "",
base->flags & ISAKMP_FLAG_R ? "R" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo, ":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np)
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
void
isakmp_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
const struct isakmp *p;
struct isakmp base;
const u_char *ep;
int major, minor;
#ifdef HAVE_LIBCRYPTO
/* initialize SAs */
if (ndo->ndo_sa_list_head == NULL) {
if (ndo->ndo_espsecret)
esp_print_decodesecret(ndo);
}
#endif
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
if ((const struct isakmp *)ep < p + 1) {
ND_PRINT((ndo,"[|isakmp]"));
return;
}
UNALIGNED_MEMCPY(&base, p, sizeof(base));
ND_PRINT((ndo,"isakmp"));
major = (base.vers & ISAKMP_VERS_MAJOR)
>> ISAKMP_VERS_MAJOR_SHIFT;
minor = (base.vers & ISAKMP_VERS_MINOR)
>> ISAKMP_VERS_MINOR_SHIFT;
if (ndo->ndo_vflag) {
ND_PRINT((ndo," %d.%d", major, minor));
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," msgid "));
hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid));
}
if (1 < ndo->ndo_vflag) {
ND_PRINT((ndo," cookie "));
hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck));
ND_PRINT((ndo,"->"));
hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck));
}
ND_PRINT((ndo,":"));
switch(major) {
case IKEv1_MAJOR_VERSION:
ikev1_print(ndo, bp, length, bp2, &base);
break;
case IKEv2_MAJOR_VERSION:
ikev2_print(ndo, bp, length, bp2, &base);
break;
}
}
void
isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2663_0 |
crossvul-cpp_data_bad_2663_0 | /*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* The functions from print-esp.c used in this file are only defined when both
* OpenSSL and evp.h are detected. Employ the same preprocessor device here.
*/
#ifndef HAVE_OPENSSL_EVP_H
#undef HAVE_LIBCRYPTO
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
/* refer to RFC 2408 */
typedef u_char cookie_t[8];
typedef u_char msgid_t[4];
#define PORT_ISAKMP 500
/* 3.1 ISAKMP Header Format (IKEv1 and IKEv2)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Initiator !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Responder !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Message ID !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp {
cookie_t i_ck; /* Initiator Cookie */
cookie_t r_ck; /* Responder Cookie */
uint8_t np; /* Next Payload Type */
uint8_t vers;
#define ISAKMP_VERS_MAJOR 0xf0
#define ISAKMP_VERS_MAJOR_SHIFT 4
#define ISAKMP_VERS_MINOR 0x0f
#define ISAKMP_VERS_MINOR_SHIFT 0
uint8_t etype; /* Exchange Type */
uint8_t flags; /* Flags */
msgid_t msgid;
uint32_t len; /* Length */
};
/* Next Payload Type */
#define ISAKMP_NPTYPE_NONE 0 /* NONE*/
#define ISAKMP_NPTYPE_SA 1 /* Security Association */
#define ISAKMP_NPTYPE_P 2 /* Proposal */
#define ISAKMP_NPTYPE_T 3 /* Transform */
#define ISAKMP_NPTYPE_KE 4 /* Key Exchange */
#define ISAKMP_NPTYPE_ID 5 /* Identification */
#define ISAKMP_NPTYPE_CERT 6 /* Certificate */
#define ISAKMP_NPTYPE_CR 7 /* Certificate Request */
#define ISAKMP_NPTYPE_HASH 8 /* Hash */
#define ISAKMP_NPTYPE_SIG 9 /* Signature */
#define ISAKMP_NPTYPE_NONCE 10 /* Nonce */
#define ISAKMP_NPTYPE_N 11 /* Notification */
#define ISAKMP_NPTYPE_D 12 /* Delete */
#define ISAKMP_NPTYPE_VID 13 /* Vendor ID */
#define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */
#define IKEv1_MAJOR_VERSION 1
#define IKEv1_MINOR_VERSION 0
#define IKEv2_MAJOR_VERSION 2
#define IKEv2_MINOR_VERSION 0
/* Flags */
#define ISAKMP_FLAG_E 0x01 /* Encryption Bit */
#define ISAKMP_FLAG_C 0x02 /* Commit Bit */
#define ISAKMP_FLAG_extra 0x04
/* IKEv2 */
#define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */
#define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */
#define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */
/* 3.2 Payload Generic Header
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! RESERVED ! Payload Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_gen {
uint8_t np; /* Next Payload */
uint8_t critical; /* bit 7 - critical, rest is RESERVED */
uint16_t len; /* Payload Length */
};
/* 3.3 Data Attributes
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
!A! Attribute Type ! AF=0 Attribute Length !
!F! ! AF=1 Attribute Value !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. AF=0 Attribute Value .
. AF=1 Not Transmitted .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_data {
uint16_t type; /* defined by DOI-spec, and Attribute Format */
uint16_t lorv; /* if f equal 1, Attribute Length */
/* if f equal 0, Attribute Value */
/* if f equal 1, Attribute Value */
};
/* 3.4 Security Association Payload */
/* MAY NOT be used, because of being defined in ipsec-doi. */
/*
If the current payload is the last in the message,
then the value of the next payload field will be 0.
This field MUST NOT contain the
values for the Proposal or Transform payloads as they are considered
part of the security association negotiation. For example, this
field would contain the value "10" (Nonce payload) in the first
message of a Base Exchange (see Section 4.4) and the value "0" in the
first message of an Identity Protect Exchange (see Section 4.5).
*/
struct ikev1_pl_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
/* 3.5 Proposal Payload */
/*
The value of the next payload field MUST only contain the value "2"
or "0". If there are additional Proposal payloads in the message,
then this field will be 2. If the current Proposal payload is the
last within the security association proposal, then this field will
be 0.
*/
struct ikev1_pl_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
/* SPI */
};
/* 3.6 Transform Payload */
/*
The value of the next payload field MUST only contain the value "3"
or "0". If there are additional Transform payloads in the proposal,
then this field will be 3. If the current Transform payload is the
last within the proposal, then this field will be 0.
*/
struct ikev1_pl_t {
struct isakmp_gen h;
uint8_t t_no; /* Transform # */
uint8_t t_id; /* Transform-Id */
uint16_t reserved; /* RESERVED2 */
/* SA Attributes */
};
/* 3.7 Key Exchange Payload */
struct ikev1_pl_ke {
struct isakmp_gen h;
/* Key Exchange Data */
};
/* 3.8 Identification Payload */
/* MUST NOT to be used, because of being defined in ipsec-doi. */
struct ikev1_pl_id {
struct isakmp_gen h;
union {
uint8_t id_type; /* ID Type */
uint32_t doi_data; /* DOI Specific ID Data */
} d;
/* Identification Data */
};
/* 3.9 Certificate Payload */
struct ikev1_pl_cert {
struct isakmp_gen h;
uint8_t encode; /* Cert Encoding */
char cert; /* Certificate Data */
/*
This field indicates the type of
certificate or certificate-related information contained in the
Certificate Data field.
*/
};
/* 3.10 Certificate Request Payload */
struct ikev1_pl_cr {
struct isakmp_gen h;
uint8_t num_cert; /* # Cert. Types */
/*
Certificate Types (variable length)
-- Contains a list of the types of certificates requested,
sorted in order of preference. Each individual certificate
type is 1 octet. This field is NOT requiredo
*/
/* # Certificate Authorities (1 octet) */
/* Certificate Authorities (variable length) */
};
/* 3.11 Hash Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_hash {
struct isakmp_gen h;
/* Hash Data */
};
/* 3.12 Signature Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_sig {
struct isakmp_gen h;
/* Signature Data */
};
/* 3.13 Nonce Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_nonce {
struct isakmp_gen h;
/* Nonce Data */
};
/* 3.14 Notification Payload */
struct ikev1_pl_n {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
/* SPI */
/* Notification Data */
};
/* 3.14.1 Notify Message Types */
/* NOTIFY MESSAGES - ERROR TYPES */
#define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1
#define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2
#define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3
#define ISAKMP_NTYPE_INVALID_COOKIE 4
#define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5
#define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6
#define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7
#define ISAKMP_NTYPE_INVALID_FLAGS 8
#define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9
#define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10
#define ISAKMP_NTYPE_INVALID_SPI 11
#define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12
#define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13
#define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14
#define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15
#define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16
#define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17
#define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18
#define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19
#define ISAKMP_NTYPE_INVALID_CERTIFICATE 20
#define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21
#define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22
#define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23
#define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24
#define ISAKMP_NTYPE_INVALID_SIGNATURE 25
#define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26
/* 3.15 Delete Payload */
struct ikev1_pl_d {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-Id */
uint8_t spi_size; /* SPI Size */
uint16_t num_spi; /* # of SPIs */
/* SPI(es) */
};
struct ikev1_ph1tab {
struct ikev1_ph1 *head;
struct ikev1_ph1 *tail;
int len;
};
struct isakmp_ph2tab {
struct ikev1_ph2 *head;
struct ikev1_ph2 *tail;
int len;
};
/* IKEv2 (RFC4306) */
/* 3.3 Security Association Payload -- generic header */
/* 3.3.1. Proposal Substructure */
struct ikev2_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
};
/* 3.3.2. Transform Substructure */
struct ikev2_t {
struct isakmp_gen h;
uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/
uint8_t res2; /* reserved byte */
uint16_t t_id; /* Transform ID */
};
enum ikev2_t_type {
IV2_T_ENCR = 1,
IV2_T_PRF = 2,
IV2_T_INTEG= 3,
IV2_T_DH = 4,
IV2_T_ESN = 5
};
/* 3.4. Key Exchange Payload */
struct ikev2_ke {
struct isakmp_gen h;
uint16_t ke_group;
uint16_t ke_res1;
/* KE data */
};
/* 3.5. Identification Payloads */
enum ikev2_id_type {
ID_IPV4_ADDR=1,
ID_FQDN=2,
ID_RFC822_ADDR=3,
ID_IPV6_ADDR=5,
ID_DER_ASN1_DN=9,
ID_DER_ASN1_GN=10,
ID_KEY_ID=11
};
struct ikev2_id {
struct isakmp_gen h;
uint8_t type; /* ID type */
uint8_t res1;
uint16_t res2;
/* SPI */
/* Notification Data */
};
/* 3.10 Notification Payload */
struct ikev2_n {
struct isakmp_gen h;
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
};
enum ikev2_n_type {
IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1,
IV2_NOTIFY_INVALID_IKE_SPI = 4,
IV2_NOTIFY_INVALID_MAJOR_VERSION = 5,
IV2_NOTIFY_INVALID_SYNTAX = 7,
IV2_NOTIFY_INVALID_MESSAGE_ID = 9,
IV2_NOTIFY_INVALID_SPI =11,
IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14,
IV2_NOTIFY_INVALID_KE_PAYLOAD =17,
IV2_NOTIFY_AUTHENTICATION_FAILED =24,
IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34,
IV2_NOTIFY_NO_ADDITIONAL_SAS =35,
IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36,
IV2_NOTIFY_FAILED_CP_REQUIRED =37,
IV2_NOTIFY_INVALID_SELECTORS =39,
IV2_NOTIFY_INITIAL_CONTACT =16384,
IV2_NOTIFY_SET_WINDOW_SIZE =16385,
IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386,
IV2_NOTIFY_IPCOMP_SUPPORTED =16387,
IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388,
IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389,
IV2_NOTIFY_COOKIE =16390,
IV2_NOTIFY_USE_TRANSPORT_MODE =16391,
IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392,
IV2_NOTIFY_REKEY_SA =16393,
IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394,
IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395
};
struct notify_messages {
uint16_t type;
char *msg;
};
/* 3.8 Notification Payload */
struct ikev2_auth {
struct isakmp_gen h;
uint8_t auth_method; /* Protocol-ID */
uint8_t reserved[3];
/* authentication data */
};
enum ikev2_auth_type {
IV2_RSA_SIG = 1,
IV2_SHARED = 2,
IV2_DSS_SIG = 3
};
/* refer to RFC 2409 */
#if 0
/* isakmp sa structure */
struct oakley_sa {
uint8_t proto_id; /* OAKLEY */
vchar_t *spi; /* spi */
uint8_t dhgrp; /* DH; group */
uint8_t auth_t; /* method of authentication */
uint8_t prf_t; /* type of prf */
uint8_t hash_t; /* type of hash */
uint8_t enc_t; /* type of cipher */
uint8_t life_t; /* type of duration of lifetime */
uint32_t ldur; /* life duration */
};
#endif
/* refer to RFC 2407 */
#define IPSEC_DOI 1
/* 4.2 IPSEC Situation Definition */
#define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001
#define IPSECDOI_SIT_SECRECY 0x00000002
#define IPSECDOI_SIT_INTEGRITY 0x00000004
/* 4.4.1 IPSEC Security Protocol Identifiers */
/* 4.4.2 IPSEC ISAKMP Transform Values */
#define IPSECDOI_PROTO_ISAKMP 1
#define IPSECDOI_KEY_IKE 1
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_AH 2
/* 4.4.3 IPSEC AH Transform Values */
#define IPSECDOI_AH_MD5 2
#define IPSECDOI_AH_SHA 3
#define IPSECDOI_AH_DES 4
#define IPSECDOI_AH_SHA2_256 5
#define IPSECDOI_AH_SHA2_384 6
#define IPSECDOI_AH_SHA2_512 7
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_ESP 3
/* 4.4.4 IPSEC ESP Transform Identifiers */
#define IPSECDOI_ESP_DES_IV64 1
#define IPSECDOI_ESP_DES 2
#define IPSECDOI_ESP_3DES 3
#define IPSECDOI_ESP_RC5 4
#define IPSECDOI_ESP_IDEA 5
#define IPSECDOI_ESP_CAST 6
#define IPSECDOI_ESP_BLOWFISH 7
#define IPSECDOI_ESP_3IDEA 8
#define IPSECDOI_ESP_DES_IV32 9
#define IPSECDOI_ESP_RC4 10
#define IPSECDOI_ESP_NULL 11
#define IPSECDOI_ESP_RIJNDAEL 12
#define IPSECDOI_ESP_AES 12
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPCOMP 4
/* 4.4.5 IPSEC IPCOMP Transform Identifiers */
#define IPSECDOI_IPCOMP_OUI 1
#define IPSECDOI_IPCOMP_DEFLATE 2
#define IPSECDOI_IPCOMP_LZS 3
/* 4.5 IPSEC Security Association Attributes */
#define IPSECDOI_ATTR_SA_LTYPE 1 /* B */
#define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1
#define IPSECDOI_ATTR_SA_LTYPE_SEC 1
#define IPSECDOI_ATTR_SA_LTYPE_KB 2
#define IPSECDOI_ATTR_SA_LDUR 2 /* V */
#define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */
#define IPSECDOI_ATTR_GRP_DESC 3 /* B */
#define IPSECDOI_ATTR_ENC_MODE 4 /* B */
/* default value: host dependent */
#define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1
#define IPSECDOI_ATTR_ENC_MODE_TRNS 2
#define IPSECDOI_ATTR_AUTH 5 /* B */
/* 0 means not to use authentication. */
#define IPSECDOI_ATTR_AUTH_HMAC_MD5 1
#define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2
#define IPSECDOI_ATTR_AUTH_DES_MAC 3
#define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/
/*
* When negotiating ESP without authentication, the Auth
* Algorithm attribute MUST NOT be included in the proposal.
* When negotiating ESP without confidentiality, the Auth
* Algorithm attribute MUST be included in the proposal and
* the ESP transform ID must be ESP_NULL.
*/
#define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */
#define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */
#define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */
#define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */
/* 4.6.1 Security Association Payload */
struct ipsecdoi_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
struct ipsecdoi_secrecy_h {
uint16_t len;
uint16_t reserved;
};
/* 4.6.2.1 Identification Type Values */
struct ipsecdoi_id {
struct isakmp_gen h;
uint8_t type; /* ID Type */
uint8_t proto_id; /* Protocol ID */
uint16_t port; /* Port */
/* Identification Data */
};
#define IPSECDOI_ID_IPV4_ADDR 1
#define IPSECDOI_ID_FQDN 2
#define IPSECDOI_ID_USER_FQDN 3
#define IPSECDOI_ID_IPV4_ADDR_SUBNET 4
#define IPSECDOI_ID_IPV6_ADDR 5
#define IPSECDOI_ID_IPV6_ADDR_SUBNET 6
#define IPSECDOI_ID_IPV4_ADDR_RANGE 7
#define IPSECDOI_ID_IPV6_ADDR_RANGE 8
#define IPSECDOI_ID_DER_ASN1_DN 9
#define IPSECDOI_ID_DER_ASN1_GN 10
#define IPSECDOI_ID_KEY_ID 11
/* 4.6.3 IPSEC DOI Notify Message Types */
/* Notify Messages - Status Types */
#define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576
#define IPSECDOI_NTYPE_REPLAY_STATUS 24577
#define IPSECDOI_NTYPE_INITIAL_CONTACT 24578
#define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \
netdissect_options *ndo, u_char tpay, \
const struct isakmp_gen *ext, \
u_int item_len, \
const u_char *end_pointer, \
uint32_t phase,\
uint32_t doi0, \
uint32_t proto0, int depth)
DECLARE_PRINTER(v1_sa);
DECLARE_PRINTER(v1_p);
DECLARE_PRINTER(v1_t);
DECLARE_PRINTER(v1_ke);
DECLARE_PRINTER(v1_id);
DECLARE_PRINTER(v1_cert);
DECLARE_PRINTER(v1_cr);
DECLARE_PRINTER(v1_sig);
DECLARE_PRINTER(v1_hash);
DECLARE_PRINTER(v1_nonce);
DECLARE_PRINTER(v1_n);
DECLARE_PRINTER(v1_d);
DECLARE_PRINTER(v1_vid);
DECLARE_PRINTER(v2_sa);
DECLARE_PRINTER(v2_ke);
DECLARE_PRINTER(v2_ID);
DECLARE_PRINTER(v2_cert);
DECLARE_PRINTER(v2_cr);
DECLARE_PRINTER(v2_auth);
DECLARE_PRINTER(v2_nonce);
DECLARE_PRINTER(v2_n);
DECLARE_PRINTER(v2_d);
DECLARE_PRINTER(v2_vid);
DECLARE_PRINTER(v2_TS);
DECLARE_PRINTER(v2_cp);
DECLARE_PRINTER(v2_eap);
static const u_char *ikev2_e_print(netdissect_options *ndo,
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth);
static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext,
const u_char *ep, uint32_t phase,
uint32_t doi, uint32_t proto,
int depth);
static char *numstr(int);
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base);
#define MAXINITIATORS 20
static int ninitiator = 0;
union inaddr_u {
struct in_addr in4;
struct in6_addr in6;
};
static struct {
cookie_t initiator;
u_int version;
union inaddr_u iaddr;
union inaddr_u raddr;
} cookiecache[MAXINITIATORS];
/* protocol id */
static const char *protoidstr[] = {
NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp",
};
/* isakmp->np */
static const char *npstr[] = {
"none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */
"sig", "nonce", "n", "d", "vid", /* 9 - 13 */
"pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */
"pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */
"pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */
"pay29", "pay30", "pay31", "pay32", /* 29- 32 */
"v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */
"v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */
"v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */
"v2eap", /* 48 */
};
/* isakmp->np */
static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth) = {
NULL,
ikev1_sa_print,
ikev1_p_print,
ikev1_t_print,
ikev1_ke_print,
ikev1_id_print,
ikev1_cert_print,
ikev1_cr_print,
ikev1_hash_print,
ikev1_sig_print,
ikev1_nonce_print,
ikev1_n_print,
ikev1_d_print,
ikev1_vid_print, /* 13 */
NULL, NULL, NULL, NULL, NULL, /* 14- 18 */
NULL, NULL, NULL, NULL, NULL, /* 19- 23 */
NULL, NULL, NULL, NULL, NULL, /* 24- 28 */
NULL, NULL, NULL, NULL, /* 29- 32 */
ikev2_sa_print, /* 33 */
ikev2_ke_print, /* 34 */
ikev2_ID_print, /* 35 */
ikev2_ID_print, /* 36 */
ikev2_cert_print, /* 37 */
ikev2_cr_print, /* 38 */
ikev2_auth_print, /* 39 */
ikev2_nonce_print, /* 40 */
ikev2_n_print, /* 41 */
ikev2_d_print, /* 42 */
ikev2_vid_print, /* 43 */
ikev2_TS_print, /* 44 */
ikev2_TS_print, /* 45 */
NULL, /* ikev2_e_print,*/ /* 46 - special */
ikev2_cp_print, /* 47 */
ikev2_eap_print, /* 48 */
};
/* isakmp->etype */
static const char *etypestr[] = {
/* IKEv1 exchange types */
"none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */
"oakley-quick", "oakley-newgroup", /* 32-33 */
/* IKEv2 exchange types */
"ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
#define PROTOIDSTR(x) STR_OR_ID(x, protoidstr)
#define NPSTR(x) STR_OR_ID(x, npstr)
#define ETYPESTR(x) STR_OR_ID(x, etypestr)
#define CHECKLEN(p, np) \
if (ep < (const u_char *)(p)) { \
ND_PRINT((ndo," [|%s]", NPSTR(np))); \
goto done; \
}
#define NPFUNC(x) \
(((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \
? npfunc[(x)] : NULL)
static int
iszero(const u_char *p, size_t l)
{
while (l--) {
if (*p++)
return 0;
}
return 1;
}
/* find cookie from initiator cache */
static int
cookie_find(cookie_t *in)
{
int i;
for (i = 0; i < MAXINITIATORS; i++) {
if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0)
return i;
}
return -1;
}
/* record initiator */
static void
cookie_record(cookie_t *in, const u_char *bp2)
{
int i;
const struct ip *ip;
const struct ip6_hdr *ip6;
i = cookie_find(in);
if (0 <= i) {
ninitiator = (i + 1) % MAXINITIATORS;
return;
}
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
cookiecache[ninitiator].version = 4;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp2;
cookiecache[ninitiator].version = 6;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr));
break;
default:
return;
}
UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in));
ninitiator = (ninitiator + 1) % MAXINITIATORS;
}
#define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1)
#define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0)
static int
cookie_sidecheck(int i, const u_char *bp2, int initiator)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
if (cookiecache[i].version != 4)
return 0;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0)
return 1;
}
break;
case 6:
if (cookiecache[i].version != 6)
return 0;
ip6 = (const struct ip6_hdr *)bp2;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
}
break;
default:
break;
}
return 0;
}
static void
hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
const uint8_t *p;
size_t i;
p = loc;
for (i = 0; i < len; i++)
ND_PRINT((ndo,"%02x", p[i] & 0xff));
}
static int
rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
ND_TCHECK2(*loc, len);
hexprint(ndo, loc, len);
return 1;
trunc:
return 0;
}
/*
* returns false if we run out of data buffer
*/
static int ike_show_somedata(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
/* there is too much data, just show some of it */
const u_char *end = ep - 20;
int elen = 20;
int len = ep - cp;
if(len > 10) {
len = 10;
}
/* really shouldn't happen because of above */
if(end < cp + len) {
end = cp+len;
elen = ep - end;
}
ND_PRINT((ndo," data=("));
if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc;
ND_PRINT((ndo, "..."));
if(elen) {
if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc;
}
ND_PRINT((ndo,")"));
return 1;
trunc:
return 0;
}
struct attrmap {
const char *type;
u_int nvalue;
const char *value[30]; /*XXX*/
};
static const u_char *
ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
static const u_char *
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep)
{
int totlen;
uint32_t t;
if (p[0] & 0x80)
totlen = 4;
else
totlen = 4 + EXTRACT_16BITS(&p[2]);
if (ep < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep + 1;
}
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
rawprint(ndo, (const uint8_t *)&p[2], 2);
} else {
ND_PRINT((ndo,"len=%d value=", EXTRACT_16BITS(&p[2])));
rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2]));
}
ND_PRINT((ndo,")"));
return p + totlen;
}
static const u_char *
ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0, int depth)
{
const struct ikev1_pl_sa *p;
struct ikev1_pl_sa sa;
uint32_t doi, sit, ident;
const u_char *cp, *np;
int t;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA)));
p = (const struct ikev1_pl_sa *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&sa, ext, sizeof(sa));
doi = ntohl(sa.doi);
sit = ntohl(sa.sit);
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit)));
return (const u_char *)(p + 1);
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," situation="));
t = 0;
if (sit & 0x01) {
ND_PRINT((ndo,"identity"));
t++;
}
if (sit & 0x02) {
ND_PRINT((ndo,"%ssecrecy", t ? "+" : ""));
t++;
}
if (sit & 0x04)
ND_PRINT((ndo,"%sintegrity", t ? "+" : ""));
np = (const u_char *)ext + sizeof(sa);
if (sit != 0x01) {
ND_TCHECK2(*(ext + 1), sizeof(ident));
UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident));
ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident)));
np += sizeof(ident);
}
ext = (const struct isakmp_gen *)np;
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0,
depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA)));
return NULL;
}
static const u_char *
ikev1_p_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_p *p;
struct ikev1_pl_p prop;
const u_char *cp;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P)));
p = (const struct ikev1_pl_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ND_PRINT((ndo," #%d protoid=%s transform=%d",
prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t));
if (prop.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size))
goto trunc;
}
ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size);
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0,
prop.prot_id, depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const char *ikev1_p_map[] = {
NULL, "ike",
};
static const char *ikev2_t_type_map[]={
NULL, "encr", "prf", "integ", "dh", "esn"
};
static const char *ah_p_map[] = {
NULL, "(reserved)", "md5", "sha", "1des",
"sha2-256", "sha2-384", "sha2-512",
};
static const char *prf_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "hmac-tiger",
"aes128_xcbc"
};
static const char *integ_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "dec-mac",
"kpdk-md5", "aes-xcbc"
};
static const char *esn_p_map[] = {
"no-esn", "esn"
};
static const char *dh_p_map[] = {
NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
};
static const char *esp_p_map[] = {
NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast",
"blowfish", "3idea", "1des-iv32", "rc4", "null", "aes"
};
static const char *ipcomp_p_map[] = {
NULL, "oui", "deflate", "lzs",
};
static const struct attrmap ipsec_t_map[] = {
{ NULL, 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "life", 0, { NULL } },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "enc mode", 3, { NULL, "tunnel", "transport", }, },
{ "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, },
{ "keylen", 0, { NULL } },
{ "rounds", 0, { NULL } },
{ "dictsize", 0, { NULL } },
{ "privalg", 0, { NULL } },
};
static const struct attrmap encr_t_map[] = {
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/
{ "keylen", 14, { NULL }},
};
static const struct attrmap oakley_t_map[] = {
{ NULL, 0, { NULL } },
{ "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5",
"3des", "cast", "aes", }, },
{ "hash", 7, { NULL, "md5", "sha1", "tiger",
"sha2-256", "sha2-384", "sha2-512", }, },
{ "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc",
"rsa enc revised", }, },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, },
{ "group prime", 0, { NULL } },
{ "group gen1", 0, { NULL } },
{ "group gen2", 0, { NULL } },
{ "group curve A", 0, { NULL } },
{ "group curve B", 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "lifeduration", 0, { NULL } },
{ "prf", 0, { NULL } },
{ "keylen", 0, { NULL } },
{ "field", 0, { NULL } },
{ "order", 0, { NULL } },
};
static const u_char *
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
static const u_char *
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 20)
ND_PRINT((ndo," len=%d [bad: < 20]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
static const u_char *
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
static const u_char *
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
static const u_char *
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
static const u_char *
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
static const u_char *
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
static const u_char *
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
ND_PRINT((ndo," orig=("));
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp,
(ep < ep2) ? ep : ep2, map, nmap);
}
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
break;
case ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN:
if (ikev1_sub_print(ndo, ISAKMP_NPTYPE_SA,
(const struct isakmp_gen *)cp, ep, phase, doi, proto,
depth) == NULL)
return NULL;
break;
default:
/* NULL is dummy */
isakmp_print(ndo, cp,
item_len - sizeof(*p) - n.spi_size,
NULL);
}
ND_PRINT((ndo,")"));
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev1_d_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_d *p;
struct ikev1_pl_d d;
const uint8_t *q;
uint32_t doi;
uint32_t proto;
int i;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D)));
p = (const struct ikev1_pl_d *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&d, ext, sizeof(d));
doi = ntohl(d.doi);
proto = d.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%u", doi));
ND_PRINT((ndo," proto=%u", proto));
} else {
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
}
ND_PRINT((ndo," spilen=%u", d.spi_size));
ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi)));
ND_PRINT((ndo," spi="));
q = (const uint8_t *)(p + 1);
for (i = 0; i < ntohs(d.num_spi); i++) {
if (i != 0)
ND_PRINT((ndo,","));
if (!rawprint(ndo, (const uint8_t *)q, d.spi_size))
goto trunc;
q += d.spi_size;
}
return q;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D)));
return NULL;
}
static const u_char *
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
/************************************************************/
/* */
/* IKE v2 - rfc4306 - dissector */
/* */
/************************************************************/
static void
ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical)
{
ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : ""));
}
static const u_char *
ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_t_print(netdissect_options *ndo, int tcount,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep)
{
const struct ikev2_t *p;
struct ikev2_t t;
uint16_t t_id;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
p = (const struct ikev2_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical);
t_id = ntohs(t.t_id);
map = NULL;
nmap = 0;
switch (t.t_type) {
case IV2_T_ENCR:
idstr = STR_OR_ID(t_id, esp_p_map);
map = encr_t_map;
nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]);
break;
case IV2_T_PRF:
idstr = STR_OR_ID(t_id, prf_p_map);
break;
case IV2_T_INTEG:
idstr = STR_OR_ID(t_id, integ_p_map);
break;
case IV2_T_DH:
idstr = STR_OR_ID(t_id, dh_p_map);
break;
case IV2_T_ESN:
idstr = STR_OR_ID(t_id, esn_p_map);
break;
default:
idstr = NULL;
break;
}
if (idstr)
ND_PRINT((ndo," #%u type=%s id=%s ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
idstr));
else
ND_PRINT((ndo," #%u type=%s id=%u ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2,
map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2);
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const u_char *
ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_ke ke;
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));
if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
goto trunc;
}
return (const u_char *)ext + ntohs(ke.h.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cert_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_cr_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
ND_PRINT((ndo," len=%d method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (1 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < len) {
if(!ike_show_somedata(ndo, authdata, ep)) goto trunc;
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_nonce_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, "nonce", e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," nonce=("));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < ntohs(e.len)) {
if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
/* notify payloads */
static const u_char *
ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showdata, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showdata = 0;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
showdata= 0;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if(3 < ndo->ndo_vflag) {
showdata = 1;
}
if ((showdata || (showsomedata && ep-cp < 30)) && cp < ep) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if(showsomedata && cp < ep) {
if(!ike_show_somedata(ndo, cp, ep)) goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev2_d_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_e_print(netdissect_options *ndo,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t phase,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t doi,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t proto,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
int depth)
{
struct isakmp_gen e;
const u_char *dat;
volatile int dlen;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
dlen = ntohs(e.len)-4;
ND_PRINT((ndo," len=%d", dlen));
if (2 < ndo->ndo_vflag && 4 < dlen) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen))
goto trunc;
}
dat = (const u_char *)(ext+1);
ND_TCHECK2(*dat, dlen);
#ifdef HAVE_LIBCRYPTO
/* try to decypt it! */
if(esp_print_decrypt_buffer_by_ikev2(ndo,
base->flags & ISAKMP_FLAG_I,
base->i_ck, base->r_ck,
dat, dat+dlen)) {
ext = (const struct isakmp_gen *)ndo->ndo_packetp;
/* got it decrypted, print stuff inside. */
ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend,
phase, doi, proto, depth+1);
}
#endif
/* always return NULL, because E must be at end, and NP refers
* to what was inside.
*/
return NULL;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cp_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_eap_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ike_sub0_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "#%d", x);
return buf;
}
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int i;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo," phase %d", phase));
else
ND_PRINT((ndo," phase %d/others", phase));
i = cookie_find(&base->i_ck);
if (i < 0) {
if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) {
/* the first packet */
ND_PRINT((ndo," I"));
if (bp2)
cookie_record(&base->i_ck, bp2);
} else
ND_PRINT((ndo," ?"));
} else {
if (bp2 && cookie_isinitiator(i, bp2))
ND_PRINT((ndo," I"));
else if (bp2 && cookie_isresponder(i, bp2))
ND_PRINT((ndo," R"));
else
ND_PRINT((ndo," ?"));
}
ND_PRINT((ndo," %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "",
base->flags & ISAKMP_FLAG_C ? "C" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo,":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np);
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
static const u_char *
ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base,
u_char np,
const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (np == ISAKMP_NPTYPE_v2E) {
cp = ikev2_e_print(ndo, base, np, ext, item_len,
ep, phase, doi, proto, depth);
} else if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len,
ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static void
ikev2_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2 _U_, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo, " parent_sa"));
else
ND_PRINT((ndo, " child_sa "));
ND_PRINT((ndo, " %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo, "[%s%s%s]",
base->flags & ISAKMP_FLAG_I ? "I" : "",
base->flags & ISAKMP_FLAG_V ? "V" : "",
base->flags & ISAKMP_FLAG_R ? "R" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo, ":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np)
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
void
isakmp_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
const struct isakmp *p;
struct isakmp base;
const u_char *ep;
int major, minor;
#ifdef HAVE_LIBCRYPTO
/* initialize SAs */
if (ndo->ndo_sa_list_head == NULL) {
if (ndo->ndo_espsecret)
esp_print_decodesecret(ndo);
}
#endif
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
if ((const struct isakmp *)ep < p + 1) {
ND_PRINT((ndo,"[|isakmp]"));
return;
}
UNALIGNED_MEMCPY(&base, p, sizeof(base));
ND_PRINT((ndo,"isakmp"));
major = (base.vers & ISAKMP_VERS_MAJOR)
>> ISAKMP_VERS_MAJOR_SHIFT;
minor = (base.vers & ISAKMP_VERS_MINOR)
>> ISAKMP_VERS_MINOR_SHIFT;
if (ndo->ndo_vflag) {
ND_PRINT((ndo," %d.%d", major, minor));
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," msgid "));
hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid));
}
if (1 < ndo->ndo_vflag) {
ND_PRINT((ndo," cookie "));
hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck));
ND_PRINT((ndo,"->"));
hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck));
}
ND_PRINT((ndo,":"));
switch(major) {
case IKEv1_MAJOR_VERSION:
ikev1_print(ndo, bp, length, bp2, &base);
break;
case IKEv2_MAJOR_VERSION:
ikev2_print(ndo, bp, length, bp2, &base);
break;
}
}
void
isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2663_0 |
crossvul-cpp_data_bad_2662_0 | /*
* Copyright (c) 2015 The TCPDUMP 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.
*
* 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.
*
* Initial contribution by Andrew Darqui (andrew.darqui@gmail.com).
*/
/* \summary: REdis Serialization Protocol (RESP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include <limits.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include "extract.h"
static const char tstr[] = " [|RESP]";
/*
* For information regarding RESP, see: http://redis.io/topics/protocol
*/
#define RESP_SIMPLE_STRING '+'
#define RESP_ERROR '-'
#define RESP_INTEGER ':'
#define RESP_BULK_STRING '$'
#define RESP_ARRAY '*'
#define resp_print_empty(ndo) ND_PRINT((ndo, " empty"))
#define resp_print_null(ndo) ND_PRINT((ndo, " null"))
#define resp_print_length_too_large(ndo) ND_PRINT((ndo, " length too large"))
#define resp_print_length_negative(ndo) ND_PRINT((ndo, " length negative and not -1"))
#define resp_print_invalid(ndo) ND_PRINT((ndo, " invalid"))
void resp_print(netdissect_options *, const u_char *, u_int);
static int resp_parse(netdissect_options *, register const u_char *, int);
static int resp_print_string_error_integer(netdissect_options *, register const u_char *, int);
static int resp_print_simple_string(netdissect_options *, register const u_char *, int);
static int resp_print_integer(netdissect_options *, register const u_char *, int);
static int resp_print_error(netdissect_options *, register const u_char *, int);
static int resp_print_bulk_string(netdissect_options *, register const u_char *, int);
static int resp_print_bulk_array(netdissect_options *, register const u_char *, int);
static int resp_print_inline(netdissect_options *, register const u_char *, int);
static int resp_get_length(netdissect_options *, register const u_char *, int, const u_char **);
#define LCHECK2(_tot_len, _len) \
{ \
if (_tot_len < _len) \
goto trunc; \
}
#define LCHECK(_tot_len) LCHECK2(_tot_len, 1)
/*
* FIND_CRLF:
* Attempts to move our 'ptr' forward until a \r\n is found,
* while also making sure we don't exceed the buffer '_len'
* or go past the end of the captured data.
* If we exceed or go past the end of the captured data,
* jump to trunc.
*/
#define FIND_CRLF(_ptr, _len) \
for (;;) { \
LCHECK2(_len, 2); \
ND_TCHECK2(*_ptr, 2); \
if (*_ptr == '\r' && *(_ptr+1) == '\n') \
break; \
_ptr++; \
_len--; \
}
/*
* CONSUME_CRLF
* Consume a CRLF that we've just found.
*/
#define CONSUME_CRLF(_ptr, _len) \
_ptr += 2; \
_len -= 2;
/*
* FIND_CR_OR_LF
* Attempts to move our '_ptr' forward until a \r or \n is found,
* while also making sure we don't exceed the buffer '_len'
* or go past the end of the captured data.
* If we exceed or go past the end of the captured data,
* jump to trunc.
*/
#define FIND_CR_OR_LF(_ptr, _len) \
for (;;) { \
LCHECK(_len); \
ND_TCHECK(*_ptr); \
if (*_ptr == '\r' || *_ptr == '\n') \
break; \
_ptr++; \
_len--; \
}
/*
* CONSUME_CR_OR_LF
* Consume all consecutive \r and \n bytes.
* If we exceed '_len' or go past the end of the captured data,
* jump to trunc.
*/
#define CONSUME_CR_OR_LF(_ptr, _len) \
{ \
int _found_cr_or_lf = 0; \
for (;;) { \
/* \
* Have we hit the end of data? \
*/ \
if (_len == 0 || !ND_TTEST(*_ptr)) { \
/* \
* Yes. Have we seen a \r \
* or \n? \
*/ \
if (_found_cr_or_lf) { \
/* \
* Yes. Just stop. \
*/ \
break; \
} \
/* \
* No. We ran out of packet. \
*/ \
goto trunc; \
} \
if (*_ptr != '\r' && *_ptr != '\n') \
break; \
_found_cr_or_lf = 1; \
_ptr++; \
_len--; \
} \
}
/*
* SKIP_OPCODE
* Skip over the opcode character.
* The opcode has already been fetched, so we know it's there, and don't
* need to do any checks.
*/
#define SKIP_OPCODE(_ptr, _tot_len) \
_ptr++; \
_tot_len--;
/*
* GET_LENGTH
* Get a bulk string or array length.
*/
#define GET_LENGTH(_ndo, _tot_len, _ptr, _len) \
{ \
const u_char *_endp; \
_len = resp_get_length(_ndo, _ptr, _tot_len, &_endp); \
_tot_len -= (_endp - _ptr); \
_ptr = _endp; \
}
/*
* TEST_RET_LEN
* If ret_len is < 0, jump to the trunc tag which returns (-1)
* and 'bubbles up' to printing tstr. Otherwise, return ret_len.
*/
#define TEST_RET_LEN(rl) \
if (rl < 0) { goto trunc; } else { return rl; }
/*
* TEST_RET_LEN_NORETURN
* If ret_len is < 0, jump to the trunc tag which returns (-1)
* and 'bubbles up' to printing tstr. Otherwise, continue onward.
*/
#define TEST_RET_LEN_NORETURN(rl) \
if (rl < 0) { goto trunc; }
/*
* RESP_PRINT_SEGMENT
* Prints a segment in the form of: ' "<stuff>"\n"
* Assumes the data has already been verified as present.
*/
#define RESP_PRINT_SEGMENT(_ndo, _bp, _len) \
ND_PRINT((_ndo, " \"")); \
if (fn_printn(_ndo, _bp, _len, _ndo->ndo_snapend)) \
goto trunc; \
fn_print_char(_ndo, '"');
void
resp_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
int ret_len = 0, length_cur = length;
if(!bp || length <= 0)
return;
ND_PRINT((ndo, ": RESP"));
while (length_cur > 0) {
/*
* This block supports redis pipelining.
* For example, multiple operations can be pipelined within the same string:
* "*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n*2\r\n\$4\r\nINCR\r\n\$1\r\nz\r\n"
* or
* "PING\r\nPING\r\nPING\r\n"
* In order to handle this case, we must try and parse 'bp' until
* 'length' bytes have been processed or we reach a trunc condition.
*/
ret_len = resp_parse(ndo, bp, length_cur);
TEST_RET_LEN_NORETURN(ret_len);
bp += ret_len;
length_cur -= ret_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
resp_parse(netdissect_options *ndo, register const u_char *bp, int length)
{
u_char op;
int ret_len;
LCHECK2(length, 1);
ND_TCHECK(*bp);
op = *bp;
/* bp now points to the op, so these routines must skip it */
switch(op) {
case RESP_SIMPLE_STRING: ret_len = resp_print_simple_string(ndo, bp, length); break;
case RESP_INTEGER: ret_len = resp_print_integer(ndo, bp, length); break;
case RESP_ERROR: ret_len = resp_print_error(ndo, bp, length); break;
case RESP_BULK_STRING: ret_len = resp_print_bulk_string(ndo, bp, length); break;
case RESP_ARRAY: ret_len = resp_print_bulk_array(ndo, bp, length); break;
default: ret_len = resp_print_inline(ndo, bp, length); break;
}
/*
* This gives up with a "truncated" indicator for all errors,
* including invalid packet errors; that's what we want, as
* we have to give up on further parsing in that case.
*/
TEST_RET_LEN(ret_len);
trunc:
return (-1);
}
static int
resp_print_simple_string(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_integer(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_error(netdissect_options *ndo, register const u_char *bp, int length) {
return resp_print_string_error_integer(ndo, bp, length);
}
static int
resp_print_string_error_integer(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length, len, ret_len;
const u_char *bp_ptr;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
bp_ptr = bp;
/*
* bp now prints past the (+-;) opcode, so it's pointing to the first
* character of the string (which could be numeric).
* +OK\r\n
* -ERR ...\r\n
* :02912309\r\n
*
* Find the \r\n with FIND_CRLF().
*/
FIND_CRLF(bp_ptr, length_cur);
/*
* bp_ptr points to the \r\n, so bp_ptr - bp is the length of text
* preceding the \r\n. That includes the opcode, so don't print
* that.
*/
len = (bp_ptr - bp);
RESP_PRINT_SEGMENT(ndo, bp, len);
ret_len = 1 /*<opcode>*/ + len /*<string>*/ + 2 /*<CRLF>*/;
TEST_RET_LEN(ret_len);
trunc:
return (-1);
}
static int
resp_print_bulk_string(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length, string_len;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
/* <length>\r\n */
GET_LENGTH(ndo, length_cur, bp, string_len);
if (string_len >= 0) {
/* Byte string of length string_len, starting at bp */
if (string_len == 0)
resp_print_empty(ndo);
else {
LCHECK2(length_cur, string_len);
ND_TCHECK2(*bp, string_len);
RESP_PRINT_SEGMENT(ndo, bp, string_len);
bp += string_len;
length_cur -= string_len;
}
/*
* Find the \r\n at the end of the string and skip past it.
* XXX - report an error if the \r\n isn't immediately after
* the item?
*/
FIND_CRLF(bp, length_cur);
CONSUME_CRLF(bp, length_cur);
} else {
/* null, truncated, or invalid for some reason */
switch(string_len) {
case (-1): resp_print_null(ndo); break;
case (-2): goto trunc;
case (-3): resp_print_length_too_large(ndo); break;
case (-4): resp_print_length_negative(ndo); break;
default: resp_print_invalid(ndo); break;
}
}
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_print_bulk_array(netdissect_options *ndo, register const u_char *bp, int length) {
u_int length_cur = length;
int array_len, i, ret_len;
/* bp points to the op; skip it */
SKIP_OPCODE(bp, length_cur);
/* <array_length>\r\n */
GET_LENGTH(ndo, length_cur, bp, array_len);
if (array_len > 0) {
/* non empty array */
for (i = 0; i < array_len; i++) {
ret_len = resp_parse(ndo, bp, length_cur);
TEST_RET_LEN_NORETURN(ret_len);
bp += ret_len;
length_cur -= ret_len;
}
} else {
/* empty, null, truncated, or invalid */
switch(array_len) {
case 0: resp_print_empty(ndo); break;
case (-1): resp_print_null(ndo); break;
case (-2): goto trunc;
case (-3): resp_print_length_too_large(ndo); break;
case (-4): resp_print_length_negative(ndo); break;
default: resp_print_invalid(ndo); break;
}
}
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_print_inline(netdissect_options *ndo, register const u_char *bp, int length) {
int length_cur = length;
int len;
const u_char *bp_ptr;
/*
* Inline commands are simply 'strings' followed by \r or \n or both.
* Redis will do its best to split/parse these strings.
* This feature of redis is implemented to support the ability of
* command parsing from telnet/nc sessions etc.
*
* <string><\r||\n||\r\n...>
*/
/*
* Skip forward past any leading \r, \n, or \r\n.
*/
CONSUME_CR_OR_LF(bp, length_cur);
bp_ptr = bp;
/*
* Scan forward looking for \r or \n.
*/
FIND_CR_OR_LF(bp_ptr, length_cur);
/*
* Found it; bp_ptr points to the \r or \n, so bp_ptr - bp is the
* Length of the line text that preceeds it. Print it.
*/
len = (bp_ptr - bp);
RESP_PRINT_SEGMENT(ndo, bp, len);
/*
* Skip forward past the \r, \n, or \r\n.
*/
CONSUME_CR_OR_LF(bp_ptr, length_cur);
/*
* Return the number of bytes we processed.
*/
return (length - length_cur);
trunc:
return (-1);
}
static int
resp_get_length(netdissect_options *ndo, register const u_char *bp, int len, const u_char **endp)
{
int result;
u_char c;
int saw_digit;
int neg;
int too_large;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
too_large = 0;
neg = 0;
if (*bp == '-') {
neg = 1;
bp++;
len--;
}
result = 0;
saw_digit = 0;
for (;;) {
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
c = *bp;
if (!(c >= '0' && c <= '9')) {
if (!saw_digit)
goto invalid;
break;
}
c -= '0';
if (result > (INT_MAX / 10)) {
/* This will overflow an int when we multiply it by 10. */
too_large = 1;
} else {
result *= 10;
if (result == INT_MAX && c > (INT_MAX % 10)) {
/* This will overflow an int when we add c */
too_large = 1;
} else
result += c;
}
bp++;
len--;
saw_digit = 1;
}
if (!saw_digit)
goto invalid;
/*
* OK, the next thing should be \r\n.
*/
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\r')
goto invalid;
bp++;
len--;
if (len == 0)
goto trunc;
ND_TCHECK(*bp);
if (*bp != '\n')
goto invalid;
bp++;
len--;
*endp = bp;
if (neg) {
/* -1 means "null", anything else is invalid */
if (too_large || result != 1)
return (-4);
result = -1;
}
return (too_large ? -3 : result);
trunc:
return (-2);
invalid:
return (-5);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2662_0 |
crossvul-cpp_data_good_465_0 | /*
* TechnoTrend PVA (.pva) demuxer
* Copyright (c) 2007, 2008 Ivo van Poorten
*
* 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 "avformat.h"
#include "internal.h"
#include "mpeg.h"
#define PVA_MAX_PAYLOAD_LENGTH 0x17f8
#define PVA_VIDEO_PAYLOAD 0x01
#define PVA_AUDIO_PAYLOAD 0x02
#define PVA_MAGIC (('A' << 8) + 'V')
typedef struct PVAContext {
int continue_pes;
} PVAContext;
static int pva_check(const uint8_t *p) {
int length = AV_RB16(p + 6);
if (AV_RB16(p) != PVA_MAGIC || !p[2] || p[2] > 2 || p[4] != 0x55 ||
(p[5] & 0xe0) || length > PVA_MAX_PAYLOAD_LENGTH)
return -1;
return length + 8;
}
static int pva_probe(AVProbeData * pd) {
const unsigned char *buf = pd->buf;
int len = pva_check(buf);
if (len < 0)
return 0;
if (pd->buf_size >= len + 8 &&
pva_check(buf + len) >= 0)
return AVPROBE_SCORE_EXTENSION;
return AVPROBE_SCORE_MAX / 4;
}
static int pva_read_header(AVFormatContext *s) {
AVStream *st;
if (!(st = avformat_new_stream(s, NULL)))
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
st->codecpar->codec_id = AV_CODEC_ID_MPEG2VIDEO;
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(st, 32, 1, 90000);
av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
if (!(st = avformat_new_stream(s, NULL)))
return AVERROR(ENOMEM);
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = AV_CODEC_ID_MP2;
st->need_parsing = AVSTREAM_PARSE_FULL;
avpriv_set_pts_info(st, 33, 1, 90000);
av_add_index_entry(st, 0, 0, 0, 0, AVINDEX_KEYFRAME);
/* the parameters will be extracted from the compressed bitstream */
return 0;
}
#define pva_log if (read_packet) av_log
static int read_part_of_packet(AVFormatContext *s, int64_t *pts,
int *len, int *strid, int read_packet) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int syncword, streamid, reserved, flags, length, pts_flag;
int64_t pva_pts = AV_NOPTS_VALUE, startpos;
int ret;
recover:
startpos = avio_tell(pb);
syncword = avio_rb16(pb);
streamid = avio_r8(pb);
avio_r8(pb); /* counter not used */
reserved = avio_r8(pb);
flags = avio_r8(pb);
length = avio_rb16(pb);
pts_flag = flags & 0x10;
if (syncword != PVA_MAGIC) {
pva_log(s, AV_LOG_ERROR, "invalid syncword\n");
return AVERROR(EIO);
}
if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) {
pva_log(s, AV_LOG_ERROR, "invalid streamid\n");
return AVERROR(EIO);
}
if (reserved != 0x55) {
pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n");
}
if (length > PVA_MAX_PAYLOAD_LENGTH) {
pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length);
return AVERROR(EIO);
}
if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) {
pva_pts = avio_rb32(pb);
length -= 4;
} else if (streamid == PVA_AUDIO_PAYLOAD) {
/* PVA Audio Packets either start with a signaled PES packet or
* are a continuation of the previous PES packet. New PES packets
* always start at the beginning of a PVA Packet, never somewhere in
* the middle. */
if (!pvactx->continue_pes) {
int pes_signal, pes_header_data_length, pes_packet_length,
pes_flags;
unsigned char pes_header_data[256];
pes_signal = avio_rb24(pb);
avio_r8(pb);
pes_packet_length = avio_rb16(pb);
pes_flags = avio_rb16(pb);
pes_header_data_length = avio_r8(pb);
if (avio_feof(pb)) {
return AVERROR_EOF;
}
if (pes_signal != 1 || pes_header_data_length == 0) {
pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, "
"trying to recover\n");
avio_skip(pb, length - 9);
if (!read_packet)
return AVERROR(EIO);
goto recover;
}
ret = avio_read(pb, pes_header_data, pes_header_data_length);
if (ret != pes_header_data_length)
return ret < 0 ? ret : AVERROR_INVALIDDATA;
length -= 9 + pes_header_data_length;
pes_packet_length -= 3 + pes_header_data_length;
pvactx->continue_pes = pes_packet_length;
if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) {
if (pes_header_data_length < 5) {
pva_log(s, AV_LOG_ERROR, "header too short\n");
avio_skip(pb, length);
return AVERROR_INVALIDDATA;
}
pva_pts = ff_parse_pes_pts(pes_header_data);
}
}
pvactx->continue_pes -= length;
if (pvactx->continue_pes < 0) {
pva_log(s, AV_LOG_WARNING, "audio data corruption\n");
pvactx->continue_pes = 0;
}
}
if (pva_pts != AV_NOPTS_VALUE)
av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME);
*pts = pva_pts;
*len = length;
*strid = streamid;
return 0;
}
static int pva_read_packet(AVFormatContext *s, AVPacket *pkt) {
AVIOContext *pb = s->pb;
int64_t pva_pts;
int ret, length, streamid;
if (read_part_of_packet(s, &pva_pts, &length, &streamid, 1) < 0 ||
(ret = av_get_packet(pb, pkt, length)) <= 0)
return AVERROR(EIO);
pkt->stream_index = streamid - 1;
pkt->pts = pva_pts;
return ret;
}
static int64_t pva_read_timestamp(struct AVFormatContext *s, int stream_index,
int64_t *pos, int64_t pos_limit) {
AVIOContext *pb = s->pb;
PVAContext *pvactx = s->priv_data;
int length, streamid;
int64_t res = AV_NOPTS_VALUE;
pos_limit = FFMIN(*pos+PVA_MAX_PAYLOAD_LENGTH*8, (uint64_t)*pos+pos_limit);
while (*pos < pos_limit) {
res = AV_NOPTS_VALUE;
avio_seek(pb, *pos, SEEK_SET);
pvactx->continue_pes = 0;
if (read_part_of_packet(s, &res, &length, &streamid, 0)) {
(*pos)++;
continue;
}
if (streamid - 1 != stream_index || res == AV_NOPTS_VALUE) {
*pos = avio_tell(pb) + length;
continue;
}
break;
}
pvactx->continue_pes = 0;
return res;
}
AVInputFormat ff_pva_demuxer = {
.name = "pva",
.long_name = NULL_IF_CONFIG_SMALL("TechnoTrend PVA"),
.priv_data_size = sizeof(PVAContext),
.read_probe = pva_probe,
.read_header = pva_read_header,
.read_packet = pva_read_packet,
.read_timestamp = pva_read_timestamp,
};
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_465_0 |
crossvul-cpp_data_good_5710_0 | /*
* $Id$
*
* Lookup contacts in usrloc
*
* Copyright (C) 2001-2003 FhG Fokus
*
* This file is part of opensips, a free SIP server.
*
* opensips 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
*
* opensips 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
*
* History:
* ---------
* 2003-03-12 added support for zombie state (nils)
*/
/*!
* \file
* \brief SIP registrar module - lookup contacts in usrloc
* \ingroup registrar
*/
#include <string.h>
#include "../../ut.h"
#include "../../dset.h"
#include "../../str.h"
#include "../../config.h"
#include "../../action.h"
#include "../../mod_fix.h"
#include "../../parser/parse_rr.h"
#include "../usrloc/usrloc.h"
#include "common.h"
#include "regtime.h"
#include "reg_mod.h"
#include "lookup.h"
#define GR_E_PART_SIZE 22
#define GR_A_PART_SIZE 14
#define allowed_method(_msg, _c, _f) \
( !((_f)®_LOOKUP_METHODFILTER_FLAG) || \
((_msg)->REQ_METHOD)&((_c)->methods) )
/*! \brief
* Lookup contact in the database and rewrite Request-URI
* \return: -1 : not found
* -2 : found but method not allowed
* -3 : error
*/
int lookup(struct sip_msg* _m, char* _t, char* _f, char* _s)
{
unsigned int flags;
urecord_t* r;
str aor, uri;
ucontact_t* ptr,*it;
int res;
int ret;
str path_dst;
str flags_s;
pv_value_t val;
int_str istr;
str sip_instance = {0,0},call_id = {0,0};
flags = 0;
if (_f && _f[0]!=0) {
if (fixup_get_svalue( _m, (gparam_p)_f, &flags_s)!=0) {
LM_ERR("invalid owner uri parameter");
return -1;
}
for( res=0 ; res< flags_s.len ; res++ ) {
switch (flags_s.s[res]) {
case 'm': flags |= REG_LOOKUP_METHODFILTER_FLAG; break;
case 'b': flags |= REG_LOOKUP_NOBRANCH_FLAG; break;
default: LM_WARN("unsuported flag %c \n",flags_s.s[res]);
}
}
}
if (_s) {
if (pv_get_spec_value( _m, (pv_spec_p)_s, &val)!=0) {
LM_ERR("failed to get PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("PV vals is not string\n");
return -1;
}
uri = val.rs;
} else {
if (_m->new_uri.s) uri = _m->new_uri;
else uri = _m->first_line.u.request.uri;
}
if (extract_aor(&uri, &aor,&sip_instance,&call_id) < 0) {
LM_ERR("failed to extract address of record\n");
return -3;
}
get_act_time();
ul.lock_udomain((udomain_t*)_t, &aor);
res = ul.get_urecord((udomain_t*)_t, &aor, &r);
if (res > 0) {
LM_DBG("'%.*s' Not found in usrloc\n", aor.len, ZSW(aor.s));
ul.unlock_udomain((udomain_t*)_t, &aor);
return -1;
}
ptr = r->contacts;
ret = -1;
/* look first for an un-expired and suported contact */
search_valid_contact:
while ( (ptr) &&
!(VALID_CONTACT(ptr,act_time) && (ret=-2) && allowed_method(_m,ptr,flags)))
ptr = ptr->next;
if (ptr==0) {
/* nothing found */
LM_DBG("nothing found !\n");
goto done;
}
if (sip_instance.len && sip_instance.s) {
LM_DBG("ruri has gruu in lookup\n");
/* uri has GRUU */
if (ptr->instance.len-2 != sip_instance.len ||
memcmp(ptr->instance.s+1,sip_instance.s,sip_instance.len)) {
LM_DBG("no match to sip instace - [%.*s] - [%.*s]\n",ptr->instance.len-2,ptr->instance.s+1,
sip_instance.len,sip_instance.s);
/* not the targeted instance, search some more */
ptr = ptr->next;
goto search_valid_contact;
}
LM_DBG("matched sip instace\n");
}
if (call_id.len && call_id.s) {
/* decide whether GRUU is expired or not
*
* first - match call-id */
if (ptr->callid.len != call_id.len ||
memcmp(ptr->callid.s,call_id.s,call_id.len)) {
LM_DBG("no match to call id - [%.*s] - [%.*s]\n",ptr->callid.len,ptr->callid.s,
call_id.len,call_id.s);
ptr = ptr->next;
goto search_valid_contact;
}
/* matched call-id, check if there are newer contacts with
* same sip instace bup newer last_modified */
it = ptr->next;
while ( it ) {
if (VALID_CONTACT(it,act_time)) {
if (it->instance.len-2 == sip_instance.len &&
memcmp(it->instance.s+1,sip_instance.s,sip_instance.len) == 0)
if (it->last_modified > ptr->last_modified) {
/* same instance id, but newer modified -> expired GRUU, no match at all */
break;
}
}
it=it->next;
}
if (it != NULL) {
ret = -1;
goto done;
}
}
LM_DBG("found a complete match\n");
ret = 1;
if (ptr) {
LM_DBG("setting as ruri <%.*s>\n",ptr->c.len,ptr->c.s);
if (set_ruri(_m, &ptr->c) < 0) {
LM_ERR("unable to rewrite Request-URI\n");
ret = -3;
goto done;
}
/* If a Path is present, use first path-uri in favour of
* received-uri because in that case the last hop towards the uac
* has to handle NAT. - agranig */
if (ptr->path.s && ptr->path.len) {
if (get_path_dst_uri(&ptr->path, &path_dst) < 0) {
LM_ERR("failed to get dst_uri for Path\n");
ret = -3;
goto done;
}
if (set_path_vector(_m, &ptr->path) < 0) {
LM_ERR("failed to set path vector\n");
ret = -3;
goto done;
}
if (set_dst_uri(_m, &path_dst) < 0) {
LM_ERR("failed to set dst_uri of Path\n");
ret = -3;
goto done;
}
} else if (ptr->received.s && ptr->received.len) {
if (set_dst_uri(_m, &ptr->received) < 0) {
ret = -3;
goto done;
}
}
set_ruri_q(ptr->q);
setbflag( 0, ptr->cflags);
if (ptr->sock)
_m->force_send_socket = ptr->sock;
/* populate the 'attributes' avp */
if (attr_avp_name != -1) {
istr.s = ptr->attr;
if (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {
LM_ERR("Failed to populate attr avp!\n");
}
}
ptr = ptr->next;
}
/* Append branches if enabled */
/* If we got to this point and the URI had a ;gr parameter and it was matched
* to a contact. No point in branching */
if ( flags®_LOOKUP_NOBRANCH_FLAG || (sip_instance.len && sip_instance.s) ) goto done;
LM_DBG("looking for branches\n");
for( ; ptr ; ptr = ptr->next ) {
if (VALID_CONTACT(ptr, act_time) && allowed_method(_m,ptr,flags)) {
path_dst.len = 0;
if(ptr->path.s && ptr->path.len
&& get_path_dst_uri(&ptr->path, &path_dst) < 0) {
LM_ERR("failed to get dst_uri for Path\n");
continue;
}
/* The same as for the first contact applies for branches
* regarding path vs. received. */
LM_DBG("setting branch <%.*s>\n",ptr->c.len,ptr->c.s);
if (append_branch(_m,&ptr->c,path_dst.len?&path_dst:&ptr->received,
&ptr->path, ptr->q, ptr->cflags, ptr->sock) == -1) {
LM_ERR("failed to append a branch\n");
/* Also give a chance to the next branches*/
continue;
}
/* populate the 'attributes' avp */
if (attr_avp_name != -1) {
istr.s = ptr->attr;
if (add_avp_last(AVP_VAL_STR, attr_avp_name, istr) != 0) {
LM_ERR("Failed to populate attr avp!\n");
}
}
}
}
done:
ul.release_urecord(r);
ul.unlock_udomain((udomain_t*)_t, &aor);
return ret;
}
/*! \brief the is_registered() function
* Return true if the AOR in the Request-URI is registered,
* it is similar to lookup but registered neither rewrites
* the Request-URI nor appends branches
*/
int registered(struct sip_msg* _m, char* _t, char* _s, char *_c)
{
str uri, aor;
urecord_t* r;
ucontact_t* ptr;
pv_value_t val;
str callid;
int res;
/* get the AOR */
if (_s) {
if (pv_get_spec_value( _m, (pv_spec_p)_s, &val)!=0) {
LM_ERR("failed to getAOR PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("AOR PV vals is not string\n");
return -1;
}
uri = val.rs;
} else {
if (_m->first_line.type!=SIP_REQUEST) {
LM_ERR("no AOR and called for a reply!");
return -1;
}
if (_m->new_uri.s) uri = _m->new_uri;
else uri = _m->first_line.u.request.uri;
}
if (extract_aor(&uri, &aor,0,0) < 0) {
LM_ERR("failed to extract address of record\n");
return -1;
}
/* get the callid */
if (_c) {
if (pv_get_spec_value( _m, (pv_spec_p)_c, &val)!=0) {
LM_ERR("failed to get callid PV value\n");
return -1;
}
if ( (val.flags&PV_VAL_STR)==0 ) {
LM_ERR("callid PV vals is not string\n");
return -1;
}
callid = val.rs;
} else {
callid.s = NULL;
callid.len = 0;
}
ul.lock_udomain((udomain_t*)_t, &aor);
res = ul.get_urecord((udomain_t*)_t, &aor, &r);
if (res < 0) {
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_ERR("failed to query usrloc\n");
return -1;
}
if (res == 0) {
ptr = r->contacts;
while (ptr && !VALID_CONTACT(ptr, act_time)) {
ptr = ptr->next;
}
for( ; ptr ; ptr=ptr->next ) {
if (callid.len==0 || (callid.len==ptr->callid.len &&
memcmp(callid.s,ptr->callid.s,callid.len)==0 ) ) {
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_DBG("'%.*s' found in usrloc\n", aor.len, ZSW(aor.s));
return 1;
}
}
}
ul.unlock_udomain((udomain_t*)_t, &aor);
LM_DBG("'%.*s' not found in usrloc\n", aor.len, ZSW(aor.s));
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_5710_0 |
crossvul-cpp_data_good_3278_0 | /*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static. These functions are needed by GSO/GRO implementation.
*/
#include <linux/export.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/addrconf.h>
#include <net/secure_seq.h>
#include <linux/netfilter.h>
static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
/* This function exists only for tap drivers that must support broken
* clients requesting UFO without specifying an IPv6 fragment ID.
*
* This is similar to ipv6_select_ident() but we use an independent hash
* seed to limit information leakage.
*
* The network header must be set before calling this.
*/
void ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
skb_shinfo(skb)->ip6_frag_id = htonl(id);
}
EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);
__be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
EXPORT_SYMBOL(ipv6_select_ident);
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
unsigned int offset = sizeof(struct ipv6hdr);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset <= packet_len) {
struct ipv6_opt_hdr *exthdr;
unsigned int len;
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
if (offset + sizeof(struct ipv6_opt_hdr) > packet_len)
return -EINVAL;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
len = ipv6_optlen(exthdr);
if (len + offset >= IPV6_MAXPLEN)
return -EINVAL;
offset += len;
*nexthdr = &exthdr->nexthdr;
}
return -EINVAL;
}
EXPORT_SYMBOL(ip6_find_1stfragopt);
#if IS_ENABLED(CONFIG_IPV6)
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
#endif
int __ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out(sk, skb);
if (unlikely(!skb))
return 0;
skb->protocol = htons(ETH_P_IPV6);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, sk, skb, NULL, skb_dst(skb)->dev,
dst_output);
}
EXPORT_SYMBOL_GPL(__ip6_local_out);
int ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int err;
err = __ip6_local_out(net, sk, skb);
if (likely(err == 1))
err = dst_output(net, sk, skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_3278_0 |
crossvul-cpp_data_bad_2564_0 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
*
* Copyright (C) 2007 Novell, Inc.
* Copyright (C) 2008 Red Hat, Inc.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "config.h"
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <gio/gio.h>
#include <glib/gi18n.h>
#include "gsm-xsmp-client.h"
#include "gsm-marshal.h"
#include "gsm-util.h"
#include "gsm-autostart-app.h"
#include "gsm-manager.h"
#define GsmDesktopFile "_GSM_DesktopFile"
#define IS_STRING_EMPTY(x) ((x)==NULL||(x)[0]=='\0')
#define GSM_XSMP_CLIENT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSM_TYPE_XSMP_CLIENT, GsmXSMPClientPrivate))
struct GsmXSMPClientPrivate
{
SmsConn conn;
IceConn ice_connection;
guint watch_id;
guint protocol_timeout;
char *description;
GPtrArray *props;
/* SaveYourself state */
int current_save_yourself;
int next_save_yourself;
guint next_save_yourself_allow_interact : 1;
};
enum {
PROP_0,
PROP_ICE_CONNECTION
};
enum {
REGISTER_REQUEST,
LOGOUT_REQUEST,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };
G_DEFINE_TYPE (GsmXSMPClient, gsm_xsmp_client, GSM_TYPE_CLIENT)
static gboolean
client_iochannel_watch (GIOChannel *channel,
GIOCondition condition,
GsmXSMPClient *client)
{
gboolean keep_going;
g_object_ref (client);
switch (IceProcessMessages (client->priv->ice_connection, NULL, NULL)) {
case IceProcessMessagesSuccess:
keep_going = TRUE;
break;
case IceProcessMessagesIOError:
g_debug ("GsmXSMPClient: IceProcessMessagesIOError on '%s'", client->priv->description);
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
/* Emitting "disconnected" will eventually cause
* IceCloseConnection() to be called.
*/
gsm_client_disconnected (GSM_CLIENT (client));
keep_going = FALSE;
break;
case IceProcessMessagesConnectionClosed:
g_debug ("GsmXSMPClient: IceProcessMessagesConnectionClosed on '%s'",
client->priv->description);
client->priv->ice_connection = NULL;
keep_going = FALSE;
break;
default:
g_assert_not_reached ();
}
g_object_unref (client);
return keep_going;
}
/* Called if too much time passes between the initial connection and
* the XSMP protocol setup.
*/
static gboolean
_client_protocol_timeout (GsmXSMPClient *client)
{
g_debug ("GsmXSMPClient: client_protocol_timeout for client '%s' in ICE status %d",
client->priv->description,
IceConnectionStatus (client->priv->ice_connection));
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
gsm_client_disconnected (GSM_CLIENT (client));
return FALSE;
}
static SmProp *
find_property (GsmXSMPClient *client,
const char *name,
int *index)
{
SmProp *prop;
int i;
for (i = 0; i < client->priv->props->len; i++) {
prop = client->priv->props->pdata[i];
if (!strcmp (prop->name, name)) {
if (index) {
*index = i;
}
return prop;
}
}
return NULL;
}
static void
set_description (GsmXSMPClient *client)
{
SmProp *prop;
const char *id;
prop = find_property (client, SmProgram, NULL);
id = gsm_client_peek_startup_id (GSM_CLIENT (client));
g_free (client->priv->description);
if (prop) {
client->priv->description = g_strdup_printf ("%p [%.*s %s]",
client,
prop->vals[0].length,
(char *)prop->vals[0].value,
id);
} else if (id != NULL) {
client->priv->description = g_strdup_printf ("%p [%s]", client, id);
} else {
client->priv->description = g_strdup_printf ("%p", client);
}
}
static void
setup_connection (GsmXSMPClient *client)
{
GIOChannel *channel;
int fd;
g_debug ("GsmXSMPClient: Setting up new connection");
fd = IceConnectionNumber (client->priv->ice_connection);
fcntl (fd, F_SETFD, fcntl (fd, F_GETFD, 0) | FD_CLOEXEC);
channel = g_io_channel_unix_new (fd);
client->priv->watch_id = g_io_add_watch (channel,
G_IO_IN | G_IO_ERR,
(GIOFunc)client_iochannel_watch,
client);
g_io_channel_unref (channel);
client->priv->protocol_timeout = g_timeout_add_seconds (5,
(GSourceFunc)_client_protocol_timeout,
client);
set_description (client);
g_debug ("GsmXSMPClient: New client '%s'", client->priv->description);
}
static GObject *
gsm_xsmp_client_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_properties)
{
GsmXSMPClient *client;
client = GSM_XSMP_CLIENT (G_OBJECT_CLASS (gsm_xsmp_client_parent_class)->constructor (type,
n_construct_properties,
construct_properties));
setup_connection (client);
return G_OBJECT (client);
}
static void
gsm_xsmp_client_init (GsmXSMPClient *client)
{
client->priv = GSM_XSMP_CLIENT_GET_PRIVATE (client);
client->priv->props = g_ptr_array_new ();
client->priv->current_save_yourself = -1;
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = FALSE;
}
static void
delete_property (GsmXSMPClient *client,
const char *name)
{
int index;
SmProp *prop;
prop = find_property (client, name, &index);
if (!prop) {
return;
}
#if 0
/* This is wrong anyway; we can't unconditionally run the current
* discard command; if this client corresponds to a GsmAppResumed,
* and the current discard command is identical to the app's
* discard_command, then we don't run the discard command now,
* because that would delete a saved state we may want to resume
* again later.
*/
if (!strcmp (name, SmDiscardCommand)) {
gsm_client_run_discard (GSM_CLIENT (client));
}
#endif
g_ptr_array_remove_index_fast (client->priv->props, index);
SmFreeProperty (prop);
}
static void
debug_print_property (SmProp *prop)
{
GString *tmp;
int i;
switch (prop->type[0]) {
case 'C': /* CARD8 */
g_debug ("GsmXSMPClient: %s = %d", prop->name, *(unsigned char *)prop->vals[0].value);
break;
case 'A': /* ARRAY8 */
g_debug ("GsmXSMPClient: %s = '%s'", prop->name, (char *)prop->vals[0].value);
break;
case 'L': /* LISTofARRAY8 */
tmp = g_string_new (NULL);
for (i = 0; i < prop->num_vals; i++) {
g_string_append_printf (tmp, "'%.*s' ", prop->vals[i].length,
(char *)prop->vals[i].value);
}
g_debug ("GsmXSMPClient: %s = %s", prop->name, tmp->str);
g_string_free (tmp, TRUE);
break;
default:
g_debug ("GsmXSMPClient: %s = ??? (%s)", prop->name, prop->type);
break;
}
}
static void
set_properties_callback (SmsConn conn,
SmPointer manager_data,
int num_props,
SmProp **props)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Set properties from client '%s'", client->priv->description);
for (i = 0; i < num_props; i++) {
delete_property (client, props[i]->name);
g_ptr_array_add (client->priv->props, props[i]);
debug_print_property (props[i]);
if (!strcmp (props[i]->name, SmProgram))
set_description (client);
}
free (props);
}
static void
delete_properties_callback (SmsConn conn,
SmPointer manager_data,
int num_props,
char **prop_names)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Delete properties from '%s'", client->priv->description);
for (i = 0; i < num_props; i++) {
delete_property (client, prop_names[i]);
g_debug (" %s", prop_names[i]);
}
free (prop_names);
}
static void
get_properties_callback (SmsConn conn,
SmPointer manager_data)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Get properties request from '%s'", client->priv->description);
SmsReturnProperties (conn,
client->priv->props->len,
(SmProp **)client->priv->props->pdata);
}
static char *
prop_to_command (SmProp *prop)
{
GString *str;
int i, j;
gboolean need_quotes;
str = g_string_new (NULL);
for (i = 0; i < prop->num_vals; i++) {
char *val = prop->vals[i].value;
need_quotes = FALSE;
for (j = 0; j < prop->vals[i].length; j++) {
if (!g_ascii_isalnum (val[j]) && !strchr ("-_=:./", val[j])) {
need_quotes = TRUE;
break;
}
}
if (i > 0) {
g_string_append_c (str, ' ');
}
if (!need_quotes) {
g_string_append_printf (str,
"%.*s",
prop->vals[i].length,
(char *)prop->vals[i].value);
} else {
g_string_append_c (str, '\'');
while (val < (char *)prop->vals[i].value + prop->vals[i].length) {
if (*val == '\'') {
g_string_append (str, "'\''");
} else {
g_string_append_c (str, *val);
}
val++;
}
g_string_append_c (str, '\'');
}
}
return g_string_free (str, FALSE);
}
static char *
xsmp_get_restart_command (GsmClient *client)
{
SmProp *prop;
prop = find_property (GSM_XSMP_CLIENT (client), SmRestartCommand, NULL);
if (!prop || strcmp (prop->type, SmLISTofARRAY8) != 0) {
return NULL;
}
return prop_to_command (prop);
}
static char *
xsmp_get_discard_command (GsmClient *client)
{
SmProp *prop;
prop = find_property (GSM_XSMP_CLIENT (client), SmDiscardCommand, NULL);
if (!prop || strcmp (prop->type, SmLISTofARRAY8) != 0) {
return NULL;
}
return prop_to_command (prop);
}
static void
do_save_yourself (GsmXSMPClient *client,
int save_type,
gboolean allow_interact)
{
g_assert (client->priv->conn != NULL);
if (client->priv->next_save_yourself != -1) {
/* Either we're currently doing a shutdown and there's a checkpoint
* queued after it, or vice versa. Either way, the new SaveYourself
* is redundant.
*/
g_debug ("GsmXSMPClient: skipping redundant SaveYourself for '%s'",
client->priv->description);
} else if (client->priv->current_save_yourself != -1) {
g_debug ("GsmXSMPClient: queuing new SaveYourself for '%s'",
client->priv->description);
client->priv->next_save_yourself = save_type;
client->priv->next_save_yourself_allow_interact = allow_interact;
} else {
client->priv->current_save_yourself = save_type;
/* make sure we don't have anything queued */
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = FALSE;
switch (save_type) {
case SmSaveLocal:
/* Save state */
SmsSaveYourself (client->priv->conn,
SmSaveLocal,
FALSE,
SmInteractStyleNone,
FALSE);
break;
default:
/* Logout */
if (!allow_interact) {
SmsSaveYourself (client->priv->conn,
save_type, /* save type */
TRUE, /* shutdown */
SmInteractStyleNone, /* interact style */
TRUE); /* fast */
} else {
SmsSaveYourself (client->priv->conn,
save_type, /* save type */
TRUE, /* shutdown */
SmInteractStyleAny, /* interact style */
FALSE /* fast */);
}
break;
}
}
}
static void
xsmp_save_yourself_phase2 (GsmClient *client)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_save_yourself_phase2 ('%s')", xsmp->priv->description);
SmsSaveYourselfPhase2 (xsmp->priv->conn);
}
static void
xsmp_interact (GsmClient *client)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_interact ('%s')", xsmp->priv->description);
SmsInteract (xsmp->priv->conn);
}
static gboolean
xsmp_cancel_end_session (GsmClient *client,
GError **error)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_cancel_end_session ('%s')", xsmp->priv->description);
if (xsmp->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
SmsShutdownCancelled (xsmp->priv->conn);
/* reset the state */
xsmp->priv->current_save_yourself = -1;
xsmp->priv->next_save_yourself = -1;
xsmp->priv->next_save_yourself_allow_interact = FALSE;
return TRUE;
}
static char *
get_desktop_file_path (GsmXSMPClient *client)
{
SmProp *prop;
char *desktop_file_path = NULL;
char **dirs;
const char *program_name;
/* XSMP clients using eggsmclient defines a special property
* pointing to their respective desktop entry file */
prop = find_property (client, GsmDesktopFile, NULL);
if (prop) {
GFile *file = g_file_new_for_uri (prop->vals[0].value);
desktop_file_path = g_file_get_path (file);
g_object_unref (file);
goto out;
}
/* If we can't get desktop file from GsmDesktopFile then we
* try to find the desktop file from its program name */
prop = find_property (client, SmProgram, NULL);
program_name = prop->vals[0].value;
dirs = gsm_util_get_autostart_dirs ();
desktop_file_path =
gsm_util_find_desktop_file_for_app_name (program_name,
dirs);
g_strfreev (dirs);
out:
g_debug ("GsmXSMPClient: desktop file for client %s is %s",
gsm_client_peek_id (GSM_CLIENT (client)),
desktop_file_path ? desktop_file_path : "(null)");
return desktop_file_path;
}
static void
set_desktop_file_keys_from_client (GsmClient *client,
GKeyFile *keyfile)
{
SmProp *prop;
char *name;
char *comment;
prop = find_property (GSM_XSMP_CLIENT (client), SmProgram, NULL);
name = g_strdup (prop->vals[0].value);
comment = g_strdup_printf ("Client %s which was automatically saved",
gsm_client_peek_startup_id (client));
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_NAME,
name);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_COMMENT,
comment);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_ICON,
"system-run");
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_TYPE,
"Application");
g_key_file_set_boolean (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY,
TRUE);
g_free (name);
g_free (comment);
}
static GKeyFile *
create_client_key_file (GsmClient *client,
const char *desktop_file_path,
GError **error) {
GKeyFile *keyfile;
keyfile = g_key_file_new ();
if (desktop_file_path != NULL) {
g_key_file_load_from_file (keyfile,
desktop_file_path,
G_KEY_FILE_KEEP_COMMENTS |
G_KEY_FILE_KEEP_TRANSLATIONS,
error);
} else {
set_desktop_file_keys_from_client (client, keyfile);
}
return keyfile;
}
static GsmClientRestartStyle
xsmp_get_restart_style_hint (GsmClient *client);
static GKeyFile *
xsmp_save (GsmClient *client,
GError **error)
{
GsmClientRestartStyle restart_style;
GKeyFile *keyfile = NULL;
char *desktop_file_path = NULL;
char *exec_program = NULL;
char *exec_discard = NULL;
char *startup_id = NULL;
GError *local_error;
g_debug ("GsmXSMPClient: saving client with id %s",
gsm_client_peek_id (client));
local_error = NULL;
restart_style = xsmp_get_restart_style_hint (client);
if (restart_style == GSM_CLIENT_RESTART_NEVER) {
goto out;
}
exec_program = xsmp_get_restart_command (client);
if (!exec_program) {
goto out;
}
desktop_file_path = get_desktop_file_path (GSM_XSMP_CLIENT (client));
keyfile = create_client_key_file (client,
desktop_file_path,
&local_error);
if (local_error) {
goto out;
}
g_object_get (client,
"startup-id", &startup_id,
NULL);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
GSM_AUTOSTART_APP_STARTUP_ID_KEY,
startup_id);
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
G_KEY_FILE_DESKTOP_KEY_EXEC,
exec_program);
exec_discard = xsmp_get_discard_command (client);
if (exec_discard)
g_key_file_set_string (keyfile,
G_KEY_FILE_DESKTOP_GROUP,
GSM_AUTOSTART_APP_DISCARD_KEY,
exec_discard);
out:
g_free (desktop_file_path);
g_free (exec_program);
g_free (exec_discard);
g_free (startup_id);
if (local_error != NULL) {
g_propagate_error (error, local_error);
g_key_file_free (keyfile);
return NULL;
}
return keyfile;
}
static gboolean
xsmp_stop (GsmClient *client,
GError **error)
{
GsmXSMPClient *xsmp = (GsmXSMPClient *) client;
g_debug ("GsmXSMPClient: xsmp_stop ('%s')", xsmp->priv->description);
if (xsmp->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
SmsDie (xsmp->priv->conn);
return TRUE;
}
static gboolean
xsmp_query_end_session (GsmClient *client,
guint flags,
GError **error)
{
gboolean allow_interact;
int save_type;
if (GSM_XSMP_CLIENT (client)->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
allow_interact = !(flags & GSM_CLIENT_END_SESSION_FLAG_FORCEFUL);
/* we don't want to save the session state, but we just want to know if
* there's user data the client has to save and we want to give the
* client a chance to tell the user about it. This is consistent with
* the manager not setting GSM_CLIENT_END_SESSION_FLAG_SAVE for this
* phase. */
save_type = SmSaveGlobal;
do_save_yourself (GSM_XSMP_CLIENT (client), save_type, allow_interact);
return TRUE;
}
static gboolean
xsmp_end_session (GsmClient *client,
guint flags,
GError **error)
{
gboolean phase2;
if (GSM_XSMP_CLIENT (client)->priv->conn == NULL) {
g_set_error (error,
GSM_CLIENT_ERROR,
GSM_CLIENT_ERROR_NOT_REGISTERED,
"Client is not registered");
return FALSE;
}
phase2 = (flags & GSM_CLIENT_END_SESSION_FLAG_LAST);
if (phase2) {
xsmp_save_yourself_phase2 (client);
} else {
gboolean allow_interact;
int save_type;
/* we gave a chance to interact to the app during
* xsmp_query_end_session(), now it's too late to interact */
allow_interact = FALSE;
if (flags & GSM_CLIENT_END_SESSION_FLAG_SAVE) {
save_type = SmSaveBoth;
} else {
save_type = SmSaveGlobal;
}
do_save_yourself (GSM_XSMP_CLIENT (client),
save_type, allow_interact);
}
return TRUE;
}
static char *
xsmp_get_app_name (GsmClient *client)
{
SmProp *prop;
char *name;
prop = find_property (GSM_XSMP_CLIENT (client), SmProgram, NULL);
name = prop_to_command (prop);
return name;
}
static void
gsm_client_set_ice_connection (GsmXSMPClient *client,
gpointer conn)
{
client->priv->ice_connection = conn;
}
static void
gsm_xsmp_client_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GsmXSMPClient *self;
self = GSM_XSMP_CLIENT (object);
switch (prop_id) {
case PROP_ICE_CONNECTION:
gsm_client_set_ice_connection (self, g_value_get_pointer (value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_client_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GsmXSMPClient *self;
self = GSM_XSMP_CLIENT (object);
switch (prop_id) {
case PROP_ICE_CONNECTION:
g_value_set_pointer (value, self->priv->ice_connection);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
if (client->priv->protocol_timeout > 0) {
g_source_remove (client->priv->protocol_timeout);
}
}
static void
gsm_xsmp_client_finalize (GObject *object)
{
GsmXSMPClient *client = (GsmXSMPClient *) object;
g_debug ("GsmXSMPClient: xsmp_finalize (%s)", client->priv->description);
gsm_xsmp_client_disconnect (client);
g_free (client->priv->description);
g_ptr_array_foreach (client->priv->props, (GFunc)SmFreeProperty, NULL);
g_ptr_array_free (client->priv->props, TRUE);
G_OBJECT_CLASS (gsm_xsmp_client_parent_class)->finalize (object);
}
static gboolean
_boolean_handled_accumulator (GSignalInvocationHint *ihint,
GValue *return_accu,
const GValue *handler_return,
gpointer dummy)
{
gboolean continue_emission;
gboolean signal_handled;
signal_handled = g_value_get_boolean (handler_return);
g_value_set_boolean (return_accu, signal_handled);
continue_emission = !signal_handled;
return continue_emission;
}
static GsmClientRestartStyle
xsmp_get_restart_style_hint (GsmClient *client)
{
SmProp *prop;
GsmClientRestartStyle hint;
g_debug ("GsmXSMPClient: getting restart style");
hint = GSM_CLIENT_RESTART_IF_RUNNING;
prop = find_property (GSM_XSMP_CLIENT (client), SmRestartStyleHint, NULL);
if (!prop || strcmp (prop->type, SmCARD8) != 0) {
return GSM_CLIENT_RESTART_IF_RUNNING;
}
switch (((unsigned char *)prop->vals[0].value)[0]) {
case SmRestartIfRunning:
hint = GSM_CLIENT_RESTART_IF_RUNNING;
break;
case SmRestartAnyway:
hint = GSM_CLIENT_RESTART_ANYWAY;
break;
case SmRestartImmediately:
hint = GSM_CLIENT_RESTART_IMMEDIATELY;
break;
case SmRestartNever:
hint = GSM_CLIENT_RESTART_NEVER;
break;
default:
break;
}
return hint;
}
static gboolean
_parse_value_as_uint (const char *value,
guint *uintval)
{
char *end_of_valid_uint;
gulong ulong_value;
guint uint_value;
errno = 0;
ulong_value = strtoul (value, &end_of_valid_uint, 10);
if (*value == '\0' || *end_of_valid_uint != '\0') {
return FALSE;
}
uint_value = ulong_value;
if (uint_value != ulong_value || errno == ERANGE) {
return FALSE;
}
*uintval = uint_value;
return TRUE;
}
static guint
xsmp_get_unix_process_id (GsmClient *client)
{
SmProp *prop;
guint pid;
gboolean res;
g_debug ("GsmXSMPClient: getting pid");
prop = find_property (GSM_XSMP_CLIENT (client), SmProcessID, NULL);
if (!prop || strcmp (prop->type, SmARRAY8) != 0) {
return 0;
}
pid = 0;
res = _parse_value_as_uint ((char *)prop->vals[0].value, &pid);
if (! res) {
pid = 0;
}
return pid;
}
static void
gsm_xsmp_client_class_init (GsmXSMPClientClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GsmClientClass *client_class = GSM_CLIENT_CLASS (klass);
object_class->finalize = gsm_xsmp_client_finalize;
object_class->constructor = gsm_xsmp_client_constructor;
object_class->get_property = gsm_xsmp_client_get_property;
object_class->set_property = gsm_xsmp_client_set_property;
client_class->impl_save = xsmp_save;
client_class->impl_stop = xsmp_stop;
client_class->impl_query_end_session = xsmp_query_end_session;
client_class->impl_end_session = xsmp_end_session;
client_class->impl_cancel_end_session = xsmp_cancel_end_session;
client_class->impl_get_app_name = xsmp_get_app_name;
client_class->impl_get_restart_style_hint = xsmp_get_restart_style_hint;
client_class->impl_get_unix_process_id = xsmp_get_unix_process_id;
signals[REGISTER_REQUEST] =
g_signal_new ("register-request",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GsmXSMPClientClass, register_request),
_boolean_handled_accumulator,
NULL,
gsm_marshal_BOOLEAN__POINTER,
G_TYPE_BOOLEAN,
1, G_TYPE_POINTER);
signals[LOGOUT_REQUEST] =
g_signal_new ("logout-request",
G_OBJECT_CLASS_TYPE (object_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GsmXSMPClientClass, logout_request),
NULL,
NULL,
g_cclosure_marshal_VOID__BOOLEAN,
G_TYPE_NONE,
1, G_TYPE_BOOLEAN);
g_object_class_install_property (object_class,
PROP_ICE_CONNECTION,
g_param_spec_pointer ("ice-connection",
"ice-connection",
"ice-connection",
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass, sizeof (GsmXSMPClientPrivate));
}
GsmClient *
gsm_xsmp_client_new (IceConn ice_conn)
{
GsmXSMPClient *xsmp;
xsmp = g_object_new (GSM_TYPE_XSMP_CLIENT,
"ice-connection", ice_conn,
NULL);
return GSM_CLIENT (xsmp);
}
static Status
register_client_callback (SmsConn conn,
SmPointer manager_data,
char *previous_id)
{
GsmXSMPClient *client = manager_data;
gboolean handled;
char *id;
g_debug ("GsmXSMPClient: Client '%s' received RegisterClient(%s)",
client->priv->description,
previous_id ? previous_id : "NULL");
/* There are three cases:
* 1. id is NULL - we'll use a new one
* 2. id is known - we'll use known one
* 3. id is unknown - this is an error
*/
id = g_strdup (previous_id);
handled = FALSE;
g_signal_emit (client, signals[REGISTER_REQUEST], 0, &id, &handled);
if (! handled) {
g_debug ("GsmXSMPClient: RegisterClient not handled!");
g_free (id);
free (previous_id);
g_assert_not_reached ();
return FALSE;
}
if (IS_STRING_EMPTY (id)) {
g_debug ("GsmXSMPClient: rejected: invalid previous_id");
free (previous_id);
return FALSE;
}
g_object_set (client, "startup-id", id, NULL);
set_description (client);
g_debug ("GsmXSMPClient: Sending RegisterClientReply to '%s'", client->priv->description);
SmsRegisterClientReply (conn, id);
if (IS_STRING_EMPTY (previous_id)) {
/* Send the initial SaveYourself. */
g_debug ("GsmXSMPClient: Sending initial SaveYourself");
SmsSaveYourself (conn, SmSaveLocal, False, SmInteractStyleNone, False);
client->priv->current_save_yourself = SmSaveLocal;
}
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_REGISTERED);
g_free (id);
free (previous_id);
return TRUE;
}
static void
save_yourself_request_callback (SmsConn conn,
SmPointer manager_data,
int save_type,
Bool shutdown,
int interact_style,
Bool fast,
Bool global)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfRequest(%s, %s, %s, %s, %s)",
client->priv->description,
save_type == SmSaveLocal ? "SmSaveLocal" :
save_type == SmSaveGlobal ? "SmSaveGlobal" : "SmSaveBoth",
shutdown ? "Shutdown" : "!Shutdown",
interact_style == SmInteractStyleAny ? "SmInteractStyleAny" :
interact_style == SmInteractStyleErrors ? "SmInteractStyleErrors" :
"SmInteractStyleNone", fast ? "Fast" : "!Fast",
global ? "Global" : "!Global");
/* Examining the g_debug above, you can see that there are a total
* of 72 different combinations of options that this could have been
* called with. However, most of them are stupid.
*
* If @shutdown and @global are both TRUE, that means the caller is
* requesting that a logout message be sent to all clients, so we do
* that. We use @fast to decide whether or not to show a
* confirmation dialog. (This isn't really what @fast is for, but
* the old gnome-session and ksmserver both interpret it that way,
* so we do too.) We ignore @save_type because we pick the correct
* save_type ourselves later based on user prefs, dialog choices,
* etc, and we ignore @interact_style, because clients have not used
* it correctly consistently enough to make it worth honoring.
*
* If @shutdown is TRUE and @global is FALSE, the caller is
* confused, so we ignore the request.
*
* If @shutdown is FALSE and @save_type is SmSaveGlobal or
* SmSaveBoth, then the client wants us to ask some or all open
* applications to save open files to disk, but NOT quit. This is
* silly and so we ignore the request.
*
* If @shutdown is FALSE and @save_type is SmSaveLocal, then the
* client wants us to ask some or all open applications to update
* their current saved state, but not log out. At the moment, the
* code only supports this for the !global case (ie, a client
* requesting that it be allowed to update *its own* saved state,
* but not having everyone else update their saved state).
*/
if (shutdown && global) {
g_debug ("GsmXSMPClient: initiating shutdown");
g_signal_emit (client, signals[LOGOUT_REQUEST], 0, !fast);
} else if (!shutdown && !global) {
g_debug ("GsmXSMPClient: initiating checkpoint");
do_save_yourself (client, SmSaveLocal, TRUE);
} else {
g_debug ("GsmXSMPClient: ignoring");
}
}
static void
save_yourself_phase2_request_callback (SmsConn conn,
SmPointer manager_data)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfPhase2Request",
client->priv->description);
client->priv->current_save_yourself = -1;
/* this is a valid response to SaveYourself and therefore
may be a response to a QES or ES */
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, TRUE, FALSE,
NULL);
}
static void
interact_request_callback (SmsConn conn,
SmPointer manager_data,
int dialog_type)
{
GsmXSMPClient *client = manager_data;
#if 0
gboolean res;
GError *error;
#endif
g_debug ("GsmXSMPClient: Client '%s' received InteractRequest(%s)",
client->priv->description,
dialog_type == SmDialogNormal ? "Dialog" : "Errors");
gsm_client_end_session_response (GSM_CLIENT (client),
FALSE, FALSE, FALSE,
_("This program is blocking log out."));
#if 0
/* Can't just call back with Interact because session client
grabs the keyboard! So, we try to get it to release
grabs by telling it we've cancelled the shutdown.
This grabbing is clearly bullshit and is not supported by
the client spec or protocol spec.
*/
res = xsmp_cancel_end_session (GSM_CLIENT (client), &error);
if (! res) {
g_warning ("Unable to cancel end session: %s", error->message);
g_error_free (error);
}
#endif
xsmp_interact (GSM_CLIENT (client));
}
static void
interact_done_callback (SmsConn conn,
SmPointer manager_data,
Bool cancel_shutdown)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received InteractDone(cancel_shutdown = %s)",
client->priv->description,
cancel_shutdown ? "True" : "False");
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, FALSE, cancel_shutdown,
NULL);
}
static void
save_yourself_done_callback (SmsConn conn,
SmPointer manager_data,
Bool success)
{
GsmXSMPClient *client = manager_data;
g_debug ("GsmXSMPClient: Client '%s' received SaveYourselfDone(success = %s)",
client->priv->description,
success ? "True" : "False");
if (client->priv->current_save_yourself != -1) {
SmsSaveComplete (client->priv->conn);
client->priv->current_save_yourself = -1;
}
/* If success is false then the application couldn't save data. Nothing
* the session manager can do about, though. FIXME: we could display a
* dialog about this, I guess. */
gsm_client_end_session_response (GSM_CLIENT (client),
TRUE, FALSE, FALSE,
NULL);
if (client->priv->next_save_yourself) {
int save_type = client->priv->next_save_yourself;
gboolean allow_interact = client->priv->next_save_yourself_allow_interact;
client->priv->next_save_yourself = -1;
client->priv->next_save_yourself_allow_interact = -1;
do_save_yourself (client, save_type, allow_interact);
}
}
static void
close_connection_callback (SmsConn conn,
SmPointer manager_data,
int count,
char **reason_msgs)
{
GsmXSMPClient *client = manager_data;
int i;
g_debug ("GsmXSMPClient: Client '%s' received CloseConnection", client->priv->description);
for (i = 0; i < count; i++) {
g_debug ("GsmXSMPClient: close reason: '%s'", reason_msgs[i]);
}
SmFreeReasons (count, reason_msgs);
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FINISHED);
gsm_client_disconnected (GSM_CLIENT (client));
}
void
gsm_xsmp_client_connect (GsmXSMPClient *client,
SmsConn conn,
unsigned long *mask_ret,
SmsCallbacks *callbacks_ret)
{
client->priv->conn = conn;
if (client->priv->protocol_timeout) {
g_source_remove (client->priv->protocol_timeout);
client->priv->protocol_timeout = 0;
}
g_debug ("GsmXSMPClient: Initializing client %s", client->priv->description);
*mask_ret = 0;
*mask_ret |= SmsRegisterClientProcMask;
callbacks_ret->register_client.callback = register_client_callback;
callbacks_ret->register_client.manager_data = client;
*mask_ret |= SmsInteractRequestProcMask;
callbacks_ret->interact_request.callback = interact_request_callback;
callbacks_ret->interact_request.manager_data = client;
*mask_ret |= SmsInteractDoneProcMask;
callbacks_ret->interact_done.callback = interact_done_callback;
callbacks_ret->interact_done.manager_data = client;
*mask_ret |= SmsSaveYourselfRequestProcMask;
callbacks_ret->save_yourself_request.callback = save_yourself_request_callback;
callbacks_ret->save_yourself_request.manager_data = client;
*mask_ret |= SmsSaveYourselfP2RequestProcMask;
callbacks_ret->save_yourself_phase2_request.callback = save_yourself_phase2_request_callback;
callbacks_ret->save_yourself_phase2_request.manager_data = client;
*mask_ret |= SmsSaveYourselfDoneProcMask;
callbacks_ret->save_yourself_done.callback = save_yourself_done_callback;
callbacks_ret->save_yourself_done.manager_data = client;
*mask_ret |= SmsCloseConnectionProcMask;
callbacks_ret->close_connection.callback = close_connection_callback;
callbacks_ret->close_connection.manager_data = client;
*mask_ret |= SmsSetPropertiesProcMask;
callbacks_ret->set_properties.callback = set_properties_callback;
callbacks_ret->set_properties.manager_data = client;
*mask_ret |= SmsDeletePropertiesProcMask;
callbacks_ret->delete_properties.callback = delete_properties_callback;
callbacks_ret->delete_properties.manager_data = client;
*mask_ret |= SmsGetPropertiesProcMask;
callbacks_ret->get_properties.callback = get_properties_callback;
callbacks_ret->get_properties.manager_data = client;
}
void
gsm_xsmp_client_save_state (GsmXSMPClient *client)
{
g_return_if_fail (GSM_IS_XSMP_CLIENT (client));
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_2564_0 |
crossvul-cpp_data_bad_3169_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.
*
* Implementation of the Transmission Control Protocol(TCP).
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Mark Evans, <evansmp@uhura.aston.ac.uk>
* Corey Minyard <wf-rch!minyard@relay.EU.net>
* Florian La Roche, <flla@stud.uni-sb.de>
* Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
* Linus Torvalds, <torvalds@cs.helsinki.fi>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
* Matthew Dillon, <dillon@apollo.west.oic.com>
* Arnt Gulbrandsen, <agulbra@nvg.unit.no>
* Jorge Cwik, <jorge@laser.satlink.net>
*
* Fixes:
* Alan Cox : Numerous verify_area() calls
* Alan Cox : Set the ACK bit on a reset
* Alan Cox : Stopped it crashing if it closed while
* sk->inuse=1 and was trying to connect
* (tcp_err()).
* Alan Cox : All icmp error handling was broken
* pointers passed where wrong and the
* socket was looked up backwards. Nobody
* tested any icmp error code obviously.
* Alan Cox : tcp_err() now handled properly. It
* wakes people on errors. poll
* behaves and the icmp error race
* has gone by moving it into sock.c
* Alan Cox : tcp_send_reset() fixed to work for
* everything not just packets for
* unknown sockets.
* Alan Cox : tcp option processing.
* Alan Cox : Reset tweaked (still not 100%) [Had
* syn rule wrong]
* Herp Rosmanith : More reset fixes
* Alan Cox : No longer acks invalid rst frames.
* Acking any kind of RST is right out.
* Alan Cox : Sets an ignore me flag on an rst
* receive otherwise odd bits of prattle
* escape still
* Alan Cox : Fixed another acking RST frame bug.
* Should stop LAN workplace lockups.
* Alan Cox : Some tidyups using the new skb list
* facilities
* Alan Cox : sk->keepopen now seems to work
* Alan Cox : Pulls options out correctly on accepts
* Alan Cox : Fixed assorted sk->rqueue->next errors
* Alan Cox : PSH doesn't end a TCP read. Switched a
* bit to skb ops.
* Alan Cox : Tidied tcp_data to avoid a potential
* nasty.
* Alan Cox : Added some better commenting, as the
* tcp is hard to follow
* Alan Cox : Removed incorrect check for 20 * psh
* Michael O'Reilly : ack < copied bug fix.
* Johannes Stille : Misc tcp fixes (not all in yet).
* Alan Cox : FIN with no memory -> CRASH
* Alan Cox : Added socket option proto entries.
* Also added awareness of them to accept.
* Alan Cox : Added TCP options (SOL_TCP)
* Alan Cox : Switched wakeup calls to callbacks,
* so the kernel can layer network
* sockets.
* Alan Cox : Use ip_tos/ip_ttl settings.
* Alan Cox : Handle FIN (more) properly (we hope).
* Alan Cox : RST frames sent on unsynchronised
* state ack error.
* Alan Cox : Put in missing check for SYN bit.
* Alan Cox : Added tcp_select_window() aka NET2E
* window non shrink trick.
* Alan Cox : Added a couple of small NET2E timer
* fixes
* Charles Hedrick : TCP fixes
* Toomas Tamm : TCP window fixes
* Alan Cox : Small URG fix to rlogin ^C ack fight
* Charles Hedrick : Rewrote most of it to actually work
* Linus : Rewrote tcp_read() and URG handling
* completely
* Gerhard Koerting: Fixed some missing timer handling
* Matthew Dillon : Reworked TCP machine states as per RFC
* Gerhard Koerting: PC/TCP workarounds
* Adam Caldwell : Assorted timer/timing errors
* Matthew Dillon : Fixed another RST bug
* Alan Cox : Move to kernel side addressing changes.
* Alan Cox : Beginning work on TCP fastpathing
* (not yet usable)
* Arnt Gulbrandsen: Turbocharged tcp_check() routine.
* Alan Cox : TCP fast path debugging
* Alan Cox : Window clamping
* Michael Riepe : Bug in tcp_check()
* Matt Dillon : More TCP improvements and RST bug fixes
* Matt Dillon : Yet more small nasties remove from the
* TCP code (Be very nice to this man if
* tcp finally works 100%) 8)
* Alan Cox : BSD accept semantics.
* Alan Cox : Reset on closedown bug.
* Peter De Schrijver : ENOTCONN check missing in tcp_sendto().
* Michael Pall : Handle poll() after URG properly in
* all cases.
* Michael Pall : Undo the last fix in tcp_read_urg()
* (multi URG PUSH broke rlogin).
* Michael Pall : Fix the multi URG PUSH problem in
* tcp_readable(), poll() after URG
* works now.
* Michael Pall : recv(...,MSG_OOB) never blocks in the
* BSD api.
* Alan Cox : Changed the semantics of sk->socket to
* fix a race and a signal problem with
* accept() and async I/O.
* Alan Cox : Relaxed the rules on tcp_sendto().
* Yury Shevchuk : Really fixed accept() blocking problem.
* Craig I. Hagan : Allow for BSD compatible TIME_WAIT for
* clients/servers which listen in on
* fixed ports.
* Alan Cox : Cleaned the above up and shrank it to
* a sensible code size.
* Alan Cox : Self connect lockup fix.
* Alan Cox : No connect to multicast.
* Ross Biro : Close unaccepted children on master
* socket close.
* Alan Cox : Reset tracing code.
* Alan Cox : Spurious resets on shutdown.
* Alan Cox : Giant 15 minute/60 second timer error
* Alan Cox : Small whoops in polling before an
* accept.
* Alan Cox : Kept the state trace facility since
* it's handy for debugging.
* Alan Cox : More reset handler fixes.
* Alan Cox : Started rewriting the code based on
* the RFC's for other useful protocol
* references see: Comer, KA9Q NOS, and
* for a reference on the difference
* between specifications and how BSD
* works see the 4.4lite source.
* A.N.Kuznetsov : Don't time wait on completion of tidy
* close.
* Linus Torvalds : Fin/Shutdown & copied_seq changes.
* Linus Torvalds : Fixed BSD port reuse to work first syn
* Alan Cox : Reimplemented timers as per the RFC
* and using multiple timers for sanity.
* Alan Cox : Small bug fixes, and a lot of new
* comments.
* Alan Cox : Fixed dual reader crash by locking
* the buffers (much like datagram.c)
* Alan Cox : Fixed stuck sockets in probe. A probe
* now gets fed up of retrying without
* (even a no space) answer.
* Alan Cox : Extracted closing code better
* Alan Cox : Fixed the closing state machine to
* resemble the RFC.
* Alan Cox : More 'per spec' fixes.
* Jorge Cwik : Even faster checksumming.
* Alan Cox : tcp_data() doesn't ack illegal PSH
* only frames. At least one pc tcp stack
* generates them.
* Alan Cox : Cache last socket.
* Alan Cox : Per route irtt.
* Matt Day : poll()->select() match BSD precisely on error
* Alan Cox : New buffers
* Marc Tamsky : Various sk->prot->retransmits and
* sk->retransmits misupdating fixed.
* Fixed tcp_write_timeout: stuck close,
* and TCP syn retries gets used now.
* Mark Yarvis : In tcp_read_wakeup(), don't send an
* ack if state is TCP_CLOSED.
* Alan Cox : Look up device on a retransmit - routes may
* change. Doesn't yet cope with MSS shrink right
* but it's a start!
* Marc Tamsky : Closing in closing fixes.
* Mike Shaver : RFC1122 verifications.
* Alan Cox : rcv_saddr errors.
* Alan Cox : Block double connect().
* Alan Cox : Small hooks for enSKIP.
* Alexey Kuznetsov: Path MTU discovery.
* Alan Cox : Support soft errors.
* Alan Cox : Fix MTU discovery pathological case
* when the remote claims no mtu!
* Marc Tamsky : TCP_CLOSE fix.
* Colin (G3TNE) : Send a reset on syn ack replies in
* window but wrong (fixes NT lpd problems)
* Pedro Roque : Better TCP window handling, delayed ack.
* Joerg Reuter : No modification of locked buffers in
* tcp_do_retransmit()
* Eric Schenk : Changed receiver side silly window
* avoidance algorithm to BSD style
* algorithm. This doubles throughput
* against machines running Solaris,
* and seems to result in general
* improvement.
* Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD
* Willy Konynenberg : Transparent proxying support.
* Mike McLagan : Routing by source
* Keith Owens : Do proper merging with partial SKB's in
* tcp_do_sendmsg to avoid burstiness.
* Eric Schenk : Fix fast close down bug with
* shutdown() followed by close().
* Andi Kleen : Make poll agree with SIGIO
* Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and
* lingertime == 0 (RFC 793 ABORT Call)
* Hirokazu Takahashi : Use copy_from_user() instead of
* csum_and_copy_from_user() if possible.
*
* 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.
*
* Description of States:
*
* TCP_SYN_SENT sent a connection request, waiting for ack
*
* TCP_SYN_RECV received a connection request, sent ack,
* waiting for final ack in three-way handshake.
*
* TCP_ESTABLISHED connection established
*
* TCP_FIN_WAIT1 our side has shutdown, waiting to complete
* transmission of remaining buffered data
*
* TCP_FIN_WAIT2 all buffered data sent, waiting for remote
* to shutdown
*
* TCP_CLOSING both sides have shutdown but we still have
* data we have to finish sending
*
* TCP_TIME_WAIT timeout to catch resent junk before entering
* closed, can only be entered from FIN_WAIT2
* or CLOSING. Required because the other end
* may not have gotten our last ACK causing it
* to retransmit the data packet (which we ignore)
*
* TCP_CLOSE_WAIT remote side has shutdown and is waiting for
* us to finish writing our data and to shutdown
* (we have to close() to move on to LAST_ACK)
*
* TCP_LAST_ACK out side has shutdown after remote has
* shutdown. There may still be data in our
* buffer that we have to finish sending
*
* TCP_CLOSE socket is finished
*/
#define pr_fmt(fmt) "TCP: " fmt
#include <crypto/hash.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/inet_diag.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/skbuff.h>
#include <linux/scatterlist.h>
#include <linux/splice.h>
#include <linux/net.h>
#include <linux/socket.h>
#include <linux/random.h>
#include <linux/bootmem.h>
#include <linux/highmem.h>
#include <linux/swap.h>
#include <linux/cache.h>
#include <linux/err.h>
#include <linux/time.h>
#include <linux/slab.h>
#include <net/icmp.h>
#include <net/inet_common.h>
#include <net/tcp.h>
#include <net/xfrm.h>
#include <net/ip.h>
#include <net/sock.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <net/busy_poll.h>
int sysctl_tcp_min_tso_segs __read_mostly = 2;
int sysctl_tcp_autocorking __read_mostly = 1;
struct percpu_counter tcp_orphan_count;
EXPORT_SYMBOL_GPL(tcp_orphan_count);
long sysctl_tcp_mem[3] __read_mostly;
int sysctl_tcp_wmem[3] __read_mostly;
int sysctl_tcp_rmem[3] __read_mostly;
EXPORT_SYMBOL(sysctl_tcp_mem);
EXPORT_SYMBOL(sysctl_tcp_rmem);
EXPORT_SYMBOL(sysctl_tcp_wmem);
atomic_long_t tcp_memory_allocated; /* Current allocated memory. */
EXPORT_SYMBOL(tcp_memory_allocated);
/*
* Current number of TCP sockets.
*/
struct percpu_counter tcp_sockets_allocated;
EXPORT_SYMBOL(tcp_sockets_allocated);
/*
* TCP splice context
*/
struct tcp_splice_state {
struct pipe_inode_info *pipe;
size_t len;
unsigned int flags;
};
/*
* Pressure flag: try to collapse.
* Technical note: it is used by multiple contexts non atomically.
* All the __sk_mem_schedule() is of this nature: accounting
* is strict, actions are advisory and have some latency.
*/
int tcp_memory_pressure __read_mostly;
EXPORT_SYMBOL(tcp_memory_pressure);
void tcp_enter_memory_pressure(struct sock *sk)
{
if (!tcp_memory_pressure) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES);
tcp_memory_pressure = 1;
}
}
EXPORT_SYMBOL(tcp_enter_memory_pressure);
/* Convert seconds to retransmits based on initial and max timeout */
static u8 secs_to_retrans(int seconds, int timeout, int rto_max)
{
u8 res = 0;
if (seconds > 0) {
int period = timeout;
res = 1;
while (seconds > period && res < 255) {
res++;
timeout <<= 1;
if (timeout > rto_max)
timeout = rto_max;
period += timeout;
}
}
return res;
}
/* Convert retransmits to seconds based on initial and max timeout */
static int retrans_to_secs(u8 retrans, int timeout, int rto_max)
{
int period = 0;
if (retrans > 0) {
period = timeout;
while (--retrans) {
timeout <<= 1;
if (timeout > rto_max)
timeout = rto_max;
period += timeout;
}
}
return period;
}
/* Address-family independent initialization for a tcp_sock.
*
* NOTE: A lot of things set to zero explicitly by call to
* sk_alloc() so need not be done here.
*/
void tcp_init_sock(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
tp->out_of_order_queue = RB_ROOT;
tcp_init_xmit_timers(sk);
tcp_prequeue_init(tp);
INIT_LIST_HEAD(&tp->tsq_node);
icsk->icsk_rto = TCP_TIMEOUT_INIT;
tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT);
minmax_reset(&tp->rtt_min, tcp_time_stamp, ~0U);
/* So many TCP implementations out there (incorrectly) count the
* initial SYN frame in their delayed-ACK and congestion control
* algorithms that we must have the following bandaid to talk
* efficiently to them. -DaveM
*/
tp->snd_cwnd = TCP_INIT_CWND;
/* There's a bubble in the pipe until at least the first ACK. */
tp->app_limited = ~0U;
/* See draft-stevens-tcpca-spec-01 for discussion of the
* initialization of these values.
*/
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_clamp = ~0;
tp->mss_cache = TCP_MSS_DEFAULT;
tp->reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering;
tcp_enable_early_retrans(tp);
tcp_assign_congestion_control(sk);
tp->tsoffset = 0;
sk->sk_state = TCP_CLOSE;
sk->sk_write_space = sk_stream_write_space;
sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
icsk->icsk_sync_mss = tcp_sync_mss;
sk->sk_sndbuf = sysctl_tcp_wmem[1];
sk->sk_rcvbuf = sysctl_tcp_rmem[1];
local_bh_disable();
sk_sockets_allocated_inc(sk);
local_bh_enable();
}
EXPORT_SYMBOL(tcp_init_sock);
static void tcp_tx_timestamp(struct sock *sk, u16 tsflags, struct sk_buff *skb)
{
if (tsflags) {
struct skb_shared_info *shinfo = skb_shinfo(skb);
struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags);
if (tsflags & SOF_TIMESTAMPING_TX_ACK)
tcb->txstamp_ack = 1;
if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK)
shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
}
}
/*
* Wait for a TCP event.
*
* Note that we don't need to lock the socket, as the upper poll layers
* take care of normal races (between the test and the event) and we don't
* go look at any of the socket buffers directly.
*/
unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait)
{
unsigned int mask;
struct sock *sk = sock->sk;
const struct tcp_sock *tp = tcp_sk(sk);
int state;
sock_rps_record_flow(sk);
sock_poll_wait(file, sk_sleep(sk), wait);
state = sk_state_load(sk);
if (state == TCP_LISTEN)
return inet_csk_listen_poll(sk);
/* Socket is not locked. We are protected from async events
* by poll logic and correct handling of state changes
* made by other threads is impossible in any case.
*/
mask = 0;
/*
* POLLHUP is certainly not done right. But poll() doesn't
* have a notion of HUP in just one direction, and for a
* socket the read side is more interesting.
*
* Some poll() documentation says that POLLHUP is incompatible
* with the POLLOUT/POLLWR flags, so somebody should check this
* all. But careful, it tends to be safer to return too many
* bits than too few, and you can easily break real applications
* if you don't tell them that something has hung up!
*
* Check-me.
*
* Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and
* our fs/select.c). It means that after we received EOF,
* poll always returns immediately, making impossible poll() on write()
* in state CLOSE_WAIT. One solution is evident --- to set POLLHUP
* if and only if shutdown has been made in both directions.
* Actually, it is interesting to look how Solaris and DUX
* solve this dilemma. I would prefer, if POLLHUP were maskable,
* then we could set it on SND_SHUTDOWN. BTW examples given
* in Stevens' books assume exactly this behaviour, it explains
* why POLLHUP is incompatible with POLLOUT. --ANK
*
* NOTE. Check for TCP_CLOSE is added. The goal is to prevent
* blocking on fresh not-connected or disconnected socket. --ANK
*/
if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLIN | POLLRDNORM | POLLRDHUP;
/* Connected or passive Fast Open socket? */
if (state != TCP_SYN_SENT &&
(state != TCP_SYN_RECV || tp->fastopen_rsk)) {
int target = sock_rcvlowat(sk, 0, INT_MAX);
if (tp->urg_seq == tp->copied_seq &&
!sock_flag(sk, SOCK_URGINLINE) &&
tp->urg_data)
target++;
if (tp->rcv_nxt - tp->copied_seq >= target)
mask |= POLLIN | POLLRDNORM;
if (!(sk->sk_shutdown & SEND_SHUTDOWN)) {
if (sk_stream_is_writeable(sk)) {
mask |= POLLOUT | POLLWRNORM;
} else { /* send SIGIO later */
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
/* Race breaker. If space is freed after
* wspace test but before the flags are set,
* IO signal will be lost. Memory barrier
* pairs with the input side.
*/
smp_mb__after_atomic();
if (sk_stream_is_writeable(sk))
mask |= POLLOUT | POLLWRNORM;
}
} else
mask |= POLLOUT | POLLWRNORM;
if (tp->urg_data & TCP_URG_VALID)
mask |= POLLPRI;
}
/* This barrier is coupled with smp_wmb() in tcp_reset() */
smp_rmb();
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR;
return mask;
}
EXPORT_SYMBOL(tcp_poll);
int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
struct tcp_sock *tp = tcp_sk(sk);
int answ;
bool slow;
switch (cmd) {
case SIOCINQ:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
slow = lock_sock_fast(sk);
answ = tcp_inq(sk);
unlock_sock_fast(sk, slow);
break;
case SIOCATMARK:
answ = tp->urg_data && tp->urg_seq == tp->copied_seq;
break;
case SIOCOUTQ:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
answ = 0;
else
answ = tp->write_seq - tp->snd_una;
break;
case SIOCOUTQNSD:
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))
answ = 0;
else
answ = tp->write_seq - tp->snd_nxt;
break;
default:
return -ENOIOCTLCMD;
}
return put_user(answ, (int __user *)arg);
}
EXPORT_SYMBOL(tcp_ioctl);
static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb)
{
TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH;
tp->pushed_seq = tp->write_seq;
}
static inline bool forced_push(const struct tcp_sock *tp)
{
return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1));
}
static void skb_entail(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
skb->csum = 0;
tcb->seq = tcb->end_seq = tp->write_seq;
tcb->tcp_flags = TCPHDR_ACK;
tcb->sacked = 0;
__skb_header_release(skb);
tcp_add_write_queue_tail(sk, skb);
sk->sk_wmem_queued += skb->truesize;
sk_mem_charge(sk, skb->truesize);
if (tp->nonagle & TCP_NAGLE_PUSH)
tp->nonagle &= ~TCP_NAGLE_PUSH;
tcp_slow_start_after_idle_check(sk);
}
static inline void tcp_mark_urg(struct tcp_sock *tp, int flags)
{
if (flags & MSG_OOB)
tp->snd_up = tp->write_seq;
}
/* If a not yet filled skb is pushed, do not send it if
* we have data packets in Qdisc or NIC queues :
* Because TX completion will happen shortly, it gives a chance
* to coalesce future sendmsg() payload into this skb, without
* need for a timer, and with no latency trade off.
* As packets containing data payload have a bigger truesize
* than pure acks (dataless) packets, the last checks prevent
* autocorking if we only have an ACK in Qdisc/NIC queues,
* or if TX completion was delayed after we processed ACK packet.
*/
static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb,
int size_goal)
{
return skb->len < size_goal &&
sysctl_tcp_autocorking &&
skb != tcp_write_queue_head(sk) &&
atomic_read(&sk->sk_wmem_alloc) > skb->truesize;
}
static void tcp_push(struct sock *sk, int flags, int mss_now,
int nonagle, int size_goal)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
if (!tcp_send_head(sk))
return;
skb = tcp_write_queue_tail(sk);
if (!(flags & MSG_MORE) || forced_push(tp))
tcp_mark_push(tp, skb);
tcp_mark_urg(tp, flags);
if (tcp_should_autocork(sk, skb, size_goal)) {
/* avoid atomic op if TSQ_THROTTLED bit is already set */
if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) {
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING);
set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags);
}
/* It is possible TX completion already happened
* before we set TSQ_THROTTLED.
*/
if (atomic_read(&sk->sk_wmem_alloc) > skb->truesize)
return;
}
if (flags & MSG_MORE)
nonagle = TCP_NAGLE_CORK;
__tcp_push_pending_frames(sk, mss_now, nonagle);
}
static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb,
unsigned int offset, size_t len)
{
struct tcp_splice_state *tss = rd_desc->arg.data;
int ret;
ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe,
min(rd_desc->count, len), tss->flags);
if (ret > 0)
rd_desc->count -= ret;
return ret;
}
static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss)
{
/* Store TCP splice context information in read_descriptor_t. */
read_descriptor_t rd_desc = {
.arg.data = tss,
.count = tss->len,
};
return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv);
}
/**
* tcp_splice_read - splice data from TCP socket to a pipe
* @sock: socket to splice from
* @ppos: position (not valid)
* @pipe: pipe to splice to
* @len: number of bytes to splice
* @flags: splice modifier flags
*
* Description:
* Will read pages from given socket and fill them into a pipe.
*
**/
ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct sock *sk = sock->sk;
struct tcp_splice_state tss = {
.pipe = pipe,
.len = len,
.flags = flags,
};
long timeo;
ssize_t spliced;
int ret;
sock_rps_record_flow(sk);
/*
* We can't seek on a socket input
*/
if (unlikely(*ppos))
return -ESPIPE;
ret = spliced = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK);
while (tss.len) {
ret = __tcp_splice_read(sk, &tss);
if (ret < 0)
break;
else if (!ret) {
if (spliced)
break;
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
ret = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
/*
* This occurs when user tries to read
* from never connected socket.
*/
if (!sock_flag(sk, SOCK_DONE))
ret = -ENOTCONN;
break;
}
if (!timeo) {
ret = -EAGAIN;
break;
}
sk_wait_data(sk, &timeo, NULL);
if (signal_pending(current)) {
ret = sock_intr_errno(timeo);
break;
}
continue;
}
tss.len -= ret;
spliced += ret;
if (!timeo)
break;
release_sock(sk);
lock_sock(sk);
if (sk->sk_err || sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current))
break;
}
release_sock(sk);
if (spliced)
return spliced;
return ret;
}
EXPORT_SYMBOL(tcp_splice_read);
struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp,
bool force_schedule)
{
struct sk_buff *skb;
/* The TCP header must be at least 32-bit aligned. */
size = ALIGN(size, 4);
if (unlikely(tcp_under_memory_pressure(sk)))
sk_mem_reclaim_partial(sk);
skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp);
if (likely(skb)) {
bool mem_scheduled;
if (force_schedule) {
mem_scheduled = true;
sk_forced_mem_schedule(sk, skb->truesize);
} else {
mem_scheduled = sk_wmem_schedule(sk, skb->truesize);
}
if (likely(mem_scheduled)) {
skb_reserve(skb, sk->sk_prot->max_header);
/*
* Make sure that we have exactly size bytes
* available to the caller, no more, no less.
*/
skb->reserved_tailroom = skb->end - skb->tail - size;
return skb;
}
__kfree_skb(skb);
} else {
sk->sk_prot->enter_memory_pressure(sk);
sk_stream_moderate_sndbuf(sk);
}
return NULL;
}
static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now,
int large_allowed)
{
struct tcp_sock *tp = tcp_sk(sk);
u32 new_size_goal, size_goal;
if (!large_allowed || !sk_can_gso(sk))
return mss_now;
/* Note : tcp_tso_autosize() will eventually split this later */
new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER;
new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal);
/* We try hard to avoid divides here */
size_goal = tp->gso_segs * mss_now;
if (unlikely(new_size_goal < size_goal ||
new_size_goal >= size_goal + mss_now)) {
tp->gso_segs = min_t(u16, new_size_goal / mss_now,
sk->sk_gso_max_segs);
size_goal = tp->gso_segs * mss_now;
}
return max(size_goal, mss_now);
}
static int tcp_send_mss(struct sock *sk, int *size_goal, int flags)
{
int mss_now;
mss_now = tcp_current_mss(sk);
*size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB));
return mss_now;
}
static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset,
size_t size, int flags)
{
struct tcp_sock *tp = tcp_sk(sk);
int mss_now, size_goal;
int err;
ssize_t copied;
long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
/* Wait for a connection to finish. One exception is TCP Fast Open
* (passive side) where data is allowed to be sent before a connection
* is fully established.
*/
if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
!tcp_passive_fastopen(sk)) {
err = sk_stream_wait_connect(sk, &timeo);
if (err != 0)
goto out_err;
}
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
mss_now = tcp_send_mss(sk, &size_goal, flags);
copied = 0;
err = -EPIPE;
if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
goto out_err;
while (size > 0) {
struct sk_buff *skb = tcp_write_queue_tail(sk);
int copy, i;
bool can_coalesce;
if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 ||
!tcp_skb_can_collapse_to(skb)) {
new_segment:
if (!sk_stream_memory_free(sk))
goto wait_for_sndbuf;
skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation,
skb_queue_empty(&sk->sk_write_queue));
if (!skb)
goto wait_for_memory;
skb_entail(sk, skb);
copy = size_goal;
}
if (copy > size)
copy = size;
i = skb_shinfo(skb)->nr_frags;
can_coalesce = skb_can_coalesce(skb, i, page, offset);
if (!can_coalesce && i >= sysctl_max_skb_frags) {
tcp_mark_push(tp, skb);
goto new_segment;
}
if (!sk_wmem_schedule(sk, copy))
goto wait_for_memory;
if (can_coalesce) {
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
} else {
get_page(page);
skb_fill_page_desc(skb, i, page, offset, copy);
}
skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
sk->sk_wmem_queued += copy;
sk_mem_charge(sk, copy);
skb->ip_summed = CHECKSUM_PARTIAL;
tp->write_seq += copy;
TCP_SKB_CB(skb)->end_seq += copy;
tcp_skb_pcount_set(skb, 0);
if (!copied)
TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
copied += copy;
offset += copy;
size -= copy;
if (!size) {
tcp_tx_timestamp(sk, sk->sk_tsflags, skb);
goto out;
}
if (skb->len < size_goal || (flags & MSG_OOB))
continue;
if (forced_push(tp)) {
tcp_mark_push(tp, skb);
__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
} else if (skb == tcp_send_head(sk))
tcp_push_one(sk, mss_now);
continue;
wait_for_sndbuf:
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
tcp_push(sk, flags & ~MSG_MORE, mss_now,
TCP_NAGLE_PUSH, size_goal);
err = sk_stream_wait_memory(sk, &timeo);
if (err != 0)
goto do_error;
mss_now = tcp_send_mss(sk, &size_goal, flags);
}
out:
if (copied && !(flags & MSG_SENDPAGE_NOTLAST))
tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
return copied;
do_error:
if (copied)
goto out;
out_err:
/* make sure we wake any epoll edge trigger waiter */
if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
err == -EAGAIN)) {
sk->sk_write_space(sk);
tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
}
return sk_stream_error(sk, flags, err);
}
int tcp_sendpage(struct sock *sk, struct page *page, int offset,
size_t size, int flags)
{
ssize_t res;
if (!(sk->sk_route_caps & NETIF_F_SG) ||
!sk_check_csum_caps(sk))
return sock_no_sendpage(sk->sk_socket, page, offset, size,
flags);
lock_sock(sk);
tcp_rate_check_app_limited(sk); /* is sending application-limited? */
res = do_tcp_sendpages(sk, page, offset, size, flags);
release_sock(sk);
return res;
}
EXPORT_SYMBOL(tcp_sendpage);
/* Do not bother using a page frag for very small frames.
* But use this heuristic only for the first skb in write queue.
*
* Having no payload in skb->head allows better SACK shifting
* in tcp_shift_skb_data(), reducing sack/rack overhead, because
* write queue has less skbs.
* Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB.
* This also speeds up tso_fragment(), since it wont fallback
* to tcp_fragment().
*/
static int linear_payload_sz(bool first_skb)
{
if (first_skb)
return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER);
return 0;
}
static int select_size(const struct sock *sk, bool sg, bool first_skb)
{
const struct tcp_sock *tp = tcp_sk(sk);
int tmp = tp->mss_cache;
if (sg) {
if (sk_can_gso(sk)) {
tmp = linear_payload_sz(first_skb);
} else {
int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER);
if (tmp >= pgbreak &&
tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE)
tmp = pgbreak;
}
}
return tmp;
}
void tcp_free_fastopen_req(struct tcp_sock *tp)
{
if (tp->fastopen_req) {
kfree(tp->fastopen_req);
tp->fastopen_req = NULL;
}
}
static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg,
int *copied, size_t size)
{
struct tcp_sock *tp = tcp_sk(sk);
int err, flags;
if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE))
return -EOPNOTSUPP;
if (tp->fastopen_req)
return -EALREADY; /* Another Fast Open is in progress */
tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request),
sk->sk_allocation);
if (unlikely(!tp->fastopen_req))
return -ENOBUFS;
tp->fastopen_req->data = msg;
tp->fastopen_req->size = size;
flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0;
err = __inet_stream_connect(sk->sk_socket, msg->msg_name,
msg->msg_namelen, flags);
*copied = tp->fastopen_req->copied;
tcp_free_fastopen_req(tp);
return err;
}
int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *skb;
struct sockcm_cookie sockc;
int flags, err, copied = 0;
int mss_now = 0, size_goal, copied_syn = 0;
bool process_backlog = false;
bool sg;
long timeo;
lock_sock(sk);
flags = msg->msg_flags;
if (flags & MSG_FASTOPEN) {
err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size);
if (err == -EINPROGRESS && copied_syn > 0)
goto out;
else if (err)
goto out_err;
}
timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
tcp_rate_check_app_limited(sk); /* is sending application-limited? */
/* Wait for a connection to finish. One exception is TCP Fast Open
* (passive side) where data is allowed to be sent before a connection
* is fully established.
*/
if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) &&
!tcp_passive_fastopen(sk)) {
err = sk_stream_wait_connect(sk, &timeo);
if (err != 0)
goto do_error;
}
if (unlikely(tp->repair)) {
if (tp->repair_queue == TCP_RECV_QUEUE) {
copied = tcp_send_rcvq(sk, msg, size);
goto out_nopush;
}
err = -EINVAL;
if (tp->repair_queue == TCP_NO_QUEUE)
goto out_err;
/* 'common' sending to sendq */
}
sockc.tsflags = sk->sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err)) {
err = -EINVAL;
goto out_err;
}
}
/* This should be in poll */
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
/* Ok commence sending. */
copied = 0;
restart:
mss_now = tcp_send_mss(sk, &size_goal, flags);
err = -EPIPE;
if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN))
goto do_error;
sg = !!(sk->sk_route_caps & NETIF_F_SG);
while (msg_data_left(msg)) {
int copy = 0;
int max = size_goal;
skb = tcp_write_queue_tail(sk);
if (tcp_send_head(sk)) {
if (skb->ip_summed == CHECKSUM_NONE)
max = mss_now;
copy = max - skb->len;
}
if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) {
bool first_skb;
new_segment:
/* Allocate new segment. If the interface is SG,
* allocate skb fitting to single page.
*/
if (!sk_stream_memory_free(sk))
goto wait_for_sndbuf;
if (process_backlog && sk_flush_backlog(sk)) {
process_backlog = false;
goto restart;
}
first_skb = skb_queue_empty(&sk->sk_write_queue);
skb = sk_stream_alloc_skb(sk,
select_size(sk, sg, first_skb),
sk->sk_allocation,
first_skb);
if (!skb)
goto wait_for_memory;
process_backlog = true;
/*
* Check whether we can use HW checksum.
*/
if (sk_check_csum_caps(sk))
skb->ip_summed = CHECKSUM_PARTIAL;
skb_entail(sk, skb);
copy = size_goal;
max = size_goal;
/* All packets are restored as if they have
* already been sent. skb_mstamp isn't set to
* avoid wrong rtt estimation.
*/
if (tp->repair)
TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED;
}
/* Try to append data to the end of skb. */
if (copy > msg_data_left(msg))
copy = msg_data_left(msg);
/* Where to copy to? */
if (skb_availroom(skb) > 0) {
/* We have some space in skb head. Superb! */
copy = min_t(int, copy, skb_availroom(skb));
err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy);
if (err)
goto do_fault;
} else {
bool merge = true;
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
if (!sk_page_frag_refill(sk, pfrag))
goto wait_for_memory;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
if (i >= sysctl_max_skb_frags || !sg) {
tcp_mark_push(tp, skb);
goto new_segment;
}
merge = false;
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (!sk_wmem_schedule(sk, copy))
goto wait_for_memory;
err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
pfrag->page,
pfrag->offset,
copy);
if (err)
goto do_error;
/* Update the skb. */
if (merge) {
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
} else {
skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, copy);
get_page(pfrag->page);
}
pfrag->offset += copy;
}
if (!copied)
TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH;
tp->write_seq += copy;
TCP_SKB_CB(skb)->end_seq += copy;
tcp_skb_pcount_set(skb, 0);
copied += copy;
if (!msg_data_left(msg)) {
tcp_tx_timestamp(sk, sockc.tsflags, skb);
if (unlikely(flags & MSG_EOR))
TCP_SKB_CB(skb)->eor = 1;
goto out;
}
if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair))
continue;
if (forced_push(tp)) {
tcp_mark_push(tp, skb);
__tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH);
} else if (skb == tcp_send_head(sk))
tcp_push_one(sk, mss_now);
continue;
wait_for_sndbuf:
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
wait_for_memory:
if (copied)
tcp_push(sk, flags & ~MSG_MORE, mss_now,
TCP_NAGLE_PUSH, size_goal);
err = sk_stream_wait_memory(sk, &timeo);
if (err != 0)
goto do_error;
mss_now = tcp_send_mss(sk, &size_goal, flags);
}
out:
if (copied)
tcp_push(sk, flags, mss_now, tp->nonagle, size_goal);
out_nopush:
release_sock(sk);
return copied + copied_syn;
do_fault:
if (!skb->len) {
tcp_unlink_write_queue(skb, sk);
/* It is the one place in all of TCP, except connection
* reset, where we can be unlinking the send_head.
*/
tcp_check_send_head(sk, skb);
sk_wmem_free_skb(sk, skb);
}
do_error:
if (copied + copied_syn)
goto out;
out_err:
err = sk_stream_error(sk, flags, err);
/* make sure we wake any epoll edge trigger waiter */
if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
err == -EAGAIN)) {
sk->sk_write_space(sk);
tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
}
release_sock(sk);
return err;
}
EXPORT_SYMBOL(tcp_sendmsg);
/*
* Handle reading urgent data. BSD has very simple semantics for
* this, no blocking and very strange errors 8)
*/
static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags)
{
struct tcp_sock *tp = tcp_sk(sk);
/* No URG data to read. */
if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data ||
tp->urg_data == TCP_URG_READ)
return -EINVAL; /* Yes this is right ! */
if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE))
return -ENOTCONN;
if (tp->urg_data & TCP_URG_VALID) {
int err = 0;
char c = tp->urg_data;
if (!(flags & MSG_PEEK))
tp->urg_data = TCP_URG_READ;
/* Read urgent data. */
msg->msg_flags |= MSG_OOB;
if (len > 0) {
if (!(flags & MSG_TRUNC))
err = memcpy_to_msg(msg, &c, 1);
len = 1;
} else
msg->msg_flags |= MSG_TRUNC;
return err ? -EFAULT : len;
}
if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN))
return 0;
/* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and
* the available implementations agree in this case:
* this call should never block, independent of the
* blocking state of the socket.
* Mike <pall@rz.uni-karlsruhe.de>
*/
return -EAGAIN;
}
static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len)
{
struct sk_buff *skb;
int copied = 0, err = 0;
/* XXX -- need to support SO_PEEK_OFF */
skb_queue_walk(&sk->sk_write_queue, skb) {
err = skb_copy_datagram_msg(skb, 0, msg, skb->len);
if (err)
break;
copied += skb->len;
}
return err ?: copied;
}
/* Clean up the receive buffer for full frames taken by the user,
* then send an ACK if necessary. COPIED is the number of bytes
* tcp_recvmsg has given to the user so far, it speeds up the
* calculation of whether or not we must ACK for the sake of
* a window update.
*/
static void tcp_cleanup_rbuf(struct sock *sk, int copied)
{
struct tcp_sock *tp = tcp_sk(sk);
bool time_to_ack = false;
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq),
"cleanup rbuf bug: copied %X seq %X rcvnxt %X\n",
tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt);
if (inet_csk_ack_scheduled(sk)) {
const struct inet_connection_sock *icsk = inet_csk(sk);
/* Delayed ACKs frequently hit locked sockets during bulk
* receive. */
if (icsk->icsk_ack.blocked ||
/* Once-per-two-segments ACK was not sent by tcp_input.c */
tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss ||
/*
* If this read emptied read buffer, we send ACK, if
* connection is not bidirectional, user drained
* receive buffer and there was a small segment
* in queue.
*/
(copied > 0 &&
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) ||
((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) &&
!icsk->icsk_ack.pingpong)) &&
!atomic_read(&sk->sk_rmem_alloc)))
time_to_ack = true;
}
/* We send an ACK if we can now advertise a non-zero window
* which has been raised "significantly".
*
* Even if window raised up to infinity, do not send window open ACK
* in states, where we will not receive more. It is useless.
*/
if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) {
__u32 rcv_window_now = tcp_receive_window(tp);
/* Optimize, __tcp_select_window() is not cheap. */
if (2*rcv_window_now <= tp->window_clamp) {
__u32 new_window = __tcp_select_window(sk);
/* Send ACK now, if this read freed lots of space
* in our buffer. Certainly, new_window is new window.
* We can advertise it now, if it is not less than current one.
* "Lots" means "at least twice" here.
*/
if (new_window && new_window >= 2 * rcv_window_now)
time_to_ack = true;
}
}
if (time_to_ack)
tcp_send_ack(sk);
}
static void tcp_prequeue_process(struct sock *sk)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPREQUEUED);
while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
sk_backlog_rcv(sk, skb);
/* Clear memory counter. */
tp->ucopy.memory = 0;
}
static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off)
{
struct sk_buff *skb;
u32 offset;
while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) {
offset = seq - TCP_SKB_CB(skb)->seq;
if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
pr_err_once("%s: found a SYN, please report !\n", __func__);
offset--;
}
if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) {
*off = offset;
return skb;
}
/* This looks weird, but this can happen if TCP collapsing
* splitted a fat GRO packet, while we released socket lock
* in skb_splice_bits()
*/
sk_eat_skb(sk, skb);
}
return NULL;
}
/*
* This routine provides an alternative to tcp_recvmsg() for routines
* that would like to handle copying from skbuffs directly in 'sendfile'
* fashion.
* Note:
* - It is assumed that the socket was locked by the caller.
* - The routine does not block.
* - At present, there is no support for reading OOB data
* or for 'peeking' the socket using this routine
* (although both would be easy to implement).
*/
int tcp_read_sock(struct sock *sk, read_descriptor_t *desc,
sk_read_actor_t recv_actor)
{
struct sk_buff *skb;
struct tcp_sock *tp = tcp_sk(sk);
u32 seq = tp->copied_seq;
u32 offset;
int copied = 0;
if (sk->sk_state == TCP_LISTEN)
return -ENOTCONN;
while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) {
if (offset < skb->len) {
int used;
size_t len;
len = skb->len - offset;
/* Stop reading if we hit a patch of urgent data */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - seq;
if (urg_offset < len)
len = urg_offset;
if (!len)
break;
}
used = recv_actor(desc, skb, offset, len);
if (used <= 0) {
if (!copied)
copied = used;
break;
} else if (used <= len) {
seq += used;
copied += used;
offset += used;
}
/* If recv_actor drops the lock (e.g. TCP splice
* receive) the skb pointer might be invalid when
* getting here: tcp_collapse might have deleted it
* while aggregating skbs from the socket queue.
*/
skb = tcp_recv_skb(sk, seq - 1, &offset);
if (!skb)
break;
/* TCP coalescing might have appended data to the skb.
* Try to splice more frags
*/
if (offset + 1 != skb->len)
continue;
}
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) {
sk_eat_skb(sk, skb);
++seq;
break;
}
sk_eat_skb(sk, skb);
if (!desc->count)
break;
tp->copied_seq = seq;
}
tp->copied_seq = seq;
tcp_rcv_space_adjust(sk);
/* Clean up data we have read: This will do ACK frames. */
if (copied > 0) {
tcp_recv_skb(sk, seq, &offset);
tcp_cleanup_rbuf(sk, copied);
}
return copied;
}
EXPORT_SYMBOL(tcp_read_sock);
int tcp_peek_len(struct socket *sock)
{
return tcp_inq(sock->sk);
}
EXPORT_SYMBOL(tcp_peek_len);
/*
* This routine copies from a sock struct into the user buffer.
*
* Technical note: in 2.3 we work on _locked_ socket, so that
* tricks with *seq access order and skb->users are not required.
* Probably, code can be easily improved even more.
*/
int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock,
int flags, int *addr_len)
{
struct tcp_sock *tp = tcp_sk(sk);
int copied = 0;
u32 peek_seq;
u32 *seq;
unsigned long used;
int err;
int target; /* Read at least this many bytes */
long timeo;
struct task_struct *user_recv = NULL;
struct sk_buff *skb, *last;
u32 urg_hole = 0;
if (unlikely(flags & MSG_ERRQUEUE))
return inet_recv_error(sk, msg, len, addr_len);
if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) &&
(sk->sk_state == TCP_ESTABLISHED))
sk_busy_loop(sk, nonblock);
lock_sock(sk);
err = -ENOTCONN;
if (sk->sk_state == TCP_LISTEN)
goto out;
timeo = sock_rcvtimeo(sk, nonblock);
/* Urgent data needs to be handled specially. */
if (flags & MSG_OOB)
goto recv_urg;
if (unlikely(tp->repair)) {
err = -EPERM;
if (!(flags & MSG_PEEK))
goto out;
if (tp->repair_queue == TCP_SEND_QUEUE)
goto recv_sndq;
err = -EINVAL;
if (tp->repair_queue == TCP_NO_QUEUE)
goto out;
/* 'common' recv queue MSG_PEEK-ing */
}
seq = &tp->copied_seq;
if (flags & MSG_PEEK) {
peek_seq = tp->copied_seq;
seq = &peek_seq;
}
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
do {
u32 offset;
/* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */
if (tp->urg_data && tp->urg_seq == *seq) {
if (copied)
break;
if (signal_pending(current)) {
copied = timeo ? sock_intr_errno(timeo) : -EAGAIN;
break;
}
}
/* Next get a buffer. */
last = skb_peek_tail(&sk->sk_receive_queue);
skb_queue_walk(&sk->sk_receive_queue, skb) {
last = skb;
/* Now that we have two receive queues this
* shouldn't happen.
*/
if (WARN(before(*seq, TCP_SKB_CB(skb)->seq),
"recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n",
*seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt,
flags))
break;
offset = *seq - TCP_SKB_CB(skb)->seq;
if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) {
pr_err_once("%s: found a SYN, please report !\n", __func__);
offset--;
}
if (offset < skb->len)
goto found_ok_skb;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
goto found_fin_ok;
WARN(!(flags & MSG_PEEK),
"recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n",
*seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags);
}
/* Well, if we have backlog, try to process it now yet. */
if (copied >= target && !sk->sk_backlog.tail)
break;
if (copied) {
if (sk->sk_err ||
sk->sk_state == TCP_CLOSE ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
!timeo ||
signal_pending(current))
break;
} else {
if (sock_flag(sk, SOCK_DONE))
break;
if (sk->sk_err) {
copied = sock_error(sk);
break;
}
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
if (sk->sk_state == TCP_CLOSE) {
if (!sock_flag(sk, SOCK_DONE)) {
/* This occurs when user tries to read
* from never connected socket.
*/
copied = -ENOTCONN;
break;
}
break;
}
if (!timeo) {
copied = -EAGAIN;
break;
}
if (signal_pending(current)) {
copied = sock_intr_errno(timeo);
break;
}
}
tcp_cleanup_rbuf(sk, copied);
if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) {
/* Install new reader */
if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) {
user_recv = current;
tp->ucopy.task = user_recv;
tp->ucopy.msg = msg;
}
tp->ucopy.len = len;
WARN_ON(tp->copied_seq != tp->rcv_nxt &&
!(flags & (MSG_PEEK | MSG_TRUNC)));
/* Ugly... If prequeue is not empty, we have to
* process it before releasing socket, otherwise
* order will be broken at second iteration.
* More elegant solution is required!!!
*
* Look: we have the following (pseudo)queues:
*
* 1. packets in flight
* 2. backlog
* 3. prequeue
* 4. receive_queue
*
* Each queue can be processed only if the next ones
* are empty. At this point we have empty receive_queue.
* But prequeue _can_ be not empty after 2nd iteration,
* when we jumped to start of loop because backlog
* processing added something to receive_queue.
* We cannot release_sock(), because backlog contains
* packets arrived _after_ prequeued ones.
*
* Shortly, algorithm is clear --- to process all
* the queues in order. We could make it more directly,
* requeueing packets from backlog to prequeue, if
* is not empty. It is more elegant, but eats cycles,
* unfortunately.
*/
if (!skb_queue_empty(&tp->ucopy.prequeue))
goto do_prequeue;
/* __ Set realtime policy in scheduler __ */
}
if (copied >= target) {
/* Do not sleep, just process backlog. */
release_sock(sk);
lock_sock(sk);
} else {
sk_wait_data(sk, &timeo, last);
}
if (user_recv) {
int chunk;
/* __ Restore normal policy in scheduler __ */
chunk = len - tp->ucopy.len;
if (chunk != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk);
len -= chunk;
copied += chunk;
}
if (tp->rcv_nxt == tp->copied_seq &&
!skb_queue_empty(&tp->ucopy.prequeue)) {
do_prequeue:
tcp_prequeue_process(sk);
chunk = len - tp->ucopy.len;
if (chunk != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
len -= chunk;
copied += chunk;
}
}
}
if ((flags & MSG_PEEK) &&
(peek_seq - copied - urg_hole != tp->copied_seq)) {
net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n",
current->comm,
task_pid_nr(current));
peek_seq = tp->copied_seq;
}
continue;
found_ok_skb:
/* Ok so how much can we use? */
used = skb->len - offset;
if (len < used)
used = len;
/* Do we have urgent data here? */
if (tp->urg_data) {
u32 urg_offset = tp->urg_seq - *seq;
if (urg_offset < used) {
if (!urg_offset) {
if (!sock_flag(sk, SOCK_URGINLINE)) {
++*seq;
urg_hole++;
offset++;
used--;
if (!used)
goto skip_copy;
}
} else
used = urg_offset;
}
}
if (!(flags & MSG_TRUNC)) {
err = skb_copy_datagram_msg(skb, offset, msg, used);
if (err) {
/* Exception. Bailout! */
if (!copied)
copied = -EFAULT;
break;
}
}
*seq += used;
copied += used;
len -= used;
tcp_rcv_space_adjust(sk);
skip_copy:
if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) {
tp->urg_data = 0;
tcp_fast_path_check(sk);
}
if (used + offset < skb->len)
continue;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
goto found_fin_ok;
if (!(flags & MSG_PEEK))
sk_eat_skb(sk, skb);
continue;
found_fin_ok:
/* Process the FIN. */
++*seq;
if (!(flags & MSG_PEEK))
sk_eat_skb(sk, skb);
break;
} while (len > 0);
if (user_recv) {
if (!skb_queue_empty(&tp->ucopy.prequeue)) {
int chunk;
tp->ucopy.len = copied > 0 ? len : 0;
tcp_prequeue_process(sk);
if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) {
NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk);
len -= chunk;
copied += chunk;
}
}
tp->ucopy.task = NULL;
tp->ucopy.len = 0;
}
/* According to UNIX98, msg_name/msg_namelen are ignored
* on connected socket. I was just happy when found this 8) --ANK
*/
/* Clean up data we have read: This will do ACK frames. */
tcp_cleanup_rbuf(sk, copied);
release_sock(sk);
return copied;
out:
release_sock(sk);
return err;
recv_urg:
err = tcp_recv_urg(sk, msg, len, flags);
goto out;
recv_sndq:
err = tcp_peek_sndq(sk, msg, len);
goto out;
}
EXPORT_SYMBOL(tcp_recvmsg);
void tcp_set_state(struct sock *sk, int state)
{
int oldstate = sk->sk_state;
switch (state) {
case TCP_ESTABLISHED:
if (oldstate != TCP_ESTABLISHED)
TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
break;
case TCP_CLOSE:
if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED)
TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS);
sk->sk_prot->unhash(sk);
if (inet_csk(sk)->icsk_bind_hash &&
!(sk->sk_userlocks & SOCK_BINDPORT_LOCK))
inet_put_port(sk);
/* fall through */
default:
if (oldstate == TCP_ESTABLISHED)
TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB);
}
/* Change state AFTER socket is unhashed to avoid closed
* socket sitting in hash tables.
*/
sk_state_store(sk, state);
#ifdef STATE_TRACE
SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]);
#endif
}
EXPORT_SYMBOL_GPL(tcp_set_state);
/*
* State processing on a close. This implements the state shift for
* sending our FIN frame. Note that we only send a FIN for some
* states. A shutdown() may have already sent the FIN, or we may be
* closed.
*/
static const unsigned char new_state[16] = {
/* current state: new state: action: */
[0 /* (Invalid) */] = TCP_CLOSE,
[TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
[TCP_SYN_SENT] = TCP_CLOSE,
[TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN,
[TCP_FIN_WAIT1] = TCP_FIN_WAIT1,
[TCP_FIN_WAIT2] = TCP_FIN_WAIT2,
[TCP_TIME_WAIT] = TCP_CLOSE,
[TCP_CLOSE] = TCP_CLOSE,
[TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN,
[TCP_LAST_ACK] = TCP_LAST_ACK,
[TCP_LISTEN] = TCP_CLOSE,
[TCP_CLOSING] = TCP_CLOSING,
[TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */
};
static int tcp_close_state(struct sock *sk)
{
int next = (int)new_state[sk->sk_state];
int ns = next & TCP_STATE_MASK;
tcp_set_state(sk, ns);
return next & TCP_ACTION_FIN;
}
/*
* Shutdown the sending side of a connection. Much like close except
* that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD).
*/
void tcp_shutdown(struct sock *sk, int how)
{
/* We need to grab some memory, and put together a FIN,
* and then put it into the queue to be sent.
* Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92.
*/
if (!(how & SEND_SHUTDOWN))
return;
/* If we've already sent a FIN, or it's a closed state, skip this. */
if ((1 << sk->sk_state) &
(TCPF_ESTABLISHED | TCPF_SYN_SENT |
TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) {
/* Clear out any half completed packets. FIN if needed. */
if (tcp_close_state(sk))
tcp_send_fin(sk);
}
}
EXPORT_SYMBOL(tcp_shutdown);
bool tcp_check_oom(struct sock *sk, int shift)
{
bool too_many_orphans, out_of_socket_memory;
too_many_orphans = tcp_too_many_orphans(sk, shift);
out_of_socket_memory = tcp_out_of_memory(sk);
if (too_many_orphans)
net_info_ratelimited("too many orphaned sockets\n");
if (out_of_socket_memory)
net_info_ratelimited("out of memory -- consider tuning tcp_mem\n");
return too_many_orphans || out_of_socket_memory;
}
void tcp_close(struct sock *sk, long timeout)
{
struct sk_buff *skb;
int data_was_unread = 0;
int state;
lock_sock(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
if (sk->sk_state == TCP_LISTEN) {
tcp_set_state(sk, TCP_CLOSE);
/* Special case. */
inet_csk_listen_stop(sk);
goto adjudge_to_death;
}
/* We need to flush the recv. buffs. We do this only on the
* descriptor close, not protocol-sourced closes, because the
* reader process may not have drained the data yet!
*/
while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq;
if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
len--;
data_was_unread += len;
__kfree_skb(skb);
}
sk_mem_reclaim(sk);
/* If socket has been already reset (e.g. in tcp_reset()) - kill it. */
if (sk->sk_state == TCP_CLOSE)
goto adjudge_to_death;
/* As outlined in RFC 2525, section 2.17, we send a RST here because
* data was lost. To witness the awful effects of the old behavior of
* always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk
* GET in an FTP client, suspend the process, wait for the client to
* advertise a zero window, then kill -9 the FTP client, wheee...
* Note: timeout is always zero in such a case.
*/
if (unlikely(tcp_sk(sk)->repair)) {
sk->sk_prot->disconnect(sk, 0);
} else if (data_was_unread) {
/* Unread data was tossed, zap the connection. */
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE);
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, sk->sk_allocation);
} else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
/* Check zero linger _after_ checking for unread data. */
sk->sk_prot->disconnect(sk, 0);
NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
} else if (tcp_close_state(sk)) {
/* We FIN if the application ate all the data before
* zapping the connection.
*/
/* RED-PEN. Formally speaking, we have broken TCP state
* machine. State transitions:
*
* TCP_ESTABLISHED -> TCP_FIN_WAIT1
* TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible)
* TCP_CLOSE_WAIT -> TCP_LAST_ACK
*
* are legal only when FIN has been sent (i.e. in window),
* rather than queued out of window. Purists blame.
*
* F.e. "RFC state" is ESTABLISHED,
* if Linux state is FIN-WAIT-1, but FIN is still not sent.
*
* The visible declinations are that sometimes
* we enter time-wait state, when it is not required really
* (harmless), do not send active resets, when they are
* required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when
* they look as CLOSING or LAST_ACK for Linux)
* Probably, I missed some more holelets.
* --ANK
* XXX (TFO) - To start off we don't support SYN+ACK+FIN
* in a single packet! (May consider it later but will
* probably need API support or TCP_CORK SYN-ACK until
* data is written and socket is closed.)
*/
tcp_send_fin(sk);
}
sk_stream_wait_close(sk, timeout);
adjudge_to_death:
state = sk->sk_state;
sock_hold(sk);
sock_orphan(sk);
/* It is the last release_sock in its life. It will remove backlog. */
release_sock(sk);
/* Now socket is owned by kernel and we acquire BH lock
to finish close. No need to check for user refs.
*/
local_bh_disable();
bh_lock_sock(sk);
WARN_ON(sock_owned_by_user(sk));
percpu_counter_inc(sk->sk_prot->orphan_count);
/* Have we already been destroyed by a softirq or backlog? */
if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE)
goto out;
/* This is a (useful) BSD violating of the RFC. There is a
* problem with TCP as specified in that the other end could
* keep a socket open forever with no application left this end.
* We use a 1 minute timeout (about the same as BSD) then kill
* our end. If they send after that then tough - BUT: long enough
* that we won't make the old 4*rto = almost no time - whoops
* reset mistake.
*
* Nope, it was not mistake. It is really desired behaviour
* f.e. on http servers, when such sockets are useless, but
* consume significant resources. Let's do it with special
* linger2 option. --ANK
*/
if (sk->sk_state == TCP_FIN_WAIT2) {
struct tcp_sock *tp = tcp_sk(sk);
if (tp->linger2 < 0) {
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, GFP_ATOMIC);
__NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPABORTONLINGER);
} else {
const int tmo = tcp_fin_time(sk);
if (tmo > TCP_TIMEWAIT_LEN) {
inet_csk_reset_keepalive_timer(sk,
tmo - TCP_TIMEWAIT_LEN);
} else {
tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
goto out;
}
}
}
if (sk->sk_state != TCP_CLOSE) {
sk_mem_reclaim(sk);
if (tcp_check_oom(sk, 0)) {
tcp_set_state(sk, TCP_CLOSE);
tcp_send_active_reset(sk, GFP_ATOMIC);
__NET_INC_STATS(sock_net(sk),
LINUX_MIB_TCPABORTONMEMORY);
}
}
if (sk->sk_state == TCP_CLOSE) {
struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
/* We could get here with a non-NULL req if the socket is
* aborted (e.g., closed with unread data) before 3WHS
* finishes.
*/
if (req)
reqsk_fastopen_remove(sk, req, false);
inet_csk_destroy_sock(sk);
}
/* Otherwise, socket is reprieved until protocol close. */
out:
bh_unlock_sock(sk);
local_bh_enable();
sock_put(sk);
}
EXPORT_SYMBOL(tcp_close);
/* These states need RST on ABORT according to RFC793 */
static inline bool tcp_need_reset(int state)
{
return (1 << state) &
(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 |
TCPF_FIN_WAIT2 | TCPF_SYN_RECV);
}
int tcp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int err = 0;
int old_state = sk->sk_state;
if (old_state != TCP_CLOSE)
tcp_set_state(sk, TCP_CLOSE);
/* ABORT function of RFC793 */
if (old_state == TCP_LISTEN) {
inet_csk_listen_stop(sk);
} else if (unlikely(tp->repair)) {
sk->sk_err = ECONNABORTED;
} else if (tcp_need_reset(old_state) ||
(tp->snd_nxt != tp->write_seq &&
(1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
/* The last check adjusts for discrepancy of Linux wrt. RFC
* states
*/
tcp_send_active_reset(sk, gfp_any());
sk->sk_err = ECONNRESET;
} else if (old_state == TCP_SYN_SENT)
sk->sk_err = ECONNRESET;
tcp_clear_xmit_timers(sk);
__skb_queue_purge(&sk->sk_receive_queue);
tcp_write_queue_purge(sk);
skb_rbtree_purge(&tp->out_of_order_queue);
inet->inet_dport = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
sk->sk_shutdown = 0;
sock_reset_flag(sk, SOCK_DONE);
tp->srtt_us = 0;
tp->write_seq += tp->max_window + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
icsk->icsk_backoff = 0;
tp->snd_cwnd = 2;
icsk->icsk_probes_out = 0;
tp->packets_out = 0;
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_cnt = 0;
tp->window_clamp = 0;
tcp_set_ca_state(sk, TCP_CA_Open);
tcp_clear_retrans(tp);
inet_csk_delack_init(sk);
tcp_init_send_head(sk);
memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
__sk_dst_reset(sk);
WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
sk->sk_error_report(sk);
return err;
}
EXPORT_SYMBOL(tcp_disconnect);
static inline bool tcp_can_repair_sock(const struct sock *sk)
{
return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) &&
(sk->sk_state != TCP_LISTEN);
}
static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len)
{
struct tcp_repair_window opt;
if (!tp->repair)
return -EPERM;
if (len != sizeof(opt))
return -EINVAL;
if (copy_from_user(&opt, optbuf, sizeof(opt)))
return -EFAULT;
if (opt.max_window < opt.snd_wnd)
return -EINVAL;
if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd))
return -EINVAL;
if (after(opt.rcv_wup, tp->rcv_nxt))
return -EINVAL;
tp->snd_wl1 = opt.snd_wl1;
tp->snd_wnd = opt.snd_wnd;
tp->max_window = opt.max_window;
tp->rcv_wnd = opt.rcv_wnd;
tp->rcv_wup = opt.rcv_wup;
return 0;
}
static int tcp_repair_options_est(struct tcp_sock *tp,
struct tcp_repair_opt __user *optbuf, unsigned int len)
{
struct tcp_repair_opt opt;
while (len >= sizeof(opt)) {
if (copy_from_user(&opt, optbuf, sizeof(opt)))
return -EFAULT;
optbuf++;
len -= sizeof(opt);
switch (opt.opt_code) {
case TCPOPT_MSS:
tp->rx_opt.mss_clamp = opt.opt_val;
break;
case TCPOPT_WINDOW:
{
u16 snd_wscale = opt.opt_val & 0xFFFF;
u16 rcv_wscale = opt.opt_val >> 16;
if (snd_wscale > 14 || rcv_wscale > 14)
return -EFBIG;
tp->rx_opt.snd_wscale = snd_wscale;
tp->rx_opt.rcv_wscale = rcv_wscale;
tp->rx_opt.wscale_ok = 1;
}
break;
case TCPOPT_SACK_PERM:
if (opt.opt_val != 0)
return -EINVAL;
tp->rx_opt.sack_ok |= TCP_SACK_SEEN;
if (sysctl_tcp_fack)
tcp_enable_fack(tp);
break;
case TCPOPT_TIMESTAMP:
if (opt.opt_val != 0)
return -EINVAL;
tp->rx_opt.tstamp_ok = 1;
break;
}
}
return 0;
}
/*
* Socket option code for TCP.
*/
static int do_tcp_setsockopt(struct sock *sk, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct net *net = sock_net(sk);
int val;
int err = 0;
/* These are data/string values, all the others are ints */
switch (optname) {
case TCP_CONGESTION: {
char name[TCP_CA_NAME_MAX];
if (optlen < 1)
return -EINVAL;
val = strncpy_from_user(name, optval,
min_t(long, TCP_CA_NAME_MAX-1, optlen));
if (val < 0)
return -EFAULT;
name[val] = 0;
lock_sock(sk);
err = tcp_set_congestion_control(sk, name);
release_sock(sk);
return err;
}
default:
/* fallthru */
break;
}
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case TCP_MAXSEG:
/* Values greater than interface MTU won't take effect. However
* at the point when this call is done we typically don't yet
* know which interface is going to be used */
if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) {
err = -EINVAL;
break;
}
tp->rx_opt.user_mss = val;
break;
case TCP_NODELAY:
if (val) {
/* TCP_NODELAY is weaker than TCP_CORK, so that
* this option on corked socket is remembered, but
* it is not activated until cork is cleared.
*
* However, when TCP_NODELAY is set we make
* an explicit push, which overrides even TCP_CORK
* for currently queued segments.
*/
tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH;
tcp_push_pending_frames(sk);
} else {
tp->nonagle &= ~TCP_NAGLE_OFF;
}
break;
case TCP_THIN_LINEAR_TIMEOUTS:
if (val < 0 || val > 1)
err = -EINVAL;
else
tp->thin_lto = val;
break;
case TCP_THIN_DUPACK:
if (val < 0 || val > 1)
err = -EINVAL;
else {
tp->thin_dupack = val;
if (tp->thin_dupack)
tcp_disable_early_retrans(tp);
}
break;
case TCP_REPAIR:
if (!tcp_can_repair_sock(sk))
err = -EPERM;
else if (val == 1) {
tp->repair = 1;
sk->sk_reuse = SK_FORCE_REUSE;
tp->repair_queue = TCP_NO_QUEUE;
} else if (val == 0) {
tp->repair = 0;
sk->sk_reuse = SK_NO_REUSE;
tcp_send_window_probe(sk);
} else
err = -EINVAL;
break;
case TCP_REPAIR_QUEUE:
if (!tp->repair)
err = -EPERM;
else if (val < TCP_QUEUES_NR)
tp->repair_queue = val;
else
err = -EINVAL;
break;
case TCP_QUEUE_SEQ:
if (sk->sk_state != TCP_CLOSE)
err = -EPERM;
else if (tp->repair_queue == TCP_SEND_QUEUE)
tp->write_seq = val;
else if (tp->repair_queue == TCP_RECV_QUEUE)
tp->rcv_nxt = val;
else
err = -EINVAL;
break;
case TCP_REPAIR_OPTIONS:
if (!tp->repair)
err = -EINVAL;
else if (sk->sk_state == TCP_ESTABLISHED)
err = tcp_repair_options_est(tp,
(struct tcp_repair_opt __user *)optval,
optlen);
else
err = -EPERM;
break;
case TCP_CORK:
/* When set indicates to always queue non-full frames.
* Later the user clears this option and we transmit
* any pending partial frames in the queue. This is
* meant to be used alongside sendfile() to get properly
* filled frames when the user (for example) must write
* out headers with a write() call first and then use
* sendfile to send out the data parts.
*
* TCP_CORK can be set together with TCP_NODELAY and it is
* stronger than TCP_NODELAY.
*/
if (val) {
tp->nonagle |= TCP_NAGLE_CORK;
} else {
tp->nonagle &= ~TCP_NAGLE_CORK;
if (tp->nonagle&TCP_NAGLE_OFF)
tp->nonagle |= TCP_NAGLE_PUSH;
tcp_push_pending_frames(sk);
}
break;
case TCP_KEEPIDLE:
if (val < 1 || val > MAX_TCP_KEEPIDLE)
err = -EINVAL;
else {
tp->keepalive_time = val * HZ;
if (sock_flag(sk, SOCK_KEEPOPEN) &&
!((1 << sk->sk_state) &
(TCPF_CLOSE | TCPF_LISTEN))) {
u32 elapsed = keepalive_time_elapsed(tp);
if (tp->keepalive_time > elapsed)
elapsed = tp->keepalive_time - elapsed;
else
elapsed = 0;
inet_csk_reset_keepalive_timer(sk, elapsed);
}
}
break;
case TCP_KEEPINTVL:
if (val < 1 || val > MAX_TCP_KEEPINTVL)
err = -EINVAL;
else
tp->keepalive_intvl = val * HZ;
break;
case TCP_KEEPCNT:
if (val < 1 || val > MAX_TCP_KEEPCNT)
err = -EINVAL;
else
tp->keepalive_probes = val;
break;
case TCP_SYNCNT:
if (val < 1 || val > MAX_TCP_SYNCNT)
err = -EINVAL;
else
icsk->icsk_syn_retries = val;
break;
case TCP_SAVE_SYN:
if (val < 0 || val > 1)
err = -EINVAL;
else
tp->save_syn = val;
break;
case TCP_LINGER2:
if (val < 0)
tp->linger2 = -1;
else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ)
tp->linger2 = 0;
else
tp->linger2 = val * HZ;
break;
case TCP_DEFER_ACCEPT:
/* Translate value in seconds to number of retransmits */
icsk->icsk_accept_queue.rskq_defer_accept =
secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ,
TCP_RTO_MAX / HZ);
break;
case TCP_WINDOW_CLAMP:
if (!val) {
if (sk->sk_state != TCP_CLOSE) {
err = -EINVAL;
break;
}
tp->window_clamp = 0;
} else
tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ?
SOCK_MIN_RCVBUF / 2 : val;
break;
case TCP_QUICKACK:
if (!val) {
icsk->icsk_ack.pingpong = 1;
} else {
icsk->icsk_ack.pingpong = 0;
if ((1 << sk->sk_state) &
(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) &&
inet_csk_ack_scheduled(sk)) {
icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
tcp_cleanup_rbuf(sk, 1);
if (!(val & 1))
icsk->icsk_ack.pingpong = 1;
}
}
break;
#ifdef CONFIG_TCP_MD5SIG
case TCP_MD5SIG:
/* Read the IP->Key mappings from userspace */
err = tp->af_specific->md5_parse(sk, optval, optlen);
break;
#endif
case TCP_USER_TIMEOUT:
/* Cap the max time in ms TCP will retry or probe the window
* before giving up and aborting (ETIMEDOUT) a connection.
*/
if (val < 0)
err = -EINVAL;
else
icsk->icsk_user_timeout = msecs_to_jiffies(val);
break;
case TCP_FASTOPEN:
if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE |
TCPF_LISTEN))) {
tcp_fastopen_init_key_once(true);
fastopen_queue_tune(sk, val);
} else {
err = -EINVAL;
}
break;
case TCP_TIMESTAMP:
if (!tp->repair)
err = -EPERM;
else
tp->tsoffset = val - tcp_time_stamp;
break;
case TCP_REPAIR_WINDOW:
err = tcp_repair_set_window(tp, optval, optlen);
break;
case TCP_NOTSENT_LOWAT:
tp->notsent_lowat = val;
sk->sk_write_space(sk);
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval,
unsigned int optlen)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (level != SOL_TCP)
return icsk->icsk_af_ops->setsockopt(sk, level, optname,
optval, optlen);
return do_tcp_setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(tcp_setsockopt);
#ifdef CONFIG_COMPAT
int compat_tcp_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_TCP)
return inet_csk_compat_setsockopt(sk, level, optname,
optval, optlen);
return do_tcp_setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_tcp_setsockopt);
#endif
static void tcp_get_info_chrono_stats(const struct tcp_sock *tp,
struct tcp_info *info)
{
u64 stats[__TCP_CHRONO_MAX], total = 0;
enum tcp_chrono i;
for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) {
stats[i] = tp->chrono_stat[i - 1];
if (i == tp->chrono_type)
stats[i] += tcp_time_stamp - tp->chrono_start;
stats[i] *= USEC_PER_SEC / HZ;
total += stats[i];
}
info->tcpi_busy_time = total;
info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED];
info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED];
}
/* Return information about state of tcp endpoint in API format. */
void tcp_get_info(struct sock *sk, struct tcp_info *info)
{
const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */
const struct inet_connection_sock *icsk = inet_csk(sk);
u32 now = tcp_time_stamp, intv;
u64 rate64;
bool slow;
u32 rate;
memset(info, 0, sizeof(*info));
if (sk->sk_type != SOCK_STREAM)
return;
info->tcpi_state = sk_state_load(sk);
/* Report meaningful fields for all TCP states, including listeners */
rate = READ_ONCE(sk->sk_pacing_rate);
rate64 = rate != ~0U ? rate : ~0ULL;
info->tcpi_pacing_rate = rate64;
rate = READ_ONCE(sk->sk_max_pacing_rate);
rate64 = rate != ~0U ? rate : ~0ULL;
info->tcpi_max_pacing_rate = rate64;
info->tcpi_reordering = tp->reordering;
info->tcpi_snd_cwnd = tp->snd_cwnd;
if (info->tcpi_state == TCP_LISTEN) {
/* listeners aliased fields :
* tcpi_unacked -> Number of children ready for accept()
* tcpi_sacked -> max backlog
*/
info->tcpi_unacked = sk->sk_ack_backlog;
info->tcpi_sacked = sk->sk_max_ack_backlog;
return;
}
info->tcpi_ca_state = icsk->icsk_ca_state;
info->tcpi_retransmits = icsk->icsk_retransmits;
info->tcpi_probes = icsk->icsk_probes_out;
info->tcpi_backoff = icsk->icsk_backoff;
if (tp->rx_opt.tstamp_ok)
info->tcpi_options |= TCPI_OPT_TIMESTAMPS;
if (tcp_is_sack(tp))
info->tcpi_options |= TCPI_OPT_SACK;
if (tp->rx_opt.wscale_ok) {
info->tcpi_options |= TCPI_OPT_WSCALE;
info->tcpi_snd_wscale = tp->rx_opt.snd_wscale;
info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale;
}
if (tp->ecn_flags & TCP_ECN_OK)
info->tcpi_options |= TCPI_OPT_ECN;
if (tp->ecn_flags & TCP_ECN_SEEN)
info->tcpi_options |= TCPI_OPT_ECN_SEEN;
if (tp->syn_data_acked)
info->tcpi_options |= TCPI_OPT_SYN_DATA;
info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto);
info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato);
info->tcpi_snd_mss = tp->mss_cache;
info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss;
info->tcpi_unacked = tp->packets_out;
info->tcpi_sacked = tp->sacked_out;
info->tcpi_lost = tp->lost_out;
info->tcpi_retrans = tp->retrans_out;
info->tcpi_fackets = tp->fackets_out;
info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime);
info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime);
info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp);
info->tcpi_pmtu = icsk->icsk_pmtu_cookie;
info->tcpi_rcv_ssthresh = tp->rcv_ssthresh;
info->tcpi_rtt = tp->srtt_us >> 3;
info->tcpi_rttvar = tp->mdev_us >> 2;
info->tcpi_snd_ssthresh = tp->snd_ssthresh;
info->tcpi_advmss = tp->advmss;
info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3;
info->tcpi_rcv_space = tp->rcvq_space.space;
info->tcpi_total_retrans = tp->total_retrans;
slow = lock_sock_fast(sk);
info->tcpi_bytes_acked = tp->bytes_acked;
info->tcpi_bytes_received = tp->bytes_received;
info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt);
tcp_get_info_chrono_stats(tp, info);
unlock_sock_fast(sk, slow);
info->tcpi_segs_out = tp->segs_out;
info->tcpi_segs_in = tp->segs_in;
info->tcpi_min_rtt = tcp_min_rtt(tp);
info->tcpi_data_segs_in = tp->data_segs_in;
info->tcpi_data_segs_out = tp->data_segs_out;
info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0;
rate = READ_ONCE(tp->rate_delivered);
intv = READ_ONCE(tp->rate_interval_us);
if (rate && intv) {
rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC;
do_div(rate64, intv);
info->tcpi_delivery_rate = rate64;
}
}
EXPORT_SYMBOL_GPL(tcp_get_info);
struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk)
{
const struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *stats;
struct tcp_info info;
stats = alloc_skb(3 * nla_total_size_64bit(sizeof(u64)), GFP_ATOMIC);
if (!stats)
return NULL;
tcp_get_info_chrono_stats(tp, &info);
nla_put_u64_64bit(stats, TCP_NLA_BUSY,
info.tcpi_busy_time, TCP_NLA_PAD);
nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED,
info.tcpi_rwnd_limited, TCP_NLA_PAD);
nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED,
info.tcpi_sndbuf_limited, TCP_NLA_PAD);
return stats;
}
static int do_tcp_getsockopt(struct sock *sk, int level,
int optname, char __user *optval, int __user *optlen)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
struct net *net = sock_net(sk);
int val, len;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
switch (optname) {
case TCP_MAXSEG:
val = tp->mss_cache;
if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
val = tp->rx_opt.user_mss;
if (tp->repair)
val = tp->rx_opt.mss_clamp;
break;
case TCP_NODELAY:
val = !!(tp->nonagle&TCP_NAGLE_OFF);
break;
case TCP_CORK:
val = !!(tp->nonagle&TCP_NAGLE_CORK);
break;
case TCP_KEEPIDLE:
val = keepalive_time_when(tp) / HZ;
break;
case TCP_KEEPINTVL:
val = keepalive_intvl_when(tp) / HZ;
break;
case TCP_KEEPCNT:
val = keepalive_probes(tp);
break;
case TCP_SYNCNT:
val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries;
break;
case TCP_LINGER2:
val = tp->linger2;
if (val >= 0)
val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ;
break;
case TCP_DEFER_ACCEPT:
val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept,
TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ);
break;
case TCP_WINDOW_CLAMP:
val = tp->window_clamp;
break;
case TCP_INFO: {
struct tcp_info info;
if (get_user(len, optlen))
return -EFAULT;
tcp_get_info(sk, &info);
len = min_t(unsigned int, len, sizeof(info));
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
case TCP_CC_INFO: {
const struct tcp_congestion_ops *ca_ops;
union tcp_cc_info info;
size_t sz = 0;
int attr;
if (get_user(len, optlen))
return -EFAULT;
ca_ops = icsk->icsk_ca_ops;
if (ca_ops && ca_ops->get_info)
sz = ca_ops->get_info(sk, ~0U, &attr, &info);
len = min_t(unsigned int, len, sz);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &info, len))
return -EFAULT;
return 0;
}
case TCP_QUICKACK:
val = !icsk->icsk_ack.pingpong;
break;
case TCP_CONGESTION:
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, TCP_CA_NAME_MAX);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, icsk->icsk_ca_ops->name, len))
return -EFAULT;
return 0;
case TCP_THIN_LINEAR_TIMEOUTS:
val = tp->thin_lto;
break;
case TCP_THIN_DUPACK:
val = tp->thin_dupack;
break;
case TCP_REPAIR:
val = tp->repair;
break;
case TCP_REPAIR_QUEUE:
if (tp->repair)
val = tp->repair_queue;
else
return -EINVAL;
break;
case TCP_REPAIR_WINDOW: {
struct tcp_repair_window opt;
if (get_user(len, optlen))
return -EFAULT;
if (len != sizeof(opt))
return -EINVAL;
if (!tp->repair)
return -EPERM;
opt.snd_wl1 = tp->snd_wl1;
opt.snd_wnd = tp->snd_wnd;
opt.max_window = tp->max_window;
opt.rcv_wnd = tp->rcv_wnd;
opt.rcv_wup = tp->rcv_wup;
if (copy_to_user(optval, &opt, len))
return -EFAULT;
return 0;
}
case TCP_QUEUE_SEQ:
if (tp->repair_queue == TCP_SEND_QUEUE)
val = tp->write_seq;
else if (tp->repair_queue == TCP_RECV_QUEUE)
val = tp->rcv_nxt;
else
return -EINVAL;
break;
case TCP_USER_TIMEOUT:
val = jiffies_to_msecs(icsk->icsk_user_timeout);
break;
case TCP_FASTOPEN:
val = icsk->icsk_accept_queue.fastopenq.max_qlen;
break;
case TCP_TIMESTAMP:
val = tcp_time_stamp + tp->tsoffset;
break;
case TCP_NOTSENT_LOWAT:
val = tp->notsent_lowat;
break;
case TCP_SAVE_SYN:
val = tp->save_syn;
break;
case TCP_SAVED_SYN: {
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
if (tp->saved_syn) {
if (len < tp->saved_syn[0]) {
if (put_user(tp->saved_syn[0], optlen)) {
release_sock(sk);
return -EFAULT;
}
release_sock(sk);
return -EINVAL;
}
len = tp->saved_syn[0];
if (put_user(len, optlen)) {
release_sock(sk);
return -EFAULT;
}
if (copy_to_user(optval, tp->saved_syn + 1, len)) {
release_sock(sk);
return -EFAULT;
}
tcp_saved_syn_free(tp);
release_sock(sk);
} else {
release_sock(sk);
len = 0;
if (put_user(len, optlen))
return -EFAULT;
}
return 0;
}
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval,
int __user *optlen)
{
struct inet_connection_sock *icsk = inet_csk(sk);
if (level != SOL_TCP)
return icsk->icsk_af_ops->getsockopt(sk, level, optname,
optval, optlen);
return do_tcp_getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(tcp_getsockopt);
#ifdef CONFIG_COMPAT
int compat_tcp_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_TCP)
return inet_csk_compat_getsockopt(sk, level, optname,
optval, optlen);
return do_tcp_getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_tcp_getsockopt);
#endif
#ifdef CONFIG_TCP_MD5SIG
static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool);
static DEFINE_MUTEX(tcp_md5sig_mutex);
static bool tcp_md5sig_pool_populated = false;
static void __tcp_alloc_md5sig_pool(void)
{
struct crypto_ahash *hash;
int cpu;
hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hash))
return;
for_each_possible_cpu(cpu) {
void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch;
struct ahash_request *req;
if (!scratch) {
scratch = kmalloc_node(sizeof(union tcp_md5sum_block) +
sizeof(struct tcphdr),
GFP_KERNEL,
cpu_to_node(cpu));
if (!scratch)
return;
per_cpu(tcp_md5sig_pool, cpu).scratch = scratch;
}
if (per_cpu(tcp_md5sig_pool, cpu).md5_req)
continue;
req = ahash_request_alloc(hash, GFP_KERNEL);
if (!req)
return;
ahash_request_set_callback(req, 0, NULL, NULL);
per_cpu(tcp_md5sig_pool, cpu).md5_req = req;
}
/* before setting tcp_md5sig_pool_populated, we must commit all writes
* to memory. See smp_rmb() in tcp_get_md5sig_pool()
*/
smp_wmb();
tcp_md5sig_pool_populated = true;
}
bool tcp_alloc_md5sig_pool(void)
{
if (unlikely(!tcp_md5sig_pool_populated)) {
mutex_lock(&tcp_md5sig_mutex);
if (!tcp_md5sig_pool_populated)
__tcp_alloc_md5sig_pool();
mutex_unlock(&tcp_md5sig_mutex);
}
return tcp_md5sig_pool_populated;
}
EXPORT_SYMBOL(tcp_alloc_md5sig_pool);
/**
* tcp_get_md5sig_pool - get md5sig_pool for this user
*
* We use percpu structure, so if we succeed, we exit with preemption
* and BH disabled, to make sure another thread or softirq handling
* wont try to get same context.
*/
struct tcp_md5sig_pool *tcp_get_md5sig_pool(void)
{
local_bh_disable();
if (tcp_md5sig_pool_populated) {
/* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */
smp_rmb();
return this_cpu_ptr(&tcp_md5sig_pool);
}
local_bh_enable();
return NULL;
}
EXPORT_SYMBOL(tcp_get_md5sig_pool);
int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp,
const struct sk_buff *skb, unsigned int header_len)
{
struct scatterlist sg;
const struct tcphdr *tp = tcp_hdr(skb);
struct ahash_request *req = hp->md5_req;
unsigned int i;
const unsigned int head_data_len = skb_headlen(skb) > header_len ?
skb_headlen(skb) - header_len : 0;
const struct skb_shared_info *shi = skb_shinfo(skb);
struct sk_buff *frag_iter;
sg_init_table(&sg, 1);
sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len);
ahash_request_set_crypt(req, &sg, NULL, head_data_len);
if (crypto_ahash_update(req))
return 1;
for (i = 0; i < shi->nr_frags; ++i) {
const struct skb_frag_struct *f = &shi->frags[i];
unsigned int offset = f->page_offset;
struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT);
sg_set_page(&sg, page, skb_frag_size(f),
offset_in_page(offset));
ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f));
if (crypto_ahash_update(req))
return 1;
}
skb_walk_frags(skb, frag_iter)
if (tcp_md5_hash_skb_data(hp, frag_iter, 0))
return 1;
return 0;
}
EXPORT_SYMBOL(tcp_md5_hash_skb_data);
int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key)
{
struct scatterlist sg;
sg_init_one(&sg, key->key, key->keylen);
ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen);
return crypto_ahash_update(hp->md5_req);
}
EXPORT_SYMBOL(tcp_md5_hash_key);
#endif
void tcp_done(struct sock *sk)
{
struct request_sock *req = tcp_sk(sk)->fastopen_rsk;
if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV)
TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
tcp_set_state(sk, TCP_CLOSE);
tcp_clear_xmit_timers(sk);
if (req)
reqsk_fastopen_remove(sk, req, false);
sk->sk_shutdown = SHUTDOWN_MASK;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
else
inet_csk_destroy_sock(sk);
}
EXPORT_SYMBOL_GPL(tcp_done);
int tcp_abort(struct sock *sk, int err)
{
if (!sk_fullsock(sk)) {
if (sk->sk_state == TCP_NEW_SYN_RECV) {
struct request_sock *req = inet_reqsk(sk);
local_bh_disable();
inet_csk_reqsk_queue_drop_and_put(req->rsk_listener,
req);
local_bh_enable();
return 0;
}
return -EOPNOTSUPP;
}
/* Don't race with userspace socket closes such as tcp_close. */
lock_sock(sk);
if (sk->sk_state == TCP_LISTEN) {
tcp_set_state(sk, TCP_CLOSE);
inet_csk_listen_stop(sk);
}
/* Don't race with BH socket closes such as inet_csk_listen_stop. */
local_bh_disable();
bh_lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD)) {
sk->sk_err = err;
/* This barrier is coupled with smp_rmb() in tcp_poll() */
smp_wmb();
sk->sk_error_report(sk);
if (tcp_need_reset(sk->sk_state))
tcp_send_active_reset(sk, GFP_ATOMIC);
tcp_done(sk);
}
bh_unlock_sock(sk);
local_bh_enable();
release_sock(sk);
return 0;
}
EXPORT_SYMBOL_GPL(tcp_abort);
extern struct tcp_congestion_ops tcp_reno;
static __initdata unsigned long thash_entries;
static int __init set_thash_entries(char *str)
{
ssize_t ret;
if (!str)
return 0;
ret = kstrtoul(str, 0, &thash_entries);
if (ret)
return 0;
return 1;
}
__setup("thash_entries=", set_thash_entries);
static void __init tcp_init_mem(void)
{
unsigned long limit = nr_free_buffer_pages() / 16;
limit = max(limit, 128UL);
sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */
sysctl_tcp_mem[1] = limit; /* 6.25 % */
sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */
}
void __init tcp_init(void)
{
int max_rshare, max_wshare, cnt;
unsigned long limit;
unsigned int i;
BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
FIELD_SIZEOF(struct sk_buff, cb));
percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL);
percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL);
tcp_hashinfo.bind_bucket_cachep =
kmem_cache_create("tcp_bind_bucket",
sizeof(struct inet_bind_bucket), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
/* Size and allocate the main established and bind bucket
* hash tables.
*
* The methodology is similar to that of the buffer cache.
*/
tcp_hashinfo.ehash =
alloc_large_system_hash("TCP established",
sizeof(struct inet_ehash_bucket),
thash_entries,
17, /* one slot per 128 KB of memory */
0,
NULL,
&tcp_hashinfo.ehash_mask,
0,
thash_entries ? 0 : 512 * 1024);
for (i = 0; i <= tcp_hashinfo.ehash_mask; i++)
INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);
if (inet_ehash_locks_alloc(&tcp_hashinfo))
panic("TCP: failed to alloc ehash_locks");
tcp_hashinfo.bhash =
alloc_large_system_hash("TCP bind",
sizeof(struct inet_bind_hashbucket),
tcp_hashinfo.ehash_mask + 1,
17, /* one slot per 128 KB of memory */
0,
&tcp_hashinfo.bhash_size,
NULL,
0,
64 * 1024);
tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;
for (i = 0; i < tcp_hashinfo.bhash_size; i++) {
spin_lock_init(&tcp_hashinfo.bhash[i].lock);
INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);
}
cnt = tcp_hashinfo.ehash_mask + 1;
tcp_death_row.sysctl_max_tw_buckets = cnt / 2;
sysctl_tcp_max_orphans = cnt / 2;
sysctl_max_syn_backlog = max(128, cnt / 256);
tcp_init_mem();
/* Set per-socket limits to no more than 1/128 the pressure threshold */
limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);
max_wshare = min(4UL*1024*1024, limit);
max_rshare = min(6UL*1024*1024, limit);
sysctl_tcp_wmem[0] = SK_MEM_QUANTUM;
sysctl_tcp_wmem[1] = 16*1024;
sysctl_tcp_wmem[2] = max(64*1024, max_wshare);
sysctl_tcp_rmem[0] = SK_MEM_QUANTUM;
sysctl_tcp_rmem[1] = 87380;
sysctl_tcp_rmem[2] = max(87380, max_rshare);
pr_info("Hash tables configured (established %u bind %u)\n",
tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);
tcp_metrics_init();
BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0);
tcp_tasklet_init();
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_3169_0 |
crossvul-cpp_data_good_2668_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Domain Name System (DNS) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "nameser.h"
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "extract.h"
static const char *ns_ops[] = {
"", " inv_q", " stat", " op3", " notify", " update", " op6", " op7",
" op8", " updateA", " updateD", " updateDA",
" updateM", " updateMA", " zoneInit", " zoneRef",
};
static const char *ns_resp[] = {
"", " FormErr", " ServFail", " NXDomain",
" NotImp", " Refused", " YXDomain", " YXRRSet",
" NXRRSet", " NotAuth", " NotZone", " Resp11",
" Resp12", " Resp13", " Resp14", " NoChange",
};
/* skip over a domain name */
static const u_char *
ns_nskip(netdissect_options *ndo,
register const u_char *cp)
{
register u_char i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
while (i) {
if ((i & INDIR_MASK) == INDIR_MASK)
return (cp + 1);
if ((i & INDIR_MASK) == EDNS0_MASK) {
int bitlen, bytelen;
if ((i & ~INDIR_MASK) != EDNS0_ELT_BITLABEL)
return(NULL); /* unknown ELT */
if (!ND_TTEST2(*cp, 1))
return (NULL);
if ((bitlen = *cp++) == 0)
bitlen = 256;
bytelen = (bitlen + 7) / 8;
cp += bytelen;
} else
cp += i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
}
return (cp);
}
/* print a <domain-name> */
static const u_char *
blabel_print(netdissect_options *ndo,
const u_char *cp)
{
int bitlen, slen, b;
const u_char *bitp, *lim;
char tc;
if (!ND_TTEST2(*cp, 1))
return(NULL);
if ((bitlen = *cp) == 0)
bitlen = 256;
slen = (bitlen + 3) / 4;
lim = cp + 1 + slen;
/* print the bit string as a hex string */
ND_PRINT((ndo, "\\[x"));
for (bitp = cp + 1, b = bitlen; bitp < lim && b > 7; b -= 8, bitp++) {
ND_TCHECK(*bitp);
ND_PRINT((ndo, "%02x", *bitp));
}
if (b > 4) {
ND_TCHECK(*bitp);
tc = *bitp++;
ND_PRINT((ndo, "%02x", tc & (0xff << (8 - b))));
} else if (b > 0) {
ND_TCHECK(*bitp);
tc = *bitp++;
ND_PRINT((ndo, "%1x", ((tc >> 4) & 0x0f) & (0x0f << (4 - b))));
}
ND_PRINT((ndo, "/%d]", bitlen));
return lim;
trunc:
ND_PRINT((ndo, ".../%d]", bitlen));
return NULL;
}
static int
labellen(netdissect_options *ndo,
const u_char *cp)
{
register u_int i;
if (!ND_TTEST2(*cp, 1))
return(-1);
i = *cp;
if ((i & INDIR_MASK) == EDNS0_MASK) {
int bitlen, elt;
if ((elt = (i & ~INDIR_MASK)) != EDNS0_ELT_BITLABEL) {
ND_PRINT((ndo, "<ELT %d>", elt));
return(-1);
}
if (!ND_TTEST2(*(cp + 1), 1))
return(-1);
if ((bitlen = *(cp + 1)) == 0)
bitlen = 256;
return(((bitlen + 7) / 8) + 1);
} else
return(i);
}
const u_char *
ns_nprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp)
{
register u_int i, l;
register const u_char *rp = NULL;
register int compress = 0;
int elt;
u_int offset, max_offset;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
max_offset = (u_int)(cp - bp);
if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) {
compress = 0;
rp = cp + l;
}
if (i != 0)
while (i && cp < ndo->ndo_snapend) {
if ((i & INDIR_MASK) == INDIR_MASK) {
if (!compress) {
rp = cp + 1;
compress = 1;
}
if (!ND_TTEST2(*cp, 1))
return(NULL);
offset = (((i << 8) | *cp) & 0x3fff);
/*
* This must move backwards in the packet.
* No RFC explicitly says that, but BIND's
* name decompression code requires it,
* as a way of preventing infinite loops
* and other bad behavior, and it's probably
* what was intended (compress by pointing
* to domain name suffixes already seen in
* the packet).
*/
if (offset >= max_offset) {
ND_PRINT((ndo, "<BAD PTR>"));
return(NULL);
}
max_offset = offset;
cp = bp + offset;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
continue;
}
if ((i & INDIR_MASK) == EDNS0_MASK) {
elt = (i & ~INDIR_MASK);
switch(elt) {
case EDNS0_ELT_BITLABEL:
if (blabel_print(ndo, cp) == NULL)
return (NULL);
break;
default:
/* unknown ELT */
ND_PRINT((ndo, "<ELT %d>", elt));
return(NULL);
}
} else {
if (fn_printn(ndo, cp, l, ndo->ndo_snapend))
return(NULL);
}
cp += l;
ND_PRINT((ndo, "."));
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
if (!compress)
rp += l + 1;
}
else
ND_PRINT((ndo, "."));
return (rp);
}
/* print a <character-string> */
static const u_char *
ns_cprint(netdissect_options *ndo,
register const u_char *cp)
{
register u_int i;
if (!ND_TTEST2(*cp, 1))
return (NULL);
i = *cp++;
if (fn_printn(ndo, cp, i, ndo->ndo_snapend))
return (NULL);
return (cp + i);
}
/* http://www.iana.org/assignments/dns-parameters */
const struct tok ns_type2str[] = {
{ T_A, "A" }, /* RFC 1035 */
{ T_NS, "NS" }, /* RFC 1035 */
{ T_MD, "MD" }, /* RFC 1035 */
{ T_MF, "MF" }, /* RFC 1035 */
{ T_CNAME, "CNAME" }, /* RFC 1035 */
{ T_SOA, "SOA" }, /* RFC 1035 */
{ T_MB, "MB" }, /* RFC 1035 */
{ T_MG, "MG" }, /* RFC 1035 */
{ T_MR, "MR" }, /* RFC 1035 */
{ T_NULL, "NULL" }, /* RFC 1035 */
{ T_WKS, "WKS" }, /* RFC 1035 */
{ T_PTR, "PTR" }, /* RFC 1035 */
{ T_HINFO, "HINFO" }, /* RFC 1035 */
{ T_MINFO, "MINFO" }, /* RFC 1035 */
{ T_MX, "MX" }, /* RFC 1035 */
{ T_TXT, "TXT" }, /* RFC 1035 */
{ T_RP, "RP" }, /* RFC 1183 */
{ T_AFSDB, "AFSDB" }, /* RFC 1183 */
{ T_X25, "X25" }, /* RFC 1183 */
{ T_ISDN, "ISDN" }, /* RFC 1183 */
{ T_RT, "RT" }, /* RFC 1183 */
{ T_NSAP, "NSAP" }, /* RFC 1706 */
{ T_NSAP_PTR, "NSAP_PTR" },
{ T_SIG, "SIG" }, /* RFC 2535 */
{ T_KEY, "KEY" }, /* RFC 2535 */
{ T_PX, "PX" }, /* RFC 2163 */
{ T_GPOS, "GPOS" }, /* RFC 1712 */
{ T_AAAA, "AAAA" }, /* RFC 1886 */
{ T_LOC, "LOC" }, /* RFC 1876 */
{ T_NXT, "NXT" }, /* RFC 2535 */
{ T_EID, "EID" }, /* Nimrod */
{ T_NIMLOC, "NIMLOC" }, /* Nimrod */
{ T_SRV, "SRV" }, /* RFC 2782 */
{ T_ATMA, "ATMA" }, /* ATM Forum */
{ T_NAPTR, "NAPTR" }, /* RFC 2168, RFC 2915 */
{ T_KX, "KX" }, /* RFC 2230 */
{ T_CERT, "CERT" }, /* RFC 2538 */
{ T_A6, "A6" }, /* RFC 2874 */
{ T_DNAME, "DNAME" }, /* RFC 2672 */
{ T_SINK, "SINK" },
{ T_OPT, "OPT" }, /* RFC 2671 */
{ T_APL, "APL" }, /* RFC 3123 */
{ T_DS, "DS" }, /* RFC 4034 */
{ T_SSHFP, "SSHFP" }, /* RFC 4255 */
{ T_IPSECKEY, "IPSECKEY" }, /* RFC 4025 */
{ T_RRSIG, "RRSIG" }, /* RFC 4034 */
{ T_NSEC, "NSEC" }, /* RFC 4034 */
{ T_DNSKEY, "DNSKEY" }, /* RFC 4034 */
{ T_SPF, "SPF" }, /* RFC-schlitt-spf-classic-02.txt */
{ T_UINFO, "UINFO" },
{ T_UID, "UID" },
{ T_GID, "GID" },
{ T_UNSPEC, "UNSPEC" },
{ T_UNSPECA, "UNSPECA" },
{ T_TKEY, "TKEY" }, /* RFC 2930 */
{ T_TSIG, "TSIG" }, /* RFC 2845 */
{ T_IXFR, "IXFR" }, /* RFC 1995 */
{ T_AXFR, "AXFR" }, /* RFC 1035 */
{ T_MAILB, "MAILB" }, /* RFC 1035 */
{ T_MAILA, "MAILA" }, /* RFC 1035 */
{ T_ANY, "ANY" },
{ 0, NULL }
};
const struct tok ns_class2str[] = {
{ C_IN, "IN" }, /* Not used */
{ C_CHAOS, "CHAOS" },
{ C_HS, "HS" },
{ C_ANY, "ANY" },
{ 0, NULL }
};
/* print a query */
static const u_char *
ns_qprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp, int is_mdns)
{
register const u_char *np = cp;
register u_int i, class;
cp = ns_nskip(ndo, cp);
if (cp == NULL || !ND_TTEST2(*cp, 4))
return(NULL);
/* print the qtype */
i = EXTRACT_16BITS(cp);
cp += 2;
ND_PRINT((ndo, " %s", tok2str(ns_type2str, "Type%d", i)));
/* print the qclass (if it's not IN) */
i = EXTRACT_16BITS(cp);
cp += 2;
if (is_mdns)
class = (i & ~C_QU);
else
class = i;
if (class != C_IN)
ND_PRINT((ndo, " %s", tok2str(ns_class2str, "(Class %d)", class)));
if (is_mdns) {
ND_PRINT((ndo, i & C_QU ? " (QU)" : " (QM)"));
}
ND_PRINT((ndo, "? "));
cp = ns_nprint(ndo, np, bp);
return(cp ? cp + 4 : NULL);
}
/* print a reply */
static const u_char *
ns_rprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp, int is_mdns)
{
register u_int i, class, opt_flags = 0;
register u_short typ, len;
register const u_char *rp;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return NULL;
} else
cp = ns_nskip(ndo, cp);
if (cp == NULL || !ND_TTEST2(*cp, 10))
return (ndo->ndo_snapend);
/* print the type/qtype */
typ = EXTRACT_16BITS(cp);
cp += 2;
/* print the class (if it's not IN and the type isn't OPT) */
i = EXTRACT_16BITS(cp);
cp += 2;
if (is_mdns)
class = (i & ~C_CACHE_FLUSH);
else
class = i;
if (class != C_IN && typ != T_OPT)
ND_PRINT((ndo, " %s", tok2str(ns_class2str, "(Class %d)", class)));
if (is_mdns) {
if (i & C_CACHE_FLUSH)
ND_PRINT((ndo, " (Cache flush)"));
}
if (typ == T_OPT) {
/* get opt flags */
cp += 2;
opt_flags = EXTRACT_16BITS(cp);
/* ignore rest of ttl field */
cp += 2;
} else if (ndo->ndo_vflag > 2) {
/* print ttl */
ND_PRINT((ndo, " ["));
unsigned_relts_print(ndo, EXTRACT_32BITS(cp));
ND_PRINT((ndo, "]"));
cp += 4;
} else {
/* ignore ttl */
cp += 4;
}
len = EXTRACT_16BITS(cp);
cp += 2;
rp = cp + len;
ND_PRINT((ndo, " %s", tok2str(ns_type2str, "Type%d", typ)));
if (rp > ndo->ndo_snapend)
return(NULL);
switch (typ) {
case T_A:
if (!ND_TTEST2(*cp, sizeof(struct in_addr)))
return(NULL);
ND_PRINT((ndo, " %s", intoa(htonl(EXTRACT_32BITS(cp)))));
break;
case T_NS:
case T_CNAME:
case T_PTR:
#ifdef T_DNAME
case T_DNAME:
#endif
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, cp, bp) == NULL)
return(NULL);
break;
case T_SOA:
if (!ndo->ndo_vflag)
break;
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
if (!ND_TTEST2(*cp, 5 * 4))
return(NULL);
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
ND_PRINT((ndo, " %u", EXTRACT_32BITS(cp)));
cp += 4;
break;
case T_MX:
ND_PRINT((ndo, " "));
if (!ND_TTEST2(*cp, 2))
return(NULL);
if (ns_nprint(ndo, cp + 2, bp) == NULL)
return(NULL);
ND_PRINT((ndo, " %d", EXTRACT_16BITS(cp)));
break;
case T_TXT:
while (cp < rp) {
ND_PRINT((ndo, " \""));
cp = ns_cprint(ndo, cp);
if (cp == NULL)
return(NULL);
ND_PRINT((ndo, "\""));
}
break;
case T_SRV:
ND_PRINT((ndo, " "));
if (!ND_TTEST2(*cp, 6))
return(NULL);
if (ns_nprint(ndo, cp + 6, bp) == NULL)
return(NULL);
ND_PRINT((ndo, ":%d %d %d", EXTRACT_16BITS(cp + 4),
EXTRACT_16BITS(cp), EXTRACT_16BITS(cp + 2)));
break;
case T_AAAA:
{
char ntop_buf[INET6_ADDRSTRLEN];
if (!ND_TTEST2(*cp, sizeof(struct in6_addr)))
return(NULL);
ND_PRINT((ndo, " %s",
addrtostr6(cp, ntop_buf, sizeof(ntop_buf))));
break;
}
case T_A6:
{
struct in6_addr a;
int pbit, pbyte;
char ntop_buf[INET6_ADDRSTRLEN];
if (!ND_TTEST2(*cp, 1))
return(NULL);
pbit = *cp;
pbyte = (pbit & ~7) / 8;
if (pbit > 128) {
ND_PRINT((ndo, " %u(bad plen)", pbit));
break;
} else if (pbit < 128) {
if (!ND_TTEST2(*(cp + 1), sizeof(a) - pbyte))
return(NULL);
memset(&a, 0, sizeof(a));
memcpy(&a.s6_addr[pbyte], cp + 1, sizeof(a) - pbyte);
ND_PRINT((ndo, " %u %s", pbit,
addrtostr6(&a, ntop_buf, sizeof(ntop_buf))));
}
if (pbit > 0) {
ND_PRINT((ndo, " "));
if (ns_nprint(ndo, cp + 1 + sizeof(a) - pbyte, bp) == NULL)
return(NULL);
}
break;
}
case T_OPT:
ND_PRINT((ndo, " UDPsize=%u", class));
if (opt_flags & 0x8000)
ND_PRINT((ndo, " DO"));
break;
case T_UNSPECA: /* One long string */
if (!ND_TTEST2(*cp, len))
return(NULL);
if (fn_printn(ndo, cp, len, ndo->ndo_snapend))
return(NULL);
break;
case T_TSIG:
{
if (cp + len > ndo->ndo_snapend)
return(NULL);
if (!ndo->ndo_vflag)
break;
ND_PRINT((ndo, " "));
if ((cp = ns_nprint(ndo, cp, bp)) == NULL)
return(NULL);
cp += 6;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " fudge=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " maclen=%u", EXTRACT_16BITS(cp)));
cp += 2 + EXTRACT_16BITS(cp);
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " origid=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " error=%u", EXTRACT_16BITS(cp)));
cp += 2;
if (!ND_TTEST2(*cp, 2))
return(NULL);
ND_PRINT((ndo, " otherlen=%u", EXTRACT_16BITS(cp)));
cp += 2;
}
}
return (rp); /* XXX This isn't always right */
}
void
ns_print(netdissect_options *ndo,
register const u_char *bp, u_int length, int is_mdns)
{
register const HEADER *np;
register int qdcount, ancount, nscount, arcount;
register const u_char *cp;
uint16_t b2;
np = (const HEADER *)bp;
ND_TCHECK(*np);
/* get the byte-order right */
qdcount = EXTRACT_16BITS(&np->qdcount);
ancount = EXTRACT_16BITS(&np->ancount);
nscount = EXTRACT_16BITS(&np->nscount);
arcount = EXTRACT_16BITS(&np->arcount);
if (DNS_QR(np)) {
/* this is a response */
ND_PRINT((ndo, "%d%s%s%s%s%s%s",
EXTRACT_16BITS(&np->id),
ns_ops[DNS_OPCODE(np)],
ns_resp[DNS_RCODE(np)],
DNS_AA(np)? "*" : "",
DNS_RA(np)? "" : "-",
DNS_TC(np)? "|" : "",
DNS_AD(np)? "$" : ""));
if (qdcount != 1)
ND_PRINT((ndo, " [%dq]", qdcount));
/* Print QUESTION section on -vv */
cp = (const u_char *)(np + 1);
while (qdcount--) {
if (qdcount < EXTRACT_16BITS(&np->qdcount) - 1)
ND_PRINT((ndo, ","));
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " q:"));
if ((cp = ns_qprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
} else {
if ((cp = ns_nskip(ndo, cp)) == NULL)
goto trunc;
cp += 4; /* skip QTYPE and QCLASS */
}
}
ND_PRINT((ndo, " %d/%d/%d", ancount, nscount, arcount));
if (ancount--) {
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && ancount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (ancount > 0)
goto trunc;
/* Print NS and AR sections on -vv */
if (ndo->ndo_vflag > 1) {
if (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, " ns:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (nscount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, " ar:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (arcount > 0)
goto trunc;
}
}
else {
/* this is a request */
ND_PRINT((ndo, "%d%s%s%s", EXTRACT_16BITS(&np->id), ns_ops[DNS_OPCODE(np)],
DNS_RD(np) ? "+" : "",
DNS_CD(np) ? "%" : ""));
/* any weirdness? */
b2 = EXTRACT_16BITS(((const u_short *)np)+1);
if (b2 & 0x6cf)
ND_PRINT((ndo, " [b2&3=0x%x]", b2));
if (DNS_OPCODE(np) == IQUERY) {
if (qdcount)
ND_PRINT((ndo, " [%dq]", qdcount));
if (ancount != 1)
ND_PRINT((ndo, " [%da]", ancount));
}
else {
if (ancount)
ND_PRINT((ndo, " [%da]", ancount));
if (qdcount != 1)
ND_PRINT((ndo, " [%dq]", qdcount));
}
if (nscount)
ND_PRINT((ndo, " [%dn]", nscount));
if (arcount)
ND_PRINT((ndo, " [%dau]", arcount));
cp = (const u_char *)(np + 1);
if (qdcount--) {
cp = ns_qprint(ndo, cp, (const u_char *)np, is_mdns);
if (!cp)
goto trunc;
while (cp < ndo->ndo_snapend && qdcount--) {
cp = ns_qprint(ndo, (const u_char *)cp,
(const u_char *)np,
is_mdns);
if (!cp)
goto trunc;
}
}
if (qdcount > 0)
goto trunc;
/* Print remaining sections on -vv */
if (ndo->ndo_vflag > 1) {
if (ancount--) {
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && ancount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (ancount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && nscount--) {
ND_PRINT((ndo, " ns:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (nscount-- && cp < ndo->ndo_snapend) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (nscount > 0)
goto trunc;
if (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, " ar:"));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
while (cp < ndo->ndo_snapend && arcount--) {
ND_PRINT((ndo, ","));
if ((cp = ns_rprint(ndo, cp, bp, is_mdns)) == NULL)
goto trunc;
}
}
if (arcount > 0)
goto trunc;
}
}
ND_PRINT((ndo, " (%d)", length));
return;
trunc:
ND_PRINT((ndo, "[|domain]"));
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/good_2668_0 |
crossvul-cpp_data_bad_1665_0 | /*
* QEMU VNC display driver
*
* Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
* Copyright (C) 2006 Fabrice Bellard
* Copyright (C) 2009 Red Hat, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "vnc.h"
#include "vnc-jobs.h"
#include "trace.h"
#include "sysemu/sysemu.h"
#include "qemu/sockets.h"
#include "qemu/timer.h"
#include "qemu/acl.h"
#include "qapi/qmp/types.h"
#include "qmp-commands.h"
#include "qemu/osdep.h"
#include "ui/input.h"
#include "qapi-event.h"
#define VNC_REFRESH_INTERVAL_BASE GUI_REFRESH_INTERVAL_DEFAULT
#define VNC_REFRESH_INTERVAL_INC 50
#define VNC_REFRESH_INTERVAL_MAX GUI_REFRESH_INTERVAL_IDLE
static const struct timeval VNC_REFRESH_STATS = { 0, 500000 };
static const struct timeval VNC_REFRESH_LOSSY = { 2, 0 };
#include "vnc_keysym.h"
#include "d3des.h"
static VncDisplay *vnc_display; /* needed for info vnc */
static int vnc_cursor_define(VncState *vs);
static void vnc_release_modifiers(VncState *vs);
static void vnc_set_share_mode(VncState *vs, VncShareMode mode)
{
#ifdef _VNC_DEBUG
static const char *mn[] = {
[0] = "undefined",
[VNC_SHARE_MODE_CONNECTING] = "connecting",
[VNC_SHARE_MODE_SHARED] = "shared",
[VNC_SHARE_MODE_EXCLUSIVE] = "exclusive",
[VNC_SHARE_MODE_DISCONNECTED] = "disconnected",
};
fprintf(stderr, "%s/%d: %s -> %s\n", __func__,
vs->csock, mn[vs->share_mode], mn[mode]);
#endif
if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
vs->vd->num_exclusive--;
}
vs->share_mode = mode;
if (vs->share_mode == VNC_SHARE_MODE_EXCLUSIVE) {
vs->vd->num_exclusive++;
}
}
static char *addr_to_string(const char *format,
struct sockaddr_storage *sa,
socklen_t salen) {
char *addr;
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
int err;
size_t addrlen;
if ((err = getnameinfo((struct sockaddr *)sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
VNC_DEBUG("Cannot resolve address %d: %s\n",
err, gai_strerror(err));
return NULL;
}
/* Enough for the existing format + the 2 vars we're
* substituting in. */
addrlen = strlen(format) + strlen(host) + strlen(serv);
addr = g_malloc(addrlen + 1);
snprintf(addr, addrlen, format, host, serv);
addr[addrlen] = '\0';
return addr;
}
char *vnc_socket_local_addr(const char *format, int fd) {
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0)
return NULL;
return addr_to_string(format, &sa, salen);
}
char *vnc_socket_remote_addr(const char *format, int fd) {
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0)
return NULL;
return addr_to_string(format, &sa, salen);
}
static VncBasicInfo *vnc_basic_info_get(struct sockaddr_storage *sa,
socklen_t salen)
{
VncBasicInfo *info;
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
int err;
if ((err = getnameinfo((struct sockaddr *)sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
VNC_DEBUG("Cannot resolve address %d: %s\n",
err, gai_strerror(err));
return NULL;
}
info = g_malloc0(sizeof(VncBasicInfo));
info->host = g_strdup(host);
info->service = g_strdup(serv);
info->family = inet_netfamily(sa->ss_family);
return info;
}
static VncBasicInfo *vnc_basic_info_get_from_server_addr(int fd)
{
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getsockname(fd, (struct sockaddr*)&sa, &salen) < 0) {
return NULL;
}
return vnc_basic_info_get(&sa, salen);
}
static VncBasicInfo *vnc_basic_info_get_from_remote_addr(int fd)
{
struct sockaddr_storage sa;
socklen_t salen;
salen = sizeof(sa);
if (getpeername(fd, (struct sockaddr*)&sa, &salen) < 0) {
return NULL;
}
return vnc_basic_info_get(&sa, salen);
}
static const char *vnc_auth_name(VncDisplay *vd) {
switch (vd->auth) {
case VNC_AUTH_INVALID:
return "invalid";
case VNC_AUTH_NONE:
return "none";
case VNC_AUTH_VNC:
return "vnc";
case VNC_AUTH_RA2:
return "ra2";
case VNC_AUTH_RA2NE:
return "ra2ne";
case VNC_AUTH_TIGHT:
return "tight";
case VNC_AUTH_ULTRA:
return "ultra";
case VNC_AUTH_TLS:
return "tls";
case VNC_AUTH_VENCRYPT:
#ifdef CONFIG_VNC_TLS
switch (vd->subauth) {
case VNC_AUTH_VENCRYPT_PLAIN:
return "vencrypt+plain";
case VNC_AUTH_VENCRYPT_TLSNONE:
return "vencrypt+tls+none";
case VNC_AUTH_VENCRYPT_TLSVNC:
return "vencrypt+tls+vnc";
case VNC_AUTH_VENCRYPT_TLSPLAIN:
return "vencrypt+tls+plain";
case VNC_AUTH_VENCRYPT_X509NONE:
return "vencrypt+x509+none";
case VNC_AUTH_VENCRYPT_X509VNC:
return "vencrypt+x509+vnc";
case VNC_AUTH_VENCRYPT_X509PLAIN:
return "vencrypt+x509+plain";
case VNC_AUTH_VENCRYPT_TLSSASL:
return "vencrypt+tls+sasl";
case VNC_AUTH_VENCRYPT_X509SASL:
return "vencrypt+x509+sasl";
default:
return "vencrypt";
}
#else
return "vencrypt";
#endif
case VNC_AUTH_SASL:
return "sasl";
}
return "unknown";
}
static VncServerInfo *vnc_server_info_get(void)
{
VncServerInfo *info;
VncBasicInfo *bi = vnc_basic_info_get_from_server_addr(vnc_display->lsock);
if (!bi) {
return NULL;
}
info = g_malloc(sizeof(*info));
info->base = bi;
info->has_auth = true;
info->auth = g_strdup(vnc_auth_name(vnc_display));
return info;
}
static void vnc_client_cache_auth(VncState *client)
{
if (!client->info) {
return;
}
#ifdef CONFIG_VNC_TLS
if (client->tls.session &&
client->tls.dname) {
client->info->has_x509_dname = true;
client->info->x509_dname = g_strdup(client->tls.dname);
}
#endif
#ifdef CONFIG_VNC_SASL
if (client->sasl.conn &&
client->sasl.username) {
client->info->has_sasl_username = true;
client->info->sasl_username = g_strdup(client->sasl.username);
}
#endif
}
static void vnc_client_cache_addr(VncState *client)
{
VncBasicInfo *bi = vnc_basic_info_get_from_remote_addr(client->csock);
if (bi) {
client->info = g_malloc0(sizeof(*client->info));
client->info->base = bi;
}
}
static void vnc_qmp_event(VncState *vs, QAPIEvent event)
{
VncServerInfo *si;
if (!vs->info) {
return;
}
g_assert(vs->info->base);
si = vnc_server_info_get();
if (!si) {
return;
}
switch (event) {
case QAPI_EVENT_VNC_CONNECTED:
qapi_event_send_vnc_connected(si, vs->info->base, &error_abort);
break;
case QAPI_EVENT_VNC_INITIALIZED:
qapi_event_send_vnc_initialized(si, vs->info, &error_abort);
break;
case QAPI_EVENT_VNC_DISCONNECTED:
qapi_event_send_vnc_disconnected(si, vs->info, &error_abort);
break;
default:
break;
}
qapi_free_VncServerInfo(si);
}
static VncClientInfo *qmp_query_vnc_client(const VncState *client)
{
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
VncClientInfo *info;
if (getpeername(client->csock, (struct sockaddr *)&sa, &salen) < 0) {
return NULL;
}
if (getnameinfo((struct sockaddr *)&sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
return NULL;
}
info = g_malloc0(sizeof(*info));
info->base = g_malloc0(sizeof(*info->base));
info->base->host = g_strdup(host);
info->base->service = g_strdup(serv);
info->base->family = inet_netfamily(sa.ss_family);
#ifdef CONFIG_VNC_TLS
if (client->tls.session && client->tls.dname) {
info->has_x509_dname = true;
info->x509_dname = g_strdup(client->tls.dname);
}
#endif
#ifdef CONFIG_VNC_SASL
if (client->sasl.conn && client->sasl.username) {
info->has_sasl_username = true;
info->sasl_username = g_strdup(client->sasl.username);
}
#endif
return info;
}
VncInfo *qmp_query_vnc(Error **errp)
{
VncInfo *info = g_malloc0(sizeof(*info));
if (vnc_display == NULL || vnc_display->display == NULL) {
info->enabled = false;
} else {
VncClientInfoList *cur_item = NULL;
struct sockaddr_storage sa;
socklen_t salen = sizeof(sa);
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
VncState *client;
info->enabled = true;
/* for compatibility with the original command */
info->has_clients = true;
QTAILQ_FOREACH(client, &vnc_display->clients, next) {
VncClientInfoList *cinfo = g_malloc0(sizeof(*info));
cinfo->value = qmp_query_vnc_client(client);
/* XXX: waiting for the qapi to support GSList */
if (!cur_item) {
info->clients = cur_item = cinfo;
} else {
cur_item->next = cinfo;
cur_item = cinfo;
}
}
if (vnc_display->lsock == -1) {
return info;
}
if (getsockname(vnc_display->lsock, (struct sockaddr *)&sa,
&salen) == -1) {
error_set(errp, QERR_UNDEFINED_ERROR);
goto out_error;
}
if (getnameinfo((struct sockaddr *)&sa, salen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV) < 0) {
error_set(errp, QERR_UNDEFINED_ERROR);
goto out_error;
}
info->has_host = true;
info->host = g_strdup(host);
info->has_service = true;
info->service = g_strdup(serv);
info->has_family = true;
info->family = inet_netfamily(sa.ss_family);
info->has_auth = true;
info->auth = g_strdup(vnc_auth_name(vnc_display));
}
return info;
out_error:
qapi_free_VncInfo(info);
return NULL;
}
/* TODO
1) Get the queue working for IO.
2) there is some weirdness when using the -S option (the screen is grey
and not totally invalidated
3) resolutions > 1024
*/
static int vnc_update_client(VncState *vs, int has_dirty, bool sync);
static void vnc_disconnect_start(VncState *vs);
static void vnc_colordepth(VncState *vs);
static void framebuffer_update_request(VncState *vs, int incremental,
int x_position, int y_position,
int w, int h);
static void vnc_refresh(DisplayChangeListener *dcl);
static int vnc_refresh_server_surface(VncDisplay *vd);
static void vnc_dpy_update(DisplayChangeListener *dcl,
int x, int y, int w, int h)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
struct VncSurface *s = &vd->guest;
int width = surface_width(vd->ds);
int height = surface_height(vd->ds);
/* this is needed this to ensure we updated all affected
* blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */
w += (x % VNC_DIRTY_PIXELS_PER_BIT);
x -= (x % VNC_DIRTY_PIXELS_PER_BIT);
x = MIN(x, width);
y = MIN(y, height);
w = MIN(x + w, width) - x;
h = MIN(y + h, height);
for (; y < h; y++) {
bitmap_set(s->dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,
DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));
}
}
void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
int32_t encoding)
{
vnc_write_u16(vs, x);
vnc_write_u16(vs, y);
vnc_write_u16(vs, w);
vnc_write_u16(vs, h);
vnc_write_s32(vs, encoding);
}
void buffer_reserve(Buffer *buffer, size_t len)
{
if ((buffer->capacity - buffer->offset) < len) {
buffer->capacity += (len + 1024);
buffer->buffer = g_realloc(buffer->buffer, buffer->capacity);
if (buffer->buffer == NULL) {
fprintf(stderr, "vnc: out of memory\n");
exit(1);
}
}
}
static int buffer_empty(Buffer *buffer)
{
return buffer->offset == 0;
}
uint8_t *buffer_end(Buffer *buffer)
{
return buffer->buffer + buffer->offset;
}
void buffer_reset(Buffer *buffer)
{
buffer->offset = 0;
}
void buffer_free(Buffer *buffer)
{
g_free(buffer->buffer);
buffer->offset = 0;
buffer->capacity = 0;
buffer->buffer = NULL;
}
void buffer_append(Buffer *buffer, const void *data, size_t len)
{
memcpy(buffer->buffer + buffer->offset, data, len);
buffer->offset += len;
}
void buffer_advance(Buffer *buf, size_t len)
{
memmove(buf->buffer, buf->buffer + len,
(buf->offset - len));
buf->offset -= len;
}
static void vnc_desktop_resize(VncState *vs)
{
DisplaySurface *ds = vs->vd->ds;
if (vs->csock == -1 || !vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {
return;
}
if (vs->client_width == surface_width(ds) &&
vs->client_height == surface_height(ds)) {
return;
}
vs->client_width = surface_width(ds);
vs->client_height = surface_height(ds);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0, vs->client_width, vs->client_height,
VNC_ENCODING_DESKTOPRESIZE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_abort_display_jobs(VncDisplay *vd)
{
VncState *vs;
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = true;
vnc_unlock_output(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_jobs_join(vs);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_lock_output(vs);
vs->abort = false;
vnc_unlock_output(vs);
}
}
int vnc_server_fb_stride(VncDisplay *vd)
{
return pixman_image_get_stride(vd->server);
}
void *vnc_server_fb_ptr(VncDisplay *vd, int x, int y)
{
uint8_t *ptr;
ptr = (uint8_t *)pixman_image_get_data(vd->server);
ptr += y * vnc_server_fb_stride(vd);
ptr += x * VNC_SERVER_FB_BYTES;
return ptr;
}
/* this sets only the visible pixels of a dirty bitmap */
#define VNC_SET_VISIBLE_PIXELS_DIRTY(bitmap, w, h) {\
int y;\
memset(bitmap, 0x00, sizeof(bitmap));\
for (y = 0; y < h; y++) {\
bitmap_set(bitmap[y], 0,\
DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));\
} \
}
static void vnc_dpy_switch(DisplayChangeListener *dcl,
DisplaySurface *surface)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs;
vnc_abort_display_jobs(vd);
/* server surface */
qemu_pixman_image_unref(vd->server);
vd->ds = surface;
vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,
surface_width(vd->ds),
surface_height(vd->ds),
NULL, 0);
/* guest surface */
#if 0 /* FIXME */
if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)
console_color_init(ds);
#endif
qemu_pixman_image_unref(vd->guest.fb);
vd->guest.fb = pixman_image_ref(surface->image);
vd->guest.format = surface->format;
VNC_SET_VISIBLE_PIXELS_DIRTY(vd->guest.dirty,
surface_width(vd->ds),
surface_height(vd->ds));
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_colordepth(vs);
vnc_desktop_resize(vs);
if (vs->vd->cursor) {
vnc_cursor_define(vs);
}
VNC_SET_VISIBLE_PIXELS_DIRTY(vs->dirty,
surface_width(vd->ds),
surface_height(vd->ds));
}
}
/* fastest code */
static void vnc_write_pixels_copy(VncState *vs,
void *pixels, int size)
{
vnc_write(vs, pixels, size);
}
/* slowest but generic code. */
void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
{
uint8_t r, g, b;
#if VNC_SERVER_FB_FORMAT == PIXMAN_FORMAT(32, PIXMAN_TYPE_ARGB, 0, 8, 8, 8)
r = (((v & 0x00ff0000) >> 16) << vs->client_pf.rbits) >> 8;
g = (((v & 0x0000ff00) >> 8) << vs->client_pf.gbits) >> 8;
b = (((v & 0x000000ff) >> 0) << vs->client_pf.bbits) >> 8;
#else
# error need some bits here if you change VNC_SERVER_FB_FORMAT
#endif
v = (r << vs->client_pf.rshift) |
(g << vs->client_pf.gshift) |
(b << vs->client_pf.bshift);
switch (vs->client_pf.bytes_per_pixel) {
case 1:
buf[0] = v;
break;
case 2:
if (vs->client_be) {
buf[0] = v >> 8;
buf[1] = v;
} else {
buf[1] = v >> 8;
buf[0] = v;
}
break;
default:
case 4:
if (vs->client_be) {
buf[0] = v >> 24;
buf[1] = v >> 16;
buf[2] = v >> 8;
buf[3] = v;
} else {
buf[3] = v >> 24;
buf[2] = v >> 16;
buf[1] = v >> 8;
buf[0] = v;
}
break;
}
}
static void vnc_write_pixels_generic(VncState *vs,
void *pixels1, int size)
{
uint8_t buf[4];
if (VNC_SERVER_FB_BYTES == 4) {
uint32_t *pixels = pixels1;
int n, i;
n = size >> 2;
for (i = 0; i < n; i++) {
vnc_convert_pixel(vs, buf, pixels[i]);
vnc_write(vs, buf, vs->client_pf.bytes_per_pixel);
}
}
}
int vnc_raw_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
{
int i;
uint8_t *row;
VncDisplay *vd = vs->vd;
row = vnc_server_fb_ptr(vd, x, y);
for (i = 0; i < h; i++) {
vs->write_pixels(vs, row, w * VNC_SERVER_FB_BYTES);
row += vnc_server_fb_stride(vd);
}
return 1;
}
int vnc_send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
{
int n = 0;
switch(vs->vnc_encoding) {
case VNC_ENCODING_ZLIB:
n = vnc_zlib_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_HEXTILE:
vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_HEXTILE);
n = vnc_hextile_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_TIGHT:
n = vnc_tight_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_TIGHT_PNG:
n = vnc_tight_png_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_ZRLE:
n = vnc_zrle_send_framebuffer_update(vs, x, y, w, h);
break;
case VNC_ENCODING_ZYWRLE:
n = vnc_zywrle_send_framebuffer_update(vs, x, y, w, h);
break;
default:
vnc_framebuffer_update(vs, x, y, w, h, VNC_ENCODING_RAW);
n = vnc_raw_send_framebuffer_update(vs, x, y, w, h);
break;
}
return n;
}
static void vnc_copy(VncState *vs, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
{
/* send bitblit op to the vnc client */
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, dst_x, dst_y, w, h, VNC_ENCODING_COPYRECT);
vnc_write_u16(vs, src_x);
vnc_write_u16(vs, src_y);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void vnc_dpy_copy(DisplayChangeListener *dcl,
int src_x, int src_y,
int dst_x, int dst_y, int w, int h)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs, *vn;
uint8_t *src_row;
uint8_t *dst_row;
int i, x, y, pitch, inc, w_lim, s;
int cmp_bytes;
vnc_refresh_server_surface(vd);
QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
vs->force_update = 1;
vnc_update_client(vs, 1, true);
/* vs might be free()ed here */
}
}
/* do bitblit op on the local surface too */
pitch = vnc_server_fb_stride(vd);
src_row = vnc_server_fb_ptr(vd, src_x, src_y);
dst_row = vnc_server_fb_ptr(vd, dst_x, dst_y);
y = dst_y;
inc = 1;
if (dst_y > src_y) {
/* copy backwards */
src_row += pitch * (h-1);
dst_row += pitch * (h-1);
pitch = -pitch;
y = dst_y + h - 1;
inc = -1;
}
w_lim = w - (VNC_DIRTY_PIXELS_PER_BIT - (dst_x % VNC_DIRTY_PIXELS_PER_BIT));
if (w_lim < 0) {
w_lim = w;
} else {
w_lim = w - (w_lim % VNC_DIRTY_PIXELS_PER_BIT);
}
for (i = 0; i < h; i++) {
for (x = 0; x <= w_lim;
x += s, src_row += cmp_bytes, dst_row += cmp_bytes) {
if (x == w_lim) {
if ((s = w - w_lim) == 0)
break;
} else if (!x) {
s = (VNC_DIRTY_PIXELS_PER_BIT -
(dst_x % VNC_DIRTY_PIXELS_PER_BIT));
s = MIN(s, w_lim);
} else {
s = VNC_DIRTY_PIXELS_PER_BIT;
}
cmp_bytes = s * VNC_SERVER_FB_BYTES;
if (memcmp(src_row, dst_row, cmp_bytes) == 0)
continue;
memmove(dst_row, src_row, cmp_bytes);
QTAILQ_FOREACH(vs, &vd->clients, next) {
if (!vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
set_bit(((x + dst_x) / VNC_DIRTY_PIXELS_PER_BIT),
vs->dirty[y]);
}
}
}
src_row += pitch - w * VNC_SERVER_FB_BYTES;
dst_row += pitch - w * VNC_SERVER_FB_BYTES;
y += inc;
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
if (vnc_has_feature(vs, VNC_FEATURE_COPYRECT)) {
vnc_copy(vs, src_x, src_y, dst_x, dst_y, w, h);
}
}
}
static void vnc_mouse_set(DisplayChangeListener *dcl,
int x, int y, int visible)
{
/* can we ask the client(s) to move the pointer ??? */
}
static int vnc_cursor_define(VncState *vs)
{
QEMUCursor *c = vs->vd->cursor;
int isize;
if (vnc_has_feature(vs, VNC_FEATURE_RICH_CURSOR)) {
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0); /* padding */
vnc_write_u16(vs, 1); /* # of rects */
vnc_framebuffer_update(vs, c->hot_x, c->hot_y, c->width, c->height,
VNC_ENCODING_RICH_CURSOR);
isize = c->width * c->height * vs->client_pf.bytes_per_pixel;
vnc_write_pixels_generic(vs, c->data, isize);
vnc_write(vs, vs->vd->cursor_mask, vs->vd->cursor_msize);
vnc_unlock_output(vs);
return 0;
}
return -1;
}
static void vnc_dpy_cursor_define(DisplayChangeListener *dcl,
QEMUCursor *c)
{
VncDisplay *vd = vnc_display;
VncState *vs;
cursor_put(vd->cursor);
g_free(vd->cursor_mask);
vd->cursor = c;
cursor_get(vd->cursor);
vd->cursor_msize = cursor_get_mono_bpl(c) * c->height;
vd->cursor_mask = g_malloc0(vd->cursor_msize);
cursor_get_mono_mask(c, 0, vd->cursor_mask);
QTAILQ_FOREACH(vs, &vd->clients, next) {
vnc_cursor_define(vs);
}
}
static int find_and_clear_dirty_height(struct VncState *vs,
int y, int last_x, int x, int height)
{
int h;
for (h = 1; h < (height - y); h++) {
if (!test_bit(last_x, vs->dirty[y + h])) {
break;
}
bitmap_clear(vs->dirty[y + h], last_x, x - last_x);
}
return h;
}
static int vnc_update_client(VncState *vs, int has_dirty, bool sync)
{
if (vs->need_update && vs->csock != -1) {
VncDisplay *vd = vs->vd;
VncJob *job;
int y;
int height, width;
int n = 0;
if (vs->output.offset && !vs->audio_cap && !vs->force_update)
/* kernel send buffers are full -> drop frames to throttle */
return 0;
if (!has_dirty && !vs->audio_cap && !vs->force_update)
return 0;
/*
* Send screen updates to the vnc client using the server
* surface and server dirty map. guest surface updates
* happening in parallel don't disturb us, the next pass will
* send them to the client.
*/
job = vnc_job_new(vs);
height = MIN(pixman_image_get_height(vd->server), vs->client_height);
width = MIN(pixman_image_get_width(vd->server), vs->client_width);
y = 0;
for (;;) {
int x, h;
unsigned long x2;
unsigned long offset = find_next_bit((unsigned long *) &vs->dirty,
height * VNC_DIRTY_BPL(vs),
y * VNC_DIRTY_BPL(vs));
if (offset == height * VNC_DIRTY_BPL(vs)) {
/* no more dirty bits */
break;
}
y = offset / VNC_DIRTY_BPL(vs);
x = offset % VNC_DIRTY_BPL(vs);
x2 = find_next_zero_bit((unsigned long *) &vs->dirty[y],
VNC_DIRTY_BPL(vs), x);
bitmap_clear(vs->dirty[y], x, x2 - x);
h = find_and_clear_dirty_height(vs, y, x, x2, height);
x2 = MIN(x2, width / VNC_DIRTY_PIXELS_PER_BIT);
if (x2 > x) {
n += vnc_job_add_rect(job, x * VNC_DIRTY_PIXELS_PER_BIT, y,
(x2 - x) * VNC_DIRTY_PIXELS_PER_BIT, h);
}
}
vnc_job_push(job);
if (sync) {
vnc_jobs_join(vs);
}
vs->force_update = 0;
return n;
}
if (vs->csock == -1) {
vnc_disconnect_finish(vs);
} else if (sync) {
vnc_jobs_join(vs);
}
return 0;
}
/* audio */
static void audio_capture_notify(void *opaque, audcnotification_e cmd)
{
VncState *vs = opaque;
switch (cmd) {
case AUD_CNOTIFY_DISABLE:
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_END);
vnc_unlock_output(vs);
vnc_flush(vs);
break;
case AUD_CNOTIFY_ENABLE:
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_BEGIN);
vnc_unlock_output(vs);
vnc_flush(vs);
break;
}
}
static void audio_capture_destroy(void *opaque)
{
}
static void audio_capture(void *opaque, void *buf, int size)
{
VncState *vs = opaque;
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU);
vnc_write_u8(vs, VNC_MSG_SERVER_QEMU_AUDIO);
vnc_write_u16(vs, VNC_MSG_SERVER_QEMU_AUDIO_DATA);
vnc_write_u32(vs, size);
vnc_write(vs, buf, size);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void audio_add(VncState *vs)
{
struct audio_capture_ops ops;
if (vs->audio_cap) {
error_report("audio already running");
return;
}
ops.notify = audio_capture_notify;
ops.destroy = audio_capture_destroy;
ops.capture = audio_capture;
vs->audio_cap = AUD_add_capture(&vs->as, &ops, vs);
if (!vs->audio_cap) {
error_report("Failed to add audio capture");
}
}
static void audio_del(VncState *vs)
{
if (vs->audio_cap) {
AUD_del_capture(vs->audio_cap, vs);
vs->audio_cap = NULL;
}
}
static void vnc_disconnect_start(VncState *vs)
{
if (vs->csock == -1)
return;
vnc_set_share_mode(vs, VNC_SHARE_MODE_DISCONNECTED);
qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
closesocket(vs->csock);
vs->csock = -1;
}
void vnc_disconnect_finish(VncState *vs)
{
int i;
vnc_jobs_join(vs); /* Wait encoding jobs */
vnc_lock_output(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_DISCONNECTED);
buffer_free(&vs->input);
buffer_free(&vs->output);
#ifdef CONFIG_VNC_WS
buffer_free(&vs->ws_input);
buffer_free(&vs->ws_output);
#endif /* CONFIG_VNC_WS */
qapi_free_VncClientInfo(vs->info);
vnc_zlib_clear(vs);
vnc_tight_clear(vs);
vnc_zrle_clear(vs);
#ifdef CONFIG_VNC_TLS
vnc_tls_client_cleanup(vs);
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
vnc_sasl_client_cleanup(vs);
#endif /* CONFIG_VNC_SASL */
audio_del(vs);
vnc_release_modifiers(vs);
if (vs->initialized) {
QTAILQ_REMOVE(&vs->vd->clients, vs, next);
qemu_remove_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
}
if (vs->vd->lock_key_sync)
qemu_remove_led_event_handler(vs->led);
vnc_unlock_output(vs);
qemu_mutex_destroy(&vs->output_mutex);
if (vs->bh != NULL) {
qemu_bh_delete(vs->bh);
}
buffer_free(&vs->jobs_buffer);
for (i = 0; i < VNC_STAT_ROWS; ++i) {
g_free(vs->lossy_rect[i]);
}
g_free(vs->lossy_rect);
g_free(vs);
}
int vnc_client_io_error(VncState *vs, int ret, int last_errno)
{
if (ret == 0 || ret == -1) {
if (ret == -1) {
switch (last_errno) {
case EINTR:
case EAGAIN:
#ifdef _WIN32
case WSAEWOULDBLOCK:
#endif
return 0;
default:
break;
}
}
VNC_DEBUG("Closing down client sock: ret %d, errno %d\n",
ret, ret < 0 ? last_errno : 0);
vnc_disconnect_start(vs);
return 0;
}
return ret;
}
void vnc_client_error(VncState *vs)
{
VNC_DEBUG("Closing down client sock: protocol error\n");
vnc_disconnect_start(vs);
}
#ifdef CONFIG_VNC_TLS
static long vnc_client_write_tls(gnutls_session_t *session,
const uint8_t *data,
size_t datalen)
{
long ret = gnutls_write(*session, data, datalen);
if (ret < 0) {
if (ret == GNUTLS_E_AGAIN) {
errno = EAGAIN;
} else {
errno = EIO;
}
ret = -1;
}
return ret;
}
#endif /* CONFIG_VNC_TLS */
/*
* Called to write a chunk of data to the client socket. The data may
* be the raw data, or may have already been encoded by SASL.
* The data will be written either straight onto the socket, or
* written via the GNUTLS wrappers, if TLS/SSL encryption is enabled
*
* NB, it is theoretically possible to have 2 layers of encryption,
* both SASL, and this TLS layer. It is highly unlikely in practice
* though, since SASL encryption will typically be a no-op if TLS
* is active
*
* Returns the number of bytes written, which may be less than
* the requested 'datalen' if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
long vnc_client_write_buf(VncState *vs, const uint8_t *data, size_t datalen)
{
long ret;
#ifdef CONFIG_VNC_TLS
if (vs->tls.session) {
ret = vnc_client_write_tls(&vs->tls.session, data, datalen);
} else {
#ifdef CONFIG_VNC_WS
if (vs->ws_tls.session) {
ret = vnc_client_write_tls(&vs->ws_tls.session, data, datalen);
} else
#endif /* CONFIG_VNC_WS */
#endif /* CONFIG_VNC_TLS */
{
ret = send(vs->csock, (const void *)data, datalen, 0);
}
#ifdef CONFIG_VNC_TLS
}
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Wrote wire %p %zd -> %ld\n", data, datalen, ret);
return vnc_client_io_error(vs, ret, socket_error());
}
/*
* Called to write buffered data to the client socket, when not
* using any SASL SSF encryption layers. Will write as much data
* as possible without blocking. If all buffered data is written,
* will switch the FD poll() handler back to read monitoring.
*
* Returns the number of bytes written, which may be less than
* the buffered output data if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
static long vnc_client_write_plain(VncState *vs)
{
long ret;
#ifdef CONFIG_VNC_SASL
VNC_DEBUG("Write Plain: Pending output %p size %zd offset %zd. Wait SSF %d\n",
vs->output.buffer, vs->output.capacity, vs->output.offset,
vs->sasl.waitWriteSSF);
if (vs->sasl.conn &&
vs->sasl.runSSF &&
vs->sasl.waitWriteSSF) {
ret = vnc_client_write_buf(vs, vs->output.buffer, vs->sasl.waitWriteSSF);
if (ret)
vs->sasl.waitWriteSSF -= ret;
} else
#endif /* CONFIG_VNC_SASL */
ret = vnc_client_write_buf(vs, vs->output.buffer, vs->output.offset);
if (!ret)
return 0;
buffer_advance(&vs->output, ret);
if (vs->output.offset == 0) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
return ret;
}
/*
* First function called whenever there is data to be written to
* the client socket. Will delegate actual work according to whether
* SASL SSF layers are enabled (thus requiring encryption calls)
*/
static void vnc_client_write_locked(void *opaque)
{
VncState *vs = opaque;
#ifdef CONFIG_VNC_SASL
if (vs->sasl.conn &&
vs->sasl.runSSF &&
!vs->sasl.waitWriteSSF) {
vnc_client_write_sasl(vs);
} else
#endif /* CONFIG_VNC_SASL */
{
#ifdef CONFIG_VNC_WS
if (vs->encode_ws) {
vnc_client_write_ws(vs);
} else
#endif /* CONFIG_VNC_WS */
{
vnc_client_write_plain(vs);
}
}
}
void vnc_client_write(void *opaque)
{
VncState *vs = opaque;
vnc_lock_output(vs);
if (vs->output.offset
#ifdef CONFIG_VNC_WS
|| vs->ws_output.offset
#endif
) {
vnc_client_write_locked(opaque);
} else if (vs->csock != -1) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
vnc_unlock_output(vs);
}
void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
{
vs->read_handler = func;
vs->read_handler_expect = expecting;
}
#ifdef CONFIG_VNC_TLS
static long vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,
size_t datalen)
{
long ret = gnutls_read(*session, data, datalen);
if (ret < 0) {
if (ret == GNUTLS_E_AGAIN) {
errno = EAGAIN;
} else {
errno = EIO;
}
ret = -1;
}
return ret;
}
#endif /* CONFIG_VNC_TLS */
/*
* Called to read a chunk of data from the client socket. The data may
* be the raw data, or may need to be further decoded by SASL.
* The data will be read either straight from to the socket, or
* read via the GNUTLS wrappers, if TLS/SSL encryption is enabled
*
* NB, it is theoretically possible to have 2 layers of encryption,
* both SASL, and this TLS layer. It is highly unlikely in practice
* though, since SASL encryption will typically be a no-op if TLS
* is active
*
* Returns the number of bytes read, which may be less than
* the requested 'datalen' if the socket would block. Returns
* -1 on error, and disconnects the client socket.
*/
long vnc_client_read_buf(VncState *vs, uint8_t *data, size_t datalen)
{
long ret;
#ifdef CONFIG_VNC_TLS
if (vs->tls.session) {
ret = vnc_client_read_tls(&vs->tls.session, data, datalen);
} else {
#ifdef CONFIG_VNC_WS
if (vs->ws_tls.session) {
ret = vnc_client_read_tls(&vs->ws_tls.session, data, datalen);
} else
#endif /* CONFIG_VNC_WS */
#endif /* CONFIG_VNC_TLS */
{
ret = qemu_recv(vs->csock, data, datalen, 0);
}
#ifdef CONFIG_VNC_TLS
}
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Read wire %p %zd -> %ld\n", data, datalen, ret);
return vnc_client_io_error(vs, ret, socket_error());
}
/*
* Called to read data from the client socket to the input buffer,
* when not using any SASL SSF encryption layers. Will read as much
* data as possible without blocking.
*
* Returns the number of bytes read. Returns -1 on error, and
* disconnects the client socket.
*/
static long vnc_client_read_plain(VncState *vs)
{
int ret;
VNC_DEBUG("Read plain %p size %zd offset %zd\n",
vs->input.buffer, vs->input.capacity, vs->input.offset);
buffer_reserve(&vs->input, 4096);
ret = vnc_client_read_buf(vs, buffer_end(&vs->input), 4096);
if (!ret)
return 0;
vs->input.offset += ret;
return ret;
}
static void vnc_jobs_bh(void *opaque)
{
VncState *vs = opaque;
vnc_jobs_consume_buffer(vs);
}
/*
* First function called whenever there is more data to be read from
* the client socket. Will delegate actual work according to whether
* SASL SSF layers are enabled (thus requiring decryption calls)
*/
void vnc_client_read(void *opaque)
{
VncState *vs = opaque;
long ret;
#ifdef CONFIG_VNC_SASL
if (vs->sasl.conn && vs->sasl.runSSF)
ret = vnc_client_read_sasl(vs);
else
#endif /* CONFIG_VNC_SASL */
#ifdef CONFIG_VNC_WS
if (vs->encode_ws) {
ret = vnc_client_read_ws(vs);
if (ret == -1) {
vnc_disconnect_start(vs);
return;
} else if (ret == -2) {
vnc_client_error(vs);
return;
}
} else
#endif /* CONFIG_VNC_WS */
{
ret = vnc_client_read_plain(vs);
}
if (!ret) {
if (vs->csock == -1)
vnc_disconnect_finish(vs);
return;
}
while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
size_t len = vs->read_handler_expect;
int ret;
ret = vs->read_handler(vs, vs->input.buffer, len);
if (vs->csock == -1) {
vnc_disconnect_finish(vs);
return;
}
if (!ret) {
buffer_advance(&vs->input, len);
} else {
vs->read_handler_expect = ret;
}
}
}
void vnc_write(VncState *vs, const void *data, size_t len)
{
buffer_reserve(&vs->output, len);
if (vs->csock != -1 && buffer_empty(&vs->output)) {
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
}
buffer_append(&vs->output, data, len);
}
void vnc_write_s32(VncState *vs, int32_t value)
{
vnc_write_u32(vs, *(uint32_t *)&value);
}
void vnc_write_u32(VncState *vs, uint32_t value)
{
uint8_t buf[4];
buf[0] = (value >> 24) & 0xFF;
buf[1] = (value >> 16) & 0xFF;
buf[2] = (value >> 8) & 0xFF;
buf[3] = value & 0xFF;
vnc_write(vs, buf, 4);
}
void vnc_write_u16(VncState *vs, uint16_t value)
{
uint8_t buf[2];
buf[0] = (value >> 8) & 0xFF;
buf[1] = value & 0xFF;
vnc_write(vs, buf, 2);
}
void vnc_write_u8(VncState *vs, uint8_t value)
{
vnc_write(vs, (char *)&value, 1);
}
void vnc_flush(VncState *vs)
{
vnc_lock_output(vs);
if (vs->csock != -1 && (vs->output.offset
#ifdef CONFIG_VNC_WS
|| vs->ws_output.offset
#endif
)) {
vnc_client_write_locked(vs);
}
vnc_unlock_output(vs);
}
static uint8_t read_u8(uint8_t *data, size_t offset)
{
return data[offset];
}
static uint16_t read_u16(uint8_t *data, size_t offset)
{
return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
}
static int32_t read_s32(uint8_t *data, size_t offset)
{
return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]);
}
uint32_t read_u32(uint8_t *data, size_t offset)
{
return ((data[offset] << 24) | (data[offset + 1] << 16) |
(data[offset + 2] << 8) | data[offset + 3]);
}
static void client_cut_text(VncState *vs, size_t len, uint8_t *text)
{
}
static void check_pointer_type_change(Notifier *notifier, void *data)
{
VncState *vs = container_of(notifier, VncState, mouse_mode_notifier);
int absolute = qemu_input_is_absolute();
if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) {
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, absolute, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_POINTER_TYPE_CHANGE);
vnc_unlock_output(vs);
vnc_flush(vs);
}
vs->absolute = absolute;
}
static void pointer_event(VncState *vs, int button_mask, int x, int y)
{
static uint32_t bmap[INPUT_BUTTON_MAX] = {
[INPUT_BUTTON_LEFT] = 0x01,
[INPUT_BUTTON_MIDDLE] = 0x02,
[INPUT_BUTTON_RIGHT] = 0x04,
[INPUT_BUTTON_WHEEL_UP] = 0x08,
[INPUT_BUTTON_WHEEL_DOWN] = 0x10,
};
QemuConsole *con = vs->vd->dcl.con;
int width = surface_width(vs->vd->ds);
int height = surface_height(vs->vd->ds);
if (vs->last_bmask != button_mask) {
qemu_input_update_buttons(con, bmap, vs->last_bmask, button_mask);
vs->last_bmask = button_mask;
}
if (vs->absolute) {
qemu_input_queue_abs(con, INPUT_AXIS_X, x, width);
qemu_input_queue_abs(con, INPUT_AXIS_Y, y, height);
} else if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE)) {
qemu_input_queue_rel(con, INPUT_AXIS_X, x - 0x7FFF);
qemu_input_queue_rel(con, INPUT_AXIS_Y, y - 0x7FFF);
} else {
if (vs->last_x != -1) {
qemu_input_queue_rel(con, INPUT_AXIS_X, x - vs->last_x);
qemu_input_queue_rel(con, INPUT_AXIS_Y, y - vs->last_y);
}
vs->last_x = x;
vs->last_y = y;
}
qemu_input_event_sync();
}
static void reset_keys(VncState *vs)
{
int i;
for(i = 0; i < 256; i++) {
if (vs->modifiers_state[i]) {
qemu_input_event_send_key_number(vs->vd->dcl.con, i, false);
vs->modifiers_state[i] = 0;
}
}
}
static void press_key(VncState *vs, int keysym)
{
int keycode = keysym2scancode(vs->vd->kbd_layout, keysym) & SCANCODE_KEYMASK;
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, true);
qemu_input_event_send_key_delay(0);
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
qemu_input_event_send_key_delay(0);
}
static int current_led_state(VncState *vs)
{
int ledstate = 0;
if (vs->modifiers_state[0x46]) {
ledstate |= QEMU_SCROLL_LOCK_LED;
}
if (vs->modifiers_state[0x45]) {
ledstate |= QEMU_NUM_LOCK_LED;
}
if (vs->modifiers_state[0x3a]) {
ledstate |= QEMU_CAPS_LOCK_LED;
}
return ledstate;
}
static void vnc_led_state_change(VncState *vs)
{
int ledstate = 0;
if (!vnc_has_feature(vs, VNC_FEATURE_LED_STATE)) {
return;
}
ledstate = current_led_state(vs);
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0, 1, 1, VNC_ENCODING_LED_STATE);
vnc_write_u8(vs, ledstate);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void kbd_leds(void *opaque, int ledstate)
{
VncState *vs = opaque;
int caps, num, scr;
bool has_changed = (ledstate != current_led_state(vs));
trace_vnc_key_guest_leds((ledstate & QEMU_CAPS_LOCK_LED),
(ledstate & QEMU_NUM_LOCK_LED),
(ledstate & QEMU_SCROLL_LOCK_LED));
caps = ledstate & QEMU_CAPS_LOCK_LED ? 1 : 0;
num = ledstate & QEMU_NUM_LOCK_LED ? 1 : 0;
scr = ledstate & QEMU_SCROLL_LOCK_LED ? 1 : 0;
if (vs->modifiers_state[0x3a] != caps) {
vs->modifiers_state[0x3a] = caps;
}
if (vs->modifiers_state[0x45] != num) {
vs->modifiers_state[0x45] = num;
}
if (vs->modifiers_state[0x46] != scr) {
vs->modifiers_state[0x46] = scr;
}
/* Sending the current led state message to the client */
if (has_changed) {
vnc_led_state_change(vs);
}
}
static void do_key_event(VncState *vs, int down, int keycode, int sym)
{
/* QEMU console switch */
switch(keycode) {
case 0x2a: /* Left Shift */
case 0x36: /* Right Shift */
case 0x1d: /* Left CTRL */
case 0x9d: /* Right CTRL */
case 0x38: /* Left ALT */
case 0xb8: /* Right ALT */
if (down)
vs->modifiers_state[keycode] = 1;
else
vs->modifiers_state[keycode] = 0;
break;
case 0x02 ... 0x0a: /* '1' to '9' keys */
if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
/* Reset the modifiers sent to the current console */
reset_keys(vs);
console_select(keycode - 0x02);
return;
}
break;
case 0x3a: /* CapsLock */
case 0x45: /* NumLock */
if (down)
vs->modifiers_state[keycode] ^= 1;
break;
}
/* Turn off the lock state sync logic if the client support the led
state extension.
*/
if (down && vs->vd->lock_key_sync &&
!vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
keycode_is_keypad(vs->vd->kbd_layout, keycode)) {
/* If the numlock state needs to change then simulate an additional
keypress before sending this one. This will happen if the user
toggles numlock away from the VNC window.
*/
if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) {
if (!vs->modifiers_state[0x45]) {
trace_vnc_key_sync_numlock(true);
vs->modifiers_state[0x45] = 1;
press_key(vs, 0xff7f);
}
} else {
if (vs->modifiers_state[0x45]) {
trace_vnc_key_sync_numlock(false);
vs->modifiers_state[0x45] = 0;
press_key(vs, 0xff7f);
}
}
}
if (down && vs->vd->lock_key_sync &&
!vnc_has_feature(vs, VNC_FEATURE_LED_STATE) &&
((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) {
/* If the capslock state needs to change then simulate an additional
keypress before sending this one. This will happen if the user
toggles capslock away from the VNC window.
*/
int uppercase = !!(sym >= 'A' && sym <= 'Z');
int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]);
int capslock = !!(vs->modifiers_state[0x3a]);
if (capslock) {
if (uppercase == shift) {
trace_vnc_key_sync_capslock(false);
vs->modifiers_state[0x3a] = 0;
press_key(vs, 0xffe5);
}
} else {
if (uppercase != shift) {
trace_vnc_key_sync_capslock(true);
vs->modifiers_state[0x3a] = 1;
press_key(vs, 0xffe5);
}
}
}
if (qemu_console_is_graphic(NULL)) {
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down);
} else {
bool numlock = vs->modifiers_state[0x45];
bool control = (vs->modifiers_state[0x1d] ||
vs->modifiers_state[0x9d]);
/* QEMU console emulation */
if (down) {
switch (keycode) {
case 0x2a: /* Left Shift */
case 0x36: /* Right Shift */
case 0x1d: /* Left CTRL */
case 0x9d: /* Right CTRL */
case 0x38: /* Left ALT */
case 0xb8: /* Right ALT */
break;
case 0xc8:
kbd_put_keysym(QEMU_KEY_UP);
break;
case 0xd0:
kbd_put_keysym(QEMU_KEY_DOWN);
break;
case 0xcb:
kbd_put_keysym(QEMU_KEY_LEFT);
break;
case 0xcd:
kbd_put_keysym(QEMU_KEY_RIGHT);
break;
case 0xd3:
kbd_put_keysym(QEMU_KEY_DELETE);
break;
case 0xc7:
kbd_put_keysym(QEMU_KEY_HOME);
break;
case 0xcf:
kbd_put_keysym(QEMU_KEY_END);
break;
case 0xc9:
kbd_put_keysym(QEMU_KEY_PAGEUP);
break;
case 0xd1:
kbd_put_keysym(QEMU_KEY_PAGEDOWN);
break;
case 0x47:
kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME);
break;
case 0x48:
kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP);
break;
case 0x49:
kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP);
break;
case 0x4b:
kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT);
break;
case 0x4c:
kbd_put_keysym('5');
break;
case 0x4d:
kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT);
break;
case 0x4f:
kbd_put_keysym(numlock ? '1' : QEMU_KEY_END);
break;
case 0x50:
kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN);
break;
case 0x51:
kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN);
break;
case 0x52:
kbd_put_keysym('0');
break;
case 0x53:
kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE);
break;
case 0xb5:
kbd_put_keysym('/');
break;
case 0x37:
kbd_put_keysym('*');
break;
case 0x4a:
kbd_put_keysym('-');
break;
case 0x4e:
kbd_put_keysym('+');
break;
case 0x9c:
kbd_put_keysym('\n');
break;
default:
if (control) {
kbd_put_keysym(sym & 0x1f);
} else {
kbd_put_keysym(sym);
}
break;
}
}
}
}
static void vnc_release_modifiers(VncState *vs)
{
static const int keycodes[] = {
/* shift, control, alt keys, both left & right */
0x2a, 0x36, 0x1d, 0x9d, 0x38, 0xb8,
};
int i, keycode;
if (!qemu_console_is_graphic(NULL)) {
return;
}
for (i = 0; i < ARRAY_SIZE(keycodes); i++) {
keycode = keycodes[i];
if (!vs->modifiers_state[keycode]) {
continue;
}
qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, false);
}
}
static const char *code2name(int keycode)
{
return QKeyCode_lookup[qemu_input_key_number_to_qcode(keycode)];
}
static void key_event(VncState *vs, int down, uint32_t sym)
{
int keycode;
int lsym = sym;
if (lsym >= 'A' && lsym <= 'Z' && qemu_console_is_graphic(NULL)) {
lsym = lsym - 'A' + 'a';
}
keycode = keysym2scancode(vs->vd->kbd_layout, lsym & 0xFFFF) & SCANCODE_KEYMASK;
trace_vnc_key_event_map(down, sym, keycode, code2name(keycode));
do_key_event(vs, down, keycode, sym);
}
static void ext_key_event(VncState *vs, int down,
uint32_t sym, uint16_t keycode)
{
/* if the user specifies a keyboard layout, always use it */
if (keyboard_layout) {
key_event(vs, down, sym);
} else {
trace_vnc_key_event_ext(down, sym, keycode, code2name(keycode));
do_key_event(vs, down, keycode, sym);
}
}
static void framebuffer_update_request(VncState *vs, int incremental,
int x_position, int y_position,
int w, int h)
{
int i;
const size_t width = surface_width(vs->vd->ds) / VNC_DIRTY_PIXELS_PER_BIT;
const size_t height = surface_height(vs->vd->ds);
if (y_position > height) {
y_position = height;
}
if (y_position + h >= height) {
h = height - y_position;
}
vs->need_update = 1;
if (!incremental) {
vs->force_update = 1;
for (i = 0; i < h; i++) {
bitmap_set(vs->dirty[y_position + i], 0, width);
bitmap_clear(vs->dirty[y_position + i], width,
VNC_DIRTY_BITS - width);
}
}
}
static void send_ext_key_event_ack(VncState *vs)
{
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_EXT_KEY_EVENT);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void send_ext_audio_ack(VncState *vs)
{
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1);
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_AUDIO);
vnc_unlock_output(vs);
vnc_flush(vs);
}
static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
{
int i;
unsigned int enc = 0;
vs->features = 0;
vs->vnc_encoding = 0;
vs->tight.compression = 9;
vs->tight.quality = -1; /* Lossless by default */
vs->absolute = -1;
/*
* Start from the end because the encodings are sent in order of preference.
* This way the preferred encoding (first encoding defined in the array)
* will be set at the end of the loop.
*/
for (i = n_encodings - 1; i >= 0; i--) {
enc = encodings[i];
switch (enc) {
case VNC_ENCODING_RAW:
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_COPYRECT:
vs->features |= VNC_FEATURE_COPYRECT_MASK;
break;
case VNC_ENCODING_HEXTILE:
vs->features |= VNC_FEATURE_HEXTILE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_TIGHT:
vs->features |= VNC_FEATURE_TIGHT_MASK;
vs->vnc_encoding = enc;
break;
#ifdef CONFIG_VNC_PNG
case VNC_ENCODING_TIGHT_PNG:
vs->features |= VNC_FEATURE_TIGHT_PNG_MASK;
vs->vnc_encoding = enc;
break;
#endif
case VNC_ENCODING_ZLIB:
vs->features |= VNC_FEATURE_ZLIB_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_ZRLE:
vs->features |= VNC_FEATURE_ZRLE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_ZYWRLE:
vs->features |= VNC_FEATURE_ZYWRLE_MASK;
vs->vnc_encoding = enc;
break;
case VNC_ENCODING_DESKTOPRESIZE:
vs->features |= VNC_FEATURE_RESIZE_MASK;
break;
case VNC_ENCODING_POINTER_TYPE_CHANGE:
vs->features |= VNC_FEATURE_POINTER_TYPE_CHANGE_MASK;
break;
case VNC_ENCODING_RICH_CURSOR:
vs->features |= VNC_FEATURE_RICH_CURSOR_MASK;
break;
case VNC_ENCODING_EXT_KEY_EVENT:
send_ext_key_event_ack(vs);
break;
case VNC_ENCODING_AUDIO:
send_ext_audio_ack(vs);
break;
case VNC_ENCODING_WMVi:
vs->features |= VNC_FEATURE_WMVI_MASK;
break;
case VNC_ENCODING_LED_STATE:
vs->features |= VNC_FEATURE_LED_STATE_MASK;
break;
case VNC_ENCODING_COMPRESSLEVEL0 ... VNC_ENCODING_COMPRESSLEVEL0 + 9:
vs->tight.compression = (enc & 0x0F);
break;
case VNC_ENCODING_QUALITYLEVEL0 ... VNC_ENCODING_QUALITYLEVEL0 + 9:
if (vs->vd->lossy) {
vs->tight.quality = (enc & 0x0F);
}
break;
default:
VNC_DEBUG("Unknown encoding: %d (0x%.8x): %d\n", i, enc, enc);
break;
}
}
vnc_desktop_resize(vs);
check_pointer_type_change(&vs->mouse_mode_notifier, NULL);
vnc_led_state_change(vs);
}
static void set_pixel_conversion(VncState *vs)
{
pixman_format_code_t fmt = qemu_pixman_get_format(&vs->client_pf);
if (fmt == VNC_SERVER_FB_FORMAT) {
vs->write_pixels = vnc_write_pixels_copy;
vnc_hextile_set_pixel_conversion(vs, 0);
} else {
vs->write_pixels = vnc_write_pixels_generic;
vnc_hextile_set_pixel_conversion(vs, 1);
}
}
static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.rmask = red_max << red_shift;
vs->client_pf.gmax = green_max;
vs->client_pf.gbits = hweight_long(green_max);
vs->client_pf.gshift = green_shift;
vs->client_pf.gmask = green_max << green_shift;
vs->client_pf.bmax = blue_max;
vs->client_pf.bbits = hweight_long(blue_max);
vs->client_pf.bshift = blue_shift;
vs->client_pf.bmask = blue_max << blue_shift;
vs->client_pf.bits_per_pixel = bits_per_pixel;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
static void pixel_format_message (VncState *vs) {
char pad[3] = { 0, 0, 0 };
vs->client_pf = qemu_default_pixelformat(32);
vnc_write_u8(vs, vs->client_pf.bits_per_pixel); /* bits-per-pixel */
vnc_write_u8(vs, vs->client_pf.depth); /* depth */
#ifdef HOST_WORDS_BIGENDIAN
vnc_write_u8(vs, 1); /* big-endian-flag */
#else
vnc_write_u8(vs, 0); /* big-endian-flag */
#endif
vnc_write_u8(vs, 1); /* true-color-flag */
vnc_write_u16(vs, vs->client_pf.rmax); /* red-max */
vnc_write_u16(vs, vs->client_pf.gmax); /* green-max */
vnc_write_u16(vs, vs->client_pf.bmax); /* blue-max */
vnc_write_u8(vs, vs->client_pf.rshift); /* red-shift */
vnc_write_u8(vs, vs->client_pf.gshift); /* green-shift */
vnc_write_u8(vs, vs->client_pf.bshift); /* blue-shift */
vnc_write(vs, pad, 3); /* padding */
vnc_hextile_set_pixel_conversion(vs, 0);
vs->write_pixels = vnc_write_pixels_copy;
}
static void vnc_colordepth(VncState *vs)
{
if (vnc_has_feature(vs, VNC_FEATURE_WMVI)) {
/* Sending a WMVi message to notify the client*/
vnc_lock_output(vs);
vnc_write_u8(vs, VNC_MSG_SERVER_FRAMEBUFFER_UPDATE);
vnc_write_u8(vs, 0);
vnc_write_u16(vs, 1); /* number of rects */
vnc_framebuffer_update(vs, 0, 0,
surface_width(vs->vd->ds),
surface_height(vs->vd->ds),
VNC_ENCODING_WMVi);
pixel_format_message(vs);
vnc_unlock_output(vs);
vnc_flush(vs);
} else {
set_pixel_conversion(vs);
}
}
static int protocol_client_msg(VncState *vs, uint8_t *data, size_t len)
{
int i;
uint16_t limit;
VncDisplay *vd = vs->vd;
if (data[0] > 3) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
}
switch (data[0]) {
case VNC_MSG_CLIENT_SET_PIXEL_FORMAT:
if (len == 1)
return 20;
set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
read_u8(data, 6), read_u8(data, 7),
read_u16(data, 8), read_u16(data, 10),
read_u16(data, 12), read_u8(data, 14),
read_u8(data, 15), read_u8(data, 16));
break;
case VNC_MSG_CLIENT_SET_ENCODINGS:
if (len == 1)
return 4;
if (len == 4) {
limit = read_u16(data, 2);
if (limit > 0)
return 4 + (limit * 4);
} else
limit = read_u16(data, 2);
for (i = 0; i < limit; i++) {
int32_t val = read_s32(data, 4 + (i * 4));
memcpy(data + 4 + (i * 4), &val, sizeof(val));
}
set_encodings(vs, (int32_t *)(data + 4), limit);
break;
case VNC_MSG_CLIENT_FRAMEBUFFER_UPDATE_REQUEST:
if (len == 1)
return 10;
framebuffer_update_request(vs,
read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
read_u16(data, 6), read_u16(data, 8));
break;
case VNC_MSG_CLIENT_KEY_EVENT:
if (len == 1)
return 8;
key_event(vs, read_u8(data, 1), read_u32(data, 4));
break;
case VNC_MSG_CLIENT_POINTER_EVENT:
if (len == 1)
return 6;
pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
break;
case VNC_MSG_CLIENT_CUT_TEXT:
if (len == 1)
return 8;
if (len == 8) {
uint32_t dlen = read_u32(data, 4);
if (dlen > 0)
return 8 + dlen;
}
client_cut_text(vs, read_u32(data, 4), data + 8);
break;
case VNC_MSG_CLIENT_QEMU:
if (len == 1)
return 2;
switch (read_u8(data, 1)) {
case VNC_MSG_CLIENT_QEMU_EXT_KEY_EVENT:
if (len == 2)
return 12;
ext_key_event(vs, read_u16(data, 2),
read_u32(data, 4), read_u32(data, 8));
break;
case VNC_MSG_CLIENT_QEMU_AUDIO:
if (len == 2)
return 4;
switch (read_u16 (data, 2)) {
case VNC_MSG_CLIENT_QEMU_AUDIO_ENABLE:
audio_add(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_DISABLE:
audio_del(vs);
break;
case VNC_MSG_CLIENT_QEMU_AUDIO_SET_FORMAT:
if (len == 4)
return 10;
switch (read_u8(data, 4)) {
case 0: vs->as.fmt = AUD_FMT_U8; break;
case 1: vs->as.fmt = AUD_FMT_S8; break;
case 2: vs->as.fmt = AUD_FMT_U16; break;
case 3: vs->as.fmt = AUD_FMT_S16; break;
case 4: vs->as.fmt = AUD_FMT_U32; break;
case 5: vs->as.fmt = AUD_FMT_S32; break;
default:
printf("Invalid audio format %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
vs->as.nchannels = read_u8(data, 5);
if (vs->as.nchannels != 1 && vs->as.nchannels != 2) {
printf("Invalid audio channel coount %d\n",
read_u8(data, 5));
vnc_client_error(vs);
break;
}
vs->as.freq = read_u32(data, 6);
break;
default:
printf ("Invalid audio message %d\n", read_u8(data, 4));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", read_u16(data, 0));
vnc_client_error(vs);
break;
}
break;
default:
printf("Msg: %d\n", data[0]);
vnc_client_error(vs);
break;
}
vnc_read_when(vs, protocol_client_msg, 1);
return 0;
}
static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)
{
char buf[1024];
VncShareMode mode;
int size;
mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;
switch (vs->vd->share_policy) {
case VNC_SHARE_POLICY_IGNORE:
/*
* Ignore the shared flag. Nothing to do here.
*
* Doesn't conform to the rfb spec but is traditional qemu
* behavior, thus left here as option for compatibility
* reasons.
*/
break;
case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:
/*
* Policy: Allow clients ask for exclusive access.
*
* Implementation: When a client asks for exclusive access,
* disconnect all others. Shared connects are allowed as long
* as no exclusive connection exists.
*
* This is how the rfb spec suggests to handle the shared flag.
*/
if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
VncState *client;
QTAILQ_FOREACH(client, &vs->vd->clients, next) {
if (vs == client) {
continue;
}
if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&
client->share_mode != VNC_SHARE_MODE_SHARED) {
continue;
}
vnc_disconnect_start(client);
}
}
if (mode == VNC_SHARE_MODE_SHARED) {
if (vs->vd->num_exclusive > 0) {
vnc_disconnect_start(vs);
return 0;
}
}
break;
case VNC_SHARE_POLICY_FORCE_SHARED:
/*
* Policy: Shared connects only.
* Implementation: Disallow clients asking for exclusive access.
*
* Useful for shared desktop sessions where you don't want
* someone forgetting to say -shared when running the vnc
* client disconnect everybody else.
*/
if (mode == VNC_SHARE_MODE_EXCLUSIVE) {
vnc_disconnect_start(vs);
return 0;
}
break;
}
vnc_set_share_mode(vs, mode);
vs->client_width = surface_width(vs->vd->ds);
vs->client_height = surface_height(vs->vd->ds);
vnc_write_u16(vs, vs->client_width);
vnc_write_u16(vs, vs->client_height);
pixel_format_message(vs);
if (qemu_name)
size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);
else
size = snprintf(buf, sizeof(buf), "QEMU");
vnc_write_u32(vs, size);
vnc_write(vs, buf, size);
vnc_flush(vs);
vnc_client_cache_auth(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);
vnc_read_when(vs, protocol_client_msg, 1);
return 0;
}
void start_client_init(VncState *vs)
{
vnc_read_when(vs, protocol_client_init, 1);
}
static void make_challenge(VncState *vs)
{
int i;
srand(time(NULL)+getpid()+getpid()*987654+rand());
for (i = 0 ; i < sizeof(vs->challenge) ; i++)
vs->challenge[i] = (int) (256.0*rand()/(RAND_MAX+1.0));
}
static int protocol_client_auth_vnc(VncState *vs, uint8_t *data, size_t len)
{
unsigned char response[VNC_AUTH_CHALLENGE_SIZE];
int i, j, pwlen;
unsigned char key[8];
time_t now = time(NULL);
if (!vs->vd->password) {
VNC_DEBUG("No password configured on server");
goto reject;
}
if (vs->vd->expires < now) {
VNC_DEBUG("Password is expired");
goto reject;
}
memcpy(response, vs->challenge, VNC_AUTH_CHALLENGE_SIZE);
/* Calculate the expected challenge response */
pwlen = strlen(vs->vd->password);
for (i=0; i<sizeof(key); i++)
key[i] = i<pwlen ? vs->vd->password[i] : 0;
deskey(key, EN0);
for (j = 0; j < VNC_AUTH_CHALLENGE_SIZE; j += 8)
des(response+j, response+j);
/* Compare expected vs actual challenge response */
if (memcmp(response, data, VNC_AUTH_CHALLENGE_SIZE) != 0) {
VNC_DEBUG("Client challenge response did not match\n");
goto reject;
} else {
VNC_DEBUG("Accepting VNC challenge response\n");
vnc_write_u32(vs, 0); /* Accept auth */
vnc_flush(vs);
start_client_init(vs);
}
return 0;
reject:
vnc_write_u32(vs, 1); /* Reject auth */
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_flush(vs);
vnc_client_error(vs);
return 0;
}
void start_auth_vnc(VncState *vs)
{
make_challenge(vs);
/* Send client a 'random' challenge */
vnc_write(vs, vs->challenge, sizeof(vs->challenge));
vnc_flush(vs);
vnc_read_when(vs, protocol_client_auth_vnc, sizeof(vs->challenge));
}
static int protocol_client_auth(VncState *vs, uint8_t *data, size_t len)
{
/* We only advertise 1 auth scheme at a time, so client
* must pick the one we sent. Verify this */
if (data[0] != vs->auth) { /* Reject auth */
VNC_DEBUG("Reject auth %d because it didn't match advertized\n", (int)data[0]);
vnc_write_u32(vs, 1);
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_client_error(vs);
} else { /* Accept requested auth */
VNC_DEBUG("Client requested auth %d\n", (int)data[0]);
switch (vs->auth) {
case VNC_AUTH_NONE:
VNC_DEBUG("Accept auth none\n");
if (vs->minor >= 8) {
vnc_write_u32(vs, 0); /* Accept auth completion */
vnc_flush(vs);
}
start_client_init(vs);
break;
case VNC_AUTH_VNC:
VNC_DEBUG("Start VNC auth\n");
start_auth_vnc(vs);
break;
#ifdef CONFIG_VNC_TLS
case VNC_AUTH_VENCRYPT:
VNC_DEBUG("Accept VeNCrypt auth\n");
start_auth_vencrypt(vs);
break;
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
case VNC_AUTH_SASL:
VNC_DEBUG("Accept SASL auth\n");
start_auth_sasl(vs);
break;
#endif /* CONFIG_VNC_SASL */
default: /* Should not be possible, but just in case */
VNC_DEBUG("Reject auth %d server code bug\n", vs->auth);
vnc_write_u8(vs, 1);
if (vs->minor >= 8) {
static const char err[] = "Authentication failed";
vnc_write_u32(vs, sizeof(err));
vnc_write(vs, err, sizeof(err));
}
vnc_client_error(vs);
}
}
return 0;
}
static int protocol_version(VncState *vs, uint8_t *version, size_t len)
{
char local[13];
memcpy(local, version, 12);
local[12] = 0;
if (sscanf(local, "RFB %03d.%03d\n", &vs->major, &vs->minor) != 2) {
VNC_DEBUG("Malformed protocol version %s\n", local);
vnc_client_error(vs);
return 0;
}
VNC_DEBUG("Client request protocol version %d.%d\n", vs->major, vs->minor);
if (vs->major != 3 ||
(vs->minor != 3 &&
vs->minor != 4 &&
vs->minor != 5 &&
vs->minor != 7 &&
vs->minor != 8)) {
VNC_DEBUG("Unsupported client version\n");
vnc_write_u32(vs, VNC_AUTH_INVALID);
vnc_flush(vs);
vnc_client_error(vs);
return 0;
}
/* Some broken clients report v3.4 or v3.5, which spec requires to be treated
* as equivalent to v3.3 by servers
*/
if (vs->minor == 4 || vs->minor == 5)
vs->minor = 3;
if (vs->minor == 3) {
if (vs->auth == VNC_AUTH_NONE) {
VNC_DEBUG("Tell client auth none\n");
vnc_write_u32(vs, vs->auth);
vnc_flush(vs);
start_client_init(vs);
} else if (vs->auth == VNC_AUTH_VNC) {
VNC_DEBUG("Tell client VNC auth\n");
vnc_write_u32(vs, vs->auth);
vnc_flush(vs);
start_auth_vnc(vs);
} else {
VNC_DEBUG("Unsupported auth %d for protocol 3.3\n", vs->auth);
vnc_write_u32(vs, VNC_AUTH_INVALID);
vnc_flush(vs);
vnc_client_error(vs);
}
} else {
VNC_DEBUG("Telling client we support auth %d\n", vs->auth);
vnc_write_u8(vs, 1); /* num auth */
vnc_write_u8(vs, vs->auth);
vnc_read_when(vs, protocol_client_auth, 1);
vnc_flush(vs);
}
return 0;
}
static VncRectStat *vnc_stat_rect(VncDisplay *vd, int x, int y)
{
struct VncSurface *vs = &vd->guest;
return &vs->stats[y / VNC_STAT_RECT][x / VNC_STAT_RECT];
}
void vnc_sent_lossy_rect(VncState *vs, int x, int y, int w, int h)
{
int i, j;
w = (x + w) / VNC_STAT_RECT;
h = (y + h) / VNC_STAT_RECT;
x /= VNC_STAT_RECT;
y /= VNC_STAT_RECT;
for (j = y; j <= h; j++) {
for (i = x; i <= w; i++) {
vs->lossy_rect[j][i] = 1;
}
}
}
static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)
{
VncState *vs;
int sty = y / VNC_STAT_RECT;
int stx = x / VNC_STAT_RECT;
int has_dirty = 0;
y = y / VNC_STAT_RECT * VNC_STAT_RECT;
x = x / VNC_STAT_RECT * VNC_STAT_RECT;
QTAILQ_FOREACH(vs, &vd->clients, next) {
int j;
/* kernel send buffers are full -> refresh later */
if (vs->output.offset) {
continue;
}
if (!vs->lossy_rect[sty][stx]) {
continue;
}
vs->lossy_rect[sty][stx] = 0;
for (j = 0; j < VNC_STAT_RECT; ++j) {
bitmap_set(vs->dirty[y + j],
x / VNC_DIRTY_PIXELS_PER_BIT,
VNC_STAT_RECT / VNC_DIRTY_PIXELS_PER_BIT);
}
has_dirty++;
}
return has_dirty;
}
static int vnc_update_stats(VncDisplay *vd, struct timeval * tv)
{
int width = pixman_image_get_width(vd->guest.fb);
int height = pixman_image_get_height(vd->guest.fb);
int x, y;
struct timeval res;
int has_dirty = 0;
for (y = 0; y < height; y += VNC_STAT_RECT) {
for (x = 0; x < width; x += VNC_STAT_RECT) {
VncRectStat *rect = vnc_stat_rect(vd, x, y);
rect->updated = false;
}
}
qemu_timersub(tv, &VNC_REFRESH_STATS, &res);
if (timercmp(&vd->guest.last_freq_check, &res, >)) {
return has_dirty;
}
vd->guest.last_freq_check = *tv;
for (y = 0; y < height; y += VNC_STAT_RECT) {
for (x = 0; x < width; x += VNC_STAT_RECT) {
VncRectStat *rect= vnc_stat_rect(vd, x, y);
int count = ARRAY_SIZE(rect->times);
struct timeval min, max;
if (!timerisset(&rect->times[count - 1])) {
continue ;
}
max = rect->times[(rect->idx + count - 1) % count];
qemu_timersub(tv, &max, &res);
if (timercmp(&res, &VNC_REFRESH_LOSSY, >)) {
rect->freq = 0;
has_dirty += vnc_refresh_lossy_rect(vd, x, y);
memset(rect->times, 0, sizeof (rect->times));
continue ;
}
min = rect->times[rect->idx];
max = rect->times[(rect->idx + count - 1) % count];
qemu_timersub(&max, &min, &res);
rect->freq = res.tv_sec + res.tv_usec / 1000000.;
rect->freq /= count;
rect->freq = 1. / rect->freq;
}
}
return has_dirty;
}
double vnc_update_freq(VncState *vs, int x, int y, int w, int h)
{
int i, j;
double total = 0;
int num = 0;
x = (x / VNC_STAT_RECT) * VNC_STAT_RECT;
y = (y / VNC_STAT_RECT) * VNC_STAT_RECT;
for (j = y; j <= y + h; j += VNC_STAT_RECT) {
for (i = x; i <= x + w; i += VNC_STAT_RECT) {
total += vnc_stat_rect(vs->vd, i, j)->freq;
num++;
}
}
if (num) {
return total / num;
} else {
return 0;
}
}
static void vnc_rect_updated(VncDisplay *vd, int x, int y, struct timeval * tv)
{
VncRectStat *rect;
rect = vnc_stat_rect(vd, x, y);
if (rect->updated) {
return ;
}
rect->times[rect->idx] = *tv;
rect->idx = (rect->idx + 1) % ARRAY_SIZE(rect->times);
rect->updated = true;
}
static int vnc_refresh_server_surface(VncDisplay *vd)
{
int width = pixman_image_get_width(vd->guest.fb);
int height = pixman_image_get_height(vd->guest.fb);
int y;
uint8_t *guest_row0 = NULL, *server_row0;
int guest_stride = 0, server_stride;
int cmp_bytes;
VncState *vs;
int has_dirty = 0;
pixman_image_t *tmpbuf = NULL;
struct timeval tv = { 0, 0 };
if (!vd->non_adaptive) {
gettimeofday(&tv, NULL);
has_dirty = vnc_update_stats(vd, &tv);
}
/*
* Walk through the guest dirty map.
* Check and copy modified bits from guest to server surface.
* Update server dirty map.
*/
cmp_bytes = VNC_DIRTY_PIXELS_PER_BIT * VNC_SERVER_FB_BYTES;
if (cmp_bytes > vnc_server_fb_stride(vd)) {
cmp_bytes = vnc_server_fb_stride(vd);
}
if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
int width = pixman_image_get_width(vd->server);
tmpbuf = qemu_pixman_linebuf_create(VNC_SERVER_FB_FORMAT, width);
} else {
guest_row0 = (uint8_t *)pixman_image_get_data(vd->guest.fb);
guest_stride = pixman_image_get_stride(vd->guest.fb);
}
server_row0 = (uint8_t *)pixman_image_get_data(vd->server);
server_stride = pixman_image_get_stride(vd->server);
y = 0;
for (;;) {
int x;
uint8_t *guest_ptr, *server_ptr;
unsigned long offset = find_next_bit((unsigned long *) &vd->guest.dirty,
height * VNC_DIRTY_BPL(&vd->guest),
y * VNC_DIRTY_BPL(&vd->guest));
if (offset == height * VNC_DIRTY_BPL(&vd->guest)) {
/* no more dirty bits */
break;
}
y = offset / VNC_DIRTY_BPL(&vd->guest);
x = offset % VNC_DIRTY_BPL(&vd->guest);
server_ptr = server_row0 + y * server_stride + x * cmp_bytes;
if (vd->guest.format != VNC_SERVER_FB_FORMAT) {
qemu_pixman_linebuf_fill(tmpbuf, vd->guest.fb, width, 0, y);
guest_ptr = (uint8_t *)pixman_image_get_data(tmpbuf);
} else {
guest_ptr = guest_row0 + y * guest_stride;
}
guest_ptr += x * cmp_bytes;
for (; x < DIV_ROUND_UP(width, VNC_DIRTY_PIXELS_PER_BIT);
x++, guest_ptr += cmp_bytes, server_ptr += cmp_bytes) {
if (!test_and_clear_bit(x, vd->guest.dirty[y])) {
continue;
}
if (memcmp(server_ptr, guest_ptr, cmp_bytes) == 0) {
continue;
}
memcpy(server_ptr, guest_ptr, cmp_bytes);
if (!vd->non_adaptive) {
vnc_rect_updated(vd, x * VNC_DIRTY_PIXELS_PER_BIT,
y, &tv);
}
QTAILQ_FOREACH(vs, &vd->clients, next) {
set_bit(x, vs->dirty[y]);
}
has_dirty++;
}
y++;
}
qemu_pixman_image_unref(tmpbuf);
return has_dirty;
}
static void vnc_refresh(DisplayChangeListener *dcl)
{
VncDisplay *vd = container_of(dcl, VncDisplay, dcl);
VncState *vs, *vn;
int has_dirty, rects = 0;
graphic_hw_update(NULL);
if (vnc_trylock_display(vd)) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
return;
}
has_dirty = vnc_refresh_server_surface(vd);
vnc_unlock_display(vd);
QTAILQ_FOREACH_SAFE(vs, &vd->clients, next, vn) {
rects += vnc_update_client(vs, has_dirty, false);
/* vs might be free()ed here */
}
if (QTAILQ_EMPTY(&vd->clients)) {
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_MAX);
return;
}
if (has_dirty && rects) {
vd->dcl.update_interval /= 2;
if (vd->dcl.update_interval < VNC_REFRESH_INTERVAL_BASE) {
vd->dcl.update_interval = VNC_REFRESH_INTERVAL_BASE;
}
} else {
vd->dcl.update_interval += VNC_REFRESH_INTERVAL_INC;
if (vd->dcl.update_interval > VNC_REFRESH_INTERVAL_MAX) {
vd->dcl.update_interval = VNC_REFRESH_INTERVAL_MAX;
}
}
}
static void vnc_connect(VncDisplay *vd, int csock,
bool skipauth, bool websocket)
{
VncState *vs = g_malloc0(sizeof(VncState));
int i;
vs->csock = csock;
if (skipauth) {
vs->auth = VNC_AUTH_NONE;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
#endif
} else {
vs->auth = vd->auth;
#ifdef CONFIG_VNC_TLS
vs->subauth = vd->subauth;
#endif
}
vs->lossy_rect = g_malloc0(VNC_STAT_ROWS * sizeof (*vs->lossy_rect));
for (i = 0; i < VNC_STAT_ROWS; ++i) {
vs->lossy_rect[i] = g_malloc0(VNC_STAT_COLS * sizeof (uint8_t));
}
VNC_DEBUG("New client on socket %d\n", csock);
update_displaychangelistener(&vd->dcl, VNC_REFRESH_INTERVAL_BASE);
qemu_set_nonblock(vs->csock);
#ifdef CONFIG_VNC_WS
if (websocket) {
vs->websocket = 1;
#ifdef CONFIG_VNC_TLS
if (vd->tls.x509cert) {
qemu_set_fd_handler2(vs->csock, NULL, vncws_tls_handshake_peek,
NULL, vs);
} else
#endif /* CONFIG_VNC_TLS */
{
qemu_set_fd_handler2(vs->csock, NULL, vncws_handshake_read,
NULL, vs);
}
} else
#endif /* CONFIG_VNC_WS */
{
qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
}
vnc_client_cache_addr(vs);
vnc_qmp_event(vs, QAPI_EVENT_VNC_CONNECTED);
vnc_set_share_mode(vs, VNC_SHARE_MODE_CONNECTING);
vs->vd = vd;
#ifdef CONFIG_VNC_WS
if (!vs->websocket)
#endif
{
vnc_init_state(vs);
}
}
void vnc_init_state(VncState *vs)
{
vs->initialized = true;
VncDisplay *vd = vs->vd;
vs->last_x = -1;
vs->last_y = -1;
vs->as.freq = 44100;
vs->as.nchannels = 2;
vs->as.fmt = AUD_FMT_S16;
vs->as.endianness = 0;
qemu_mutex_init(&vs->output_mutex);
vs->bh = qemu_bh_new(vnc_jobs_bh, vs);
QTAILQ_INSERT_HEAD(&vd->clients, vs, next);
graphic_hw_update(NULL);
vnc_write(vs, "RFB 003.008\n", 12);
vnc_flush(vs);
vnc_read_when(vs, protocol_version, 12);
reset_keys(vs);
if (vs->vd->lock_key_sync)
vs->led = qemu_add_led_event_handler(kbd_leds, vs);
vs->mouse_mode_notifier.notify = check_pointer_type_change;
qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);
/* vs might be free()ed here */
}
static void vnc_listen_read(void *opaque, bool websocket)
{
VncDisplay *vs = opaque;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
int csock;
/* Catch-up */
graphic_hw_update(NULL);
#ifdef CONFIG_VNC_WS
if (websocket) {
csock = qemu_accept(vs->lwebsock, (struct sockaddr *)&addr, &addrlen);
} else
#endif /* CONFIG_VNC_WS */
{
csock = qemu_accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
}
if (csock != -1) {
vnc_connect(vs, csock, false, websocket);
}
}
static void vnc_listen_regular_read(void *opaque)
{
vnc_listen_read(opaque, false);
}
#ifdef CONFIG_VNC_WS
static void vnc_listen_websocket_read(void *opaque)
{
vnc_listen_read(opaque, true);
}
#endif /* CONFIG_VNC_WS */
static const DisplayChangeListenerOps dcl_ops = {
.dpy_name = "vnc",
.dpy_refresh = vnc_refresh,
.dpy_gfx_copy = vnc_dpy_copy,
.dpy_gfx_update = vnc_dpy_update,
.dpy_gfx_switch = vnc_dpy_switch,
.dpy_mouse_set = vnc_mouse_set,
.dpy_cursor_define = vnc_dpy_cursor_define,
};
void vnc_display_init(DisplayState *ds)
{
VncDisplay *vs = g_malloc0(sizeof(*vs));
vnc_display = vs;
vs->lsock = -1;
#ifdef CONFIG_VNC_WS
vs->lwebsock = -1;
#endif
QTAILQ_INIT(&vs->clients);
vs->expires = TIME_MAX;
if (keyboard_layout) {
trace_vnc_key_map_init(keyboard_layout);
vs->kbd_layout = init_keyboard_layout(name2keysym, keyboard_layout);
} else {
vs->kbd_layout = init_keyboard_layout(name2keysym, "en-us");
}
if (!vs->kbd_layout)
exit(1);
qemu_mutex_init(&vs->mutex);
vnc_start_worker_thread();
vs->dcl.ops = &dcl_ops;
register_displaychangelistener(&vs->dcl);
}
static void vnc_display_close(DisplayState *ds)
{
VncDisplay *vs = vnc_display;
if (!vs)
return;
g_free(vs->display);
vs->display = NULL;
if (vs->lsock != -1) {
qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);
close(vs->lsock);
vs->lsock = -1;
}
#ifdef CONFIG_VNC_WS
g_free(vs->ws_display);
vs->ws_display = NULL;
if (vs->lwebsock != -1) {
qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);
close(vs->lwebsock);
vs->lwebsock = -1;
}
#endif /* CONFIG_VNC_WS */
vs->auth = VNC_AUTH_INVALID;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
vs->tls.x509verify = 0;
#endif
}
int vnc_display_password(DisplayState *ds, const char *password)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -EINVAL;
}
if (vs->auth == VNC_AUTH_NONE) {
error_printf_unless_qmp("If you want use passwords please enable "
"password auth using '-vnc ${dpy},password'.");
return -EINVAL;
}
g_free(vs->password);
vs->password = g_strdup(password);
return 0;
}
int vnc_display_pw_expire(DisplayState *ds, time_t expires)
{
VncDisplay *vs = vnc_display;
if (!vs) {
return -EINVAL;
}
vs->expires = expires;
return 0;
}
char *vnc_display_local_addr(DisplayState *ds)
{
VncDisplay *vs = vnc_display;
return vnc_socket_local_addr("%s:%s", vs->lsock);
}
void vnc_display_open(DisplayState *ds, const char *display, Error **errp)
{
VncDisplay *vs = vnc_display;
const char *options;
int password = 0;
int reverse = 0;
#ifdef CONFIG_VNC_TLS
int tls = 0, x509 = 0;
#endif
#ifdef CONFIG_VNC_SASL
int sasl = 0;
int saslErr;
#endif
#if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
int acl = 0;
#endif
int lock_key_sync = 1;
if (!vnc_display) {
error_setg(errp, "VNC display not active");
return;
}
vnc_display_close(ds);
if (strcmp(display, "none") == 0)
return;
vs->display = g_strdup(display);
vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
options = display;
while ((options = strchr(options, ','))) {
options++;
if (strncmp(options, "password", 8) == 0) {
if (fips_get_state()) {
error_setg(errp,
"VNC password auth disabled due to FIPS mode, "
"consider using the VeNCrypt or SASL authentication "
"methods as an alternative");
goto fail;
}
password = 1; /* Require password auth */
} else if (strncmp(options, "reverse", 7) == 0) {
reverse = 1;
} else if (strncmp(options, "no-lock-key-sync", 16) == 0) {
lock_key_sync = 0;
#ifdef CONFIG_VNC_SASL
} else if (strncmp(options, "sasl", 4) == 0) {
sasl = 1; /* Require SASL auth */
#endif
#ifdef CONFIG_VNC_WS
} else if (strncmp(options, "websocket", 9) == 0) {
char *start, *end;
vs->websocket = 1;
/* Check for 'websocket=<port>' */
start = strchr(options, '=');
end = strchr(options, ',');
if (start && (!end || (start < end))) {
int len = end ? end-(start+1) : strlen(start+1);
if (len < 6) {
/* extract the host specification from display */
char *host = NULL, *port = NULL, *host_end = NULL;
port = g_strndup(start + 1, len);
/* ipv6 hosts have colons */
end = strchr(display, ',');
host_end = g_strrstr_len(display, end - display, ":");
if (host_end) {
host = g_strndup(display, host_end - display + 1);
} else {
host = g_strndup(":", 1);
}
vs->ws_display = g_strconcat(host, port, NULL);
g_free(host);
g_free(port);
}
}
#endif /* CONFIG_VNC_WS */
#ifdef CONFIG_VNC_TLS
} else if (strncmp(options, "tls", 3) == 0) {
tls = 1; /* Require TLS */
} else if (strncmp(options, "x509", 4) == 0) {
char *start, *end;
x509 = 1; /* Require x509 certificates */
if (strncmp(options, "x509verify", 10) == 0)
vs->tls.x509verify = 1; /* ...and verify client certs */
/* Now check for 'x509=/some/path' postfix
* and use that to setup x509 certificate/key paths */
start = strchr(options, '=');
end = strchr(options, ',');
if (start && (!end || (start < end))) {
int len = end ? end-(start+1) : strlen(start+1);
char *path = g_strndup(start + 1, len);
VNC_DEBUG("Trying certificate path '%s'\n", path);
if (vnc_tls_set_x509_creds_dir(vs, path) < 0) {
error_setg(errp, "Failed to find x509 certificates/keys in %s", path);
g_free(path);
goto fail;
}
g_free(path);
} else {
error_setg(errp, "No certificate path provided");
goto fail;
}
#endif
#if defined(CONFIG_VNC_TLS) || defined(CONFIG_VNC_SASL)
} else if (strncmp(options, "acl", 3) == 0) {
acl = 1;
#endif
} else if (strncmp(options, "lossy", 5) == 0) {
#ifdef CONFIG_VNC_JPEG
vs->lossy = true;
#endif
} else if (strncmp(options, "non-adaptive", 12) == 0) {
vs->non_adaptive = true;
} else if (strncmp(options, "share=", 6) == 0) {
if (strncmp(options+6, "ignore", 6) == 0) {
vs->share_policy = VNC_SHARE_POLICY_IGNORE;
} else if (strncmp(options+6, "allow-exclusive", 15) == 0) {
vs->share_policy = VNC_SHARE_POLICY_ALLOW_EXCLUSIVE;
} else if (strncmp(options+6, "force-shared", 12) == 0) {
vs->share_policy = VNC_SHARE_POLICY_FORCE_SHARED;
} else {
error_setg(errp, "unknown vnc share= option");
goto fail;
}
}
}
/* adaptive updates are only used with tight encoding and
* if lossy updates are enabled so we can disable all the
* calculations otherwise */
if (!vs->lossy) {
vs->non_adaptive = true;
}
#ifdef CONFIG_VNC_TLS
if (acl && x509 && vs->tls.x509verify) {
if (!(vs->tls.acl = qemu_acl_init("vnc.x509dname"))) {
fprintf(stderr, "Failed to create x509 dname ACL\n");
exit(1);
}
}
#endif
#ifdef CONFIG_VNC_SASL
if (acl && sasl) {
if (!(vs->sasl.acl = qemu_acl_init("vnc.username"))) {
fprintf(stderr, "Failed to create username ACL\n");
exit(1);
}
}
#endif
/*
* Combinations we support here:
*
* - no-auth (clear text, no auth)
* - password (clear text, weak auth)
* - sasl (encrypt, good auth *IF* using Kerberos via GSSAPI)
* - tls (encrypt, weak anonymous creds, no auth)
* - tls + password (encrypt, weak anonymous creds, weak auth)
* - tls + sasl (encrypt, weak anonymous creds, good auth)
* - tls + x509 (encrypt, good x509 creds, no auth)
* - tls + x509 + password (encrypt, good x509 creds, weak auth)
* - tls + x509 + sasl (encrypt, good x509 creds, good auth)
*
* NB1. TLS is a stackable auth scheme.
* NB2. the x509 schemes have option to validate a client cert dname
*/
if (password) {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 password auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;
} else {
VNC_DEBUG("Initializing VNC server with TLS password auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;
}
} else {
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Initializing VNC server with password auth\n");
vs->auth = VNC_AUTH_VNC;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif /* CONFIG_VNC_TLS */
#ifdef CONFIG_VNC_SASL
} else if (sasl) {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;
} else {
VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;
}
} else {
#endif /* CONFIG_VNC_TLS */
VNC_DEBUG("Initializing VNC server with SASL auth\n");
vs->auth = VNC_AUTH_SASL;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif /* CONFIG_VNC_TLS */
#endif /* CONFIG_VNC_SASL */
} else {
#ifdef CONFIG_VNC_TLS
if (tls) {
vs->auth = VNC_AUTH_VENCRYPT;
if (x509) {
VNC_DEBUG("Initializing VNC server with x509 no auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;
} else {
VNC_DEBUG("Initializing VNC server with TLS no auth\n");
vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;
}
} else {
#endif
VNC_DEBUG("Initializing VNC server with no auth\n");
vs->auth = VNC_AUTH_NONE;
#ifdef CONFIG_VNC_TLS
vs->subauth = VNC_AUTH_INVALID;
}
#endif
}
#ifdef CONFIG_VNC_SASL
if ((saslErr = sasl_server_init(NULL, "qemu")) != SASL_OK) {
error_setg(errp, "Failed to initialize SASL auth: %s",
sasl_errstring(saslErr, NULL, NULL));
goto fail;
}
#endif
vs->lock_key_sync = lock_key_sync;
if (reverse) {
/* connect to viewer */
int csock;
vs->lsock = -1;
#ifdef CONFIG_VNC_WS
vs->lwebsock = -1;
#endif
if (strncmp(display, "unix:", 5) == 0) {
csock = unix_connect(display+5, errp);
} else {
csock = inet_connect(display, errp);
}
if (csock < 0) {
goto fail;
}
vnc_connect(vs, csock, false, false);
} else {
/* listen for connects */
char *dpy;
dpy = g_malloc(256);
if (strncmp(display, "unix:", 5) == 0) {
pstrcpy(dpy, 256, "unix:");
vs->lsock = unix_listen(display+5, dpy+5, 256-5, errp);
} else {
vs->lsock = inet_listen(display, dpy, 256,
SOCK_STREAM, 5900, errp);
if (vs->lsock < 0) {
g_free(dpy);
goto fail;
}
#ifdef CONFIG_VNC_WS
if (vs->websocket) {
if (vs->ws_display) {
vs->lwebsock = inet_listen(vs->ws_display, NULL, 256,
SOCK_STREAM, 0, errp);
} else {
vs->lwebsock = inet_listen(vs->display, NULL, 256,
SOCK_STREAM, 5700, errp);
}
if (vs->lwebsock < 0) {
if (vs->lsock) {
close(vs->lsock);
vs->lsock = -1;
}
g_free(dpy);
goto fail;
}
}
#endif /* CONFIG_VNC_WS */
}
g_free(vs->display);
vs->display = dpy;
qemu_set_fd_handler2(vs->lsock, NULL,
vnc_listen_regular_read, NULL, vs);
#ifdef CONFIG_VNC_WS
if (vs->websocket) {
qemu_set_fd_handler2(vs->lwebsock, NULL,
vnc_listen_websocket_read, NULL, vs);
}
#endif /* CONFIG_VNC_WS */
}
return;
fail:
g_free(vs->display);
vs->display = NULL;
#ifdef CONFIG_VNC_WS
g_free(vs->ws_display);
vs->ws_display = NULL;
#endif /* CONFIG_VNC_WS */
}
void vnc_display_add_client(DisplayState *ds, int csock, bool skipauth)
{
VncDisplay *vs = vnc_display;
vnc_connect(vs, csock, skipauth, false);
}
| ./CrossVul/dataset_final_sorted/CWE-835/c/bad_1665_0 |
crossvul-cpp_data_good_616_1 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
void StreamTcpPseudoPacketCreateStreamEndPacket(ThreadVars *tv, StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (stream->seg_list_tail != NULL) {
if (SEQ_GT((stream->seg_list_tail->seq + TCP_SEG_LEN(stream->seg_list_tail)), ack))
{
ack = stream->seg_list_tail->seq + TCP_SEG_LEN(stream->seg_list_tail);
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
#ifdef DEBUG
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
#endif
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
switch (ssn->state) {
case TCP_SYN_SENT:
if(StreamTcpPacketStateSynSent(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_SYN_RECV:
if(StreamTcpPacketStateSynRecv(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_ESTABLISHED:
if(StreamTcpPacketStateEstablished(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT1:
if(StreamTcpPacketStateFinWait1(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT2:
if(StreamTcpPacketStateFinWait2(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSING:
if(StreamTcpPacketStateClosing(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSE_WAIT:
if(StreamTcpPacketStateCloseWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_LAST_ACK:
if(StreamTcpPacketStateLastAck(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_TIME_WAIT:
if(StreamTcpPacketStateTimeWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
break;
default:
SCLogDebug("packet received on default state");
break;
}
skip:
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/**
* \brief Function to setup the IP and TCP header of the pseudo packet from
* the newly copied raw packet contents of the parent.
*
* @param np pointer to the pseudo packet
* @param p pointer to the original packet
*/
static void StreamTcpPseudoPacketSetupHeader(Packet *np, Packet *p)
{
/* Setup the IP header */
if (PKT_IS_IPV4(p)) {
np->ip4h = (IPV4Hdr *)((uint8_t *)GET_PKT_DATA(np) + (GET_PKT_LEN(np) - IPV4_GET_IPLEN(p)));
PSEUDO_PKT_SET_IPV4HDR(np->ip4h, p->ip4h);
/* Similarly setup the TCP header with ports in opposite direction */
np->tcph = (TCPHdr *)((uint8_t *)np->ip4h + IPV4_GET_HLEN(np));
PSEUDO_PKT_SET_TCPHDR(np->tcph, p->tcph);
/* Setup the adress and port details */
SET_IPV4_SRC_ADDR(p, &np->dst);
SET_IPV4_DST_ADDR(p, &np->src);
SET_TCP_SRC_PORT(p, &np->dp);
SET_TCP_DST_PORT(p, &np->sp);
} else if (PKT_IS_IPV6(p)) {
np->ip6h = (IPV6Hdr *)((uint8_t *)GET_PKT_DATA(np) + (GET_PKT_LEN(np) - IPV6_GET_PLEN(p) - IPV6_HEADER_LEN));
PSEUDO_PKT_SET_IPV6HDR(np->ip6h, p->ip6h);
/* Similarly setup the TCP header with ports in opposite direction */
np->tcph = (TCPHdr *)((uint8_t *)np->ip6h + IPV6_HEADER_LEN);
PSEUDO_PKT_SET_TCPHDR(np->tcph, p->tcph);
/* Setup the adress and port details */
SET_IPV6_SRC_ADDR(p, &np->dst);
SET_IPV6_DST_ADDR(p, &np->src);
SET_TCP_SRC_PORT(p, &np->dp);
SET_TCP_DST_PORT(p, &np->sp);
}
/* we don't need a payload (if any) */
np->payload = NULL;
np->payload_len = 0;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream to wrap up stream reassembly.
*
* \param p real packet
* \param pq packet queue to store the new pseudo packet in
*/
void StreamTcpPseudoPacketCreateStreamEndPacket(ThreadVars *tv, StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (p->flags & PKT_PSEUDO_STREAM_END) {
SCReturn;
}
/* no need for a pseudo packet if there is nothing left to reassemble */
if (ssn->server.seg_list == NULL && ssn->client.seg_list == NULL) {
SCReturn;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
SCLogDebug("The packet received from packet allocation is NULL");
StatsIncr(tv, stt->counter_tcp_pseudo_failed);
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_STREAM_END_PSEUDO);
/* Setup the IP and TCP headers */
StreamTcpPseudoPacketSetupHeader(np,p);
np->tenant_id = p->flow->tenant_id;
np->flowflags = p->flowflags;
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_STREAM_EOF;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_PSEUDO_STREAM_END;
if (p->flags & PKT_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (p->flags & PKT_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("original is to_server, so pseudo is to_client");
np->flowflags &= ~FLOW_PKT_TOSERVER;
np->flowflags |= FLOW_PKT_TOCLIENT;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOCLIENT(np)));
BUG_ON((PKT_IS_TOSERVER(np)));
#endif
} else if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("original is to_client, so pseudo is to_server");
np->flowflags &= ~FLOW_PKT_TOCLIENT;
np->flowflags |= FLOW_PKT_TOSERVER;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOSERVER(np)));
BUG_ON((PKT_IS_TOCLIENT(np)));
#endif
}
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param p real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq, bool dir)
{
SCEnter();
if (p->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
SCLogDebug("The packet received from packet allocation is NULL");
StatsIncr(tv, stt->counter_tcp_pseudo_failed);
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
/* Setup the IP and TCP headers */
StreamTcpPseudoPacketSetupHeader(np,p);
np->tenant_id = p->flow->tenant_id;
np->flowflags = p->flowflags;
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (p->flags & PKT_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (p->flags & PKT_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == false) {
SCLogDebug("pseudo is to_client");
np->flowflags &= ~(FLOW_PKT_TOSERVER|FLOW_PKT_TOCLIENT);
np->flowflags |= FLOW_PKT_TOCLIENT;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOCLIENT(np)));
BUG_ON((PKT_IS_TOSERVER(np)));
#endif
} else {
SCLogDebug("pseudo is to_server");
np->flowflags &= ~(FLOW_PKT_TOCLIENT|FLOW_PKT_TOSERVER);
np->flowflags |= FLOW_PKT_TOSERVER;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOSERVER(np)));
BUG_ON((PKT_IS_TOCLIENT(np)));
#endif
}
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg = stream->seg_list;
for (; seg != NULL &&
((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack));)
{
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
seg = seg->next;
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.seg_list->next != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
FAIL_IF(ssn.client.seg_list_tail == NULL);
FAIL_IF(TCP_SEG_LEN(ssn.client.seg_list_tail) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
FAIL_IF(ssn.client.seg_list_tail == NULL);
FAIL_IF(TCP_SEG_LEN(ssn.client.seg_list_tail) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
static int StreamTcpTest40(void)
{
uint8_t raw_vlan[] = {
0x00, 0x20, 0x08, 0x00, 0x45, 0x00, 0x00, 0x34,
0x3b, 0x36, 0x40, 0x00, 0x40, 0x06, 0xb7, 0xc9,
0x83, 0x97, 0x20, 0x81, 0x83, 0x97, 0x20, 0x15,
0x04, 0x8a, 0x17, 0x70, 0x4e, 0x14, 0xdf, 0x55,
0x4d, 0x3d, 0x5a, 0x61, 0x80, 0x10, 0x6b, 0x50,
0x3c, 0x4c, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a,
0x00, 0x04, 0xf0, 0xc8, 0x01, 0x99, 0xa3, 0xf3
};
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
ThreadVars tv;
DecodeThreadVars dtv;
memset(&tv, 0, sizeof(ThreadVars));
memset(p, 0, SIZE_OF_PACKET);
PACKET_INITIALIZE(p);
SET_PKT_LEN(p, sizeof(raw_vlan));
memcpy(GET_PKT_DATA(p), raw_vlan, sizeof(raw_vlan));
memset(&dtv, 0, sizeof(DecodeThreadVars));
FlowInitConfig(FLOW_QUIET);
DecodeVLAN(&tv, &dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), NULL);
FAIL_IF(p->vlanh[0] == NULL);
FAIL_IF(p->tcph == NULL);
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
FAIL_IF(np == NULL);
StreamTcpPseudoPacketSetupHeader(np,p);
FAIL_IF(((uint8_t *)p->tcph - (uint8_t *)p->ip4h) != ((uint8_t *)np->tcph - (uint8_t *)np->ip4h));
PACKET_DESTRUCTOR(np);
PACKET_DESTRUCTOR(p);
FlowShutdown();
PacketFree(np);
PacketFree(p);
PASS;
}
static int StreamTcpTest41(void)
{
/* IPV6/TCP/no eth header */
uint8_t raw_ip[] = {
0x60, 0x00, 0x00, 0x00, 0x00, 0x28, 0x06, 0x40,
0x20, 0x01, 0x06, 0x18, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x51, 0x99, 0xcc, 0x70,
0x20, 0x01, 0x06, 0x18, 0x00, 0x01, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x8c, 0x9b, 0x00, 0x50, 0x6a, 0xe7, 0x07, 0x36,
0x00, 0x00, 0x00, 0x00, 0xa0, 0x02, 0x16, 0x30,
0x29, 0x9c, 0x00, 0x00, 0x02, 0x04, 0x05, 0x8c,
0x04, 0x02, 0x08, 0x0a, 0x00, 0xdd, 0x1a, 0x39,
0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x02 };
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
ThreadVars tv;
DecodeThreadVars dtv;
memset(&dtv, 0, sizeof(DecodeThreadVars));
memset(&tv, 0, sizeof(ThreadVars));
memset(p, 0, SIZE_OF_PACKET);
PACKET_INITIALIZE(p);
if (PacketCopyData(p, raw_ip, sizeof(raw_ip)) == -1) {
PacketFree(p);
return 1;
}
FlowInitConfig(FLOW_QUIET);
DecodeRaw(&tv, &dtv, p, raw_ip, GET_PKT_LEN(p), NULL);
if (p->ip6h == NULL) {
printf("expected a valid ipv6 header but it was NULL: ");
FlowShutdown();
SCFree(p);
return 1;
}
if(p->tcph == NULL) {
SCFree(p);
return 0;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
printf("the packet received from packet allocation is NULL: ");
return 0;
}
StreamTcpPseudoPacketSetupHeader(np,p);
if (((uint8_t *)p->tcph - (uint8_t *)p->ip6h) != ((uint8_t *)np->tcph - (uint8_t *)np->ip6h)) {
return 0;
}
PACKET_RECYCLE(np);
PACKET_RECYCLE(p);
SCFree(p);
FlowShutdown();
return 1;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest40 -- pseudo setup", StreamTcpTest40);
UtRegisterTest("StreamTcpTest41 -- pseudo setup", StreamTcpTest41);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-693/c/good_616_1 |
crossvul-cpp_data_bad_616_1 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
void StreamTcpPseudoPacketCreateStreamEndPacket(ThreadVars *tv, StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (stream->seg_list_tail != NULL) {
if (SEQ_GT((stream->seg_list_tail->seq + TCP_SEG_LEN(stream->seg_list_tail)), ack))
{
ack = stream->seg_list_tail->seq + TCP_SEG_LEN(stream->seg_list_tail);
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
#ifdef DEBUG
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
#endif
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
switch (ssn->state) {
case TCP_SYN_SENT:
if(StreamTcpPacketStateSynSent(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_SYN_RECV:
if(StreamTcpPacketStateSynRecv(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_ESTABLISHED:
if(StreamTcpPacketStateEstablished(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT1:
if(StreamTcpPacketStateFinWait1(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_FIN_WAIT2:
if(StreamTcpPacketStateFinWait2(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSING:
if(StreamTcpPacketStateClosing(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSE_WAIT:
if(StreamTcpPacketStateCloseWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_LAST_ACK:
if(StreamTcpPacketStateLastAck(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_TIME_WAIT:
if(StreamTcpPacketStateTimeWait(tv, p, stt, ssn, &stt->pseudo_queue)) {
goto error;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
break;
default:
SCLogDebug("packet received on default state");
break;
}
skip:
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/**
* \brief Function to setup the IP and TCP header of the pseudo packet from
* the newly copied raw packet contents of the parent.
*
* @param np pointer to the pseudo packet
* @param p pointer to the original packet
*/
static void StreamTcpPseudoPacketSetupHeader(Packet *np, Packet *p)
{
/* Setup the IP header */
if (PKT_IS_IPV4(p)) {
np->ip4h = (IPV4Hdr *)((uint8_t *)GET_PKT_DATA(np) + (GET_PKT_LEN(np) - IPV4_GET_IPLEN(p)));
PSEUDO_PKT_SET_IPV4HDR(np->ip4h, p->ip4h);
/* Similarly setup the TCP header with ports in opposite direction */
np->tcph = (TCPHdr *)((uint8_t *)np->ip4h + IPV4_GET_HLEN(np));
PSEUDO_PKT_SET_TCPHDR(np->tcph, p->tcph);
/* Setup the adress and port details */
SET_IPV4_SRC_ADDR(p, &np->dst);
SET_IPV4_DST_ADDR(p, &np->src);
SET_TCP_SRC_PORT(p, &np->dp);
SET_TCP_DST_PORT(p, &np->sp);
} else if (PKT_IS_IPV6(p)) {
np->ip6h = (IPV6Hdr *)((uint8_t *)GET_PKT_DATA(np) + (GET_PKT_LEN(np) - IPV6_GET_PLEN(p) - IPV6_HEADER_LEN));
PSEUDO_PKT_SET_IPV6HDR(np->ip6h, p->ip6h);
/* Similarly setup the TCP header with ports in opposite direction */
np->tcph = (TCPHdr *)((uint8_t *)np->ip6h + IPV6_HEADER_LEN);
PSEUDO_PKT_SET_TCPHDR(np->tcph, p->tcph);
/* Setup the adress and port details */
SET_IPV6_SRC_ADDR(p, &np->dst);
SET_IPV6_DST_ADDR(p, &np->src);
SET_TCP_SRC_PORT(p, &np->dp);
SET_TCP_DST_PORT(p, &np->sp);
}
/* we don't need a payload (if any) */
np->payload = NULL;
np->payload_len = 0;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream to wrap up stream reassembly.
*
* \param p real packet
* \param pq packet queue to store the new pseudo packet in
*/
void StreamTcpPseudoPacketCreateStreamEndPacket(ThreadVars *tv, StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (p->flags & PKT_PSEUDO_STREAM_END) {
SCReturn;
}
/* no need for a pseudo packet if there is nothing left to reassemble */
if (ssn->server.seg_list == NULL && ssn->client.seg_list == NULL) {
SCReturn;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
SCLogDebug("The packet received from packet allocation is NULL");
StatsIncr(tv, stt->counter_tcp_pseudo_failed);
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_STREAM_END_PSEUDO);
/* Setup the IP and TCP headers */
StreamTcpPseudoPacketSetupHeader(np,p);
np->tenant_id = p->flow->tenant_id;
np->flowflags = p->flowflags;
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_STREAM_EOF;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_PSEUDO_STREAM_END;
if (p->flags & PKT_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (p->flags & PKT_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("original is to_server, so pseudo is to_client");
np->flowflags &= ~FLOW_PKT_TOSERVER;
np->flowflags |= FLOW_PKT_TOCLIENT;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOCLIENT(np)));
BUG_ON((PKT_IS_TOSERVER(np)));
#endif
} else if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("original is to_client, so pseudo is to_server");
np->flowflags &= ~FLOW_PKT_TOCLIENT;
np->flowflags |= FLOW_PKT_TOSERVER;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOSERVER(np)));
BUG_ON((PKT_IS_TOCLIENT(np)));
#endif
}
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param p real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *p, TcpSession *ssn, PacketQueue *pq, bool dir)
{
SCEnter();
if (p->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
SCLogDebug("The packet received from packet allocation is NULL");
StatsIncr(tv, stt->counter_tcp_pseudo_failed);
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
/* Setup the IP and TCP headers */
StreamTcpPseudoPacketSetupHeader(np,p);
np->tenant_id = p->flow->tenant_id;
np->flowflags = p->flowflags;
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (p->flags & PKT_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (p->flags & PKT_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == false) {
SCLogDebug("pseudo is to_client");
np->flowflags &= ~(FLOW_PKT_TOSERVER|FLOW_PKT_TOCLIENT);
np->flowflags |= FLOW_PKT_TOCLIENT;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOCLIENT(np)));
BUG_ON((PKT_IS_TOSERVER(np)));
#endif
} else {
SCLogDebug("pseudo is to_server");
np->flowflags &= ~(FLOW_PKT_TOCLIENT|FLOW_PKT_TOSERVER);
np->flowflags |= FLOW_PKT_TOSERVER;
#ifdef DEBUG
BUG_ON(!(PKT_IS_TOSERVER(np)));
BUG_ON((PKT_IS_TOCLIENT(np)));
#endif
}
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg = stream->seg_list;
for (; seg != NULL &&
((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack));)
{
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
seg = seg->next;
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.seg_list->next != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
FAIL_IF(ssn.client.seg_list_tail == NULL);
FAIL_IF(TCP_SEG_LEN(ssn.client.seg_list_tail) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
FAIL_IF(ssn.client.seg_list_tail == NULL);
FAIL_IF(TCP_SEG_LEN(ssn.client.seg_list_tail) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
static int StreamTcpTest40(void)
{
uint8_t raw_vlan[] = {
0x00, 0x20, 0x08, 0x00, 0x45, 0x00, 0x00, 0x34,
0x3b, 0x36, 0x40, 0x00, 0x40, 0x06, 0xb7, 0xc9,
0x83, 0x97, 0x20, 0x81, 0x83, 0x97, 0x20, 0x15,
0x04, 0x8a, 0x17, 0x70, 0x4e, 0x14, 0xdf, 0x55,
0x4d, 0x3d, 0x5a, 0x61, 0x80, 0x10, 0x6b, 0x50,
0x3c, 0x4c, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a,
0x00, 0x04, 0xf0, 0xc8, 0x01, 0x99, 0xa3, 0xf3
};
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
ThreadVars tv;
DecodeThreadVars dtv;
memset(&tv, 0, sizeof(ThreadVars));
memset(p, 0, SIZE_OF_PACKET);
PACKET_INITIALIZE(p);
SET_PKT_LEN(p, sizeof(raw_vlan));
memcpy(GET_PKT_DATA(p), raw_vlan, sizeof(raw_vlan));
memset(&dtv, 0, sizeof(DecodeThreadVars));
FlowInitConfig(FLOW_QUIET);
DecodeVLAN(&tv, &dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), NULL);
FAIL_IF(p->vlanh[0] == NULL);
FAIL_IF(p->tcph == NULL);
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
FAIL_IF(np == NULL);
StreamTcpPseudoPacketSetupHeader(np,p);
FAIL_IF(((uint8_t *)p->tcph - (uint8_t *)p->ip4h) != ((uint8_t *)np->tcph - (uint8_t *)np->ip4h));
PACKET_DESTRUCTOR(np);
PACKET_DESTRUCTOR(p);
FlowShutdown();
PacketFree(np);
PacketFree(p);
PASS;
}
static int StreamTcpTest41(void)
{
/* IPV6/TCP/no eth header */
uint8_t raw_ip[] = {
0x60, 0x00, 0x00, 0x00, 0x00, 0x28, 0x06, 0x40,
0x20, 0x01, 0x06, 0x18, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x51, 0x99, 0xcc, 0x70,
0x20, 0x01, 0x06, 0x18, 0x00, 0x01, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
0x8c, 0x9b, 0x00, 0x50, 0x6a, 0xe7, 0x07, 0x36,
0x00, 0x00, 0x00, 0x00, 0xa0, 0x02, 0x16, 0x30,
0x29, 0x9c, 0x00, 0x00, 0x02, 0x04, 0x05, 0x8c,
0x04, 0x02, 0x08, 0x0a, 0x00, 0xdd, 0x1a, 0x39,
0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x02 };
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
ThreadVars tv;
DecodeThreadVars dtv;
memset(&dtv, 0, sizeof(DecodeThreadVars));
memset(&tv, 0, sizeof(ThreadVars));
memset(p, 0, SIZE_OF_PACKET);
PACKET_INITIALIZE(p);
if (PacketCopyData(p, raw_ip, sizeof(raw_ip)) == -1) {
PacketFree(p);
return 1;
}
FlowInitConfig(FLOW_QUIET);
DecodeRaw(&tv, &dtv, p, raw_ip, GET_PKT_LEN(p), NULL);
if (p->ip6h == NULL) {
printf("expected a valid ipv6 header but it was NULL: ");
FlowShutdown();
SCFree(p);
return 1;
}
if(p->tcph == NULL) {
SCFree(p);
return 0;
}
Packet *np = StreamTcpPseudoSetup(p, GET_PKT_DATA(p), GET_PKT_LEN(p));
if (np == NULL) {
printf("the packet received from packet allocation is NULL: ");
return 0;
}
StreamTcpPseudoPacketSetupHeader(np,p);
if (((uint8_t *)p->tcph - (uint8_t *)p->ip6h) != ((uint8_t *)np->tcph - (uint8_t *)np->ip6h)) {
return 0;
}
PACKET_RECYCLE(np);
PACKET_RECYCLE(p);
SCFree(p);
FlowShutdown();
return 1;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest40 -- pseudo setup", StreamTcpTest40);
UtRegisterTest("StreamTcpTest41 -- pseudo setup", StreamTcpTest41);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-693/c/bad_616_1 |
crossvul-cpp_data_good_616_0 | /* Copyright (C) 2007-2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
*
* Basic detection engine
*/
#include "suricata-common.h"
#include "suricata.h"
#include "conf.h"
#include "decode.h"
#include "flow.h"
#include "stream-tcp.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "detect.h"
#include "detect-engine.h"
#include "detect-engine-profile.h"
#include "detect-engine-alert.h"
#include "detect-engine-siggroup.h"
#include "detect-engine-address.h"
#include "detect-engine-proto.h"
#include "detect-engine-port.h"
#include "detect-engine-mpm.h"
#include "detect-engine-iponly.h"
#include "detect-engine-threshold.h"
#include "detect-engine-prefilter.h"
#include "detect-engine-state.h"
#include "detect-engine-analyzer.h"
#include "detect-engine-filedata.h"
#include "detect-engine-payload.h"
#include "detect-engine-event.h"
#include "detect-engine-hcbd.h"
#include "detect-engine-hsbd.h"
#include "detect-filestore.h"
#include "detect-flowvar.h"
#include "detect-replace.h"
#include "util-validate.h"
#include "util-detect.h"
typedef struct DetectRunScratchpad {
const AppProto alproto;
const uint8_t flow_flags; /* flow/state flags: STREAM_* */
const bool app_decoder_events;
const SigGroupHead *sgh;
SignatureMask pkt_mask;
} DetectRunScratchpad;
/* prototypes */
static DetectRunScratchpad DetectRunSetup(const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow);
static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Flow * const pflow, Packet * const p);
static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx,
Packet * const p, Flow * const pflow, DetectRunScratchpad *scratch);
static inline void DetectRunPrefilterPkt(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p,
DetectRunScratchpad *scratch);
static inline void DetectRulePacketRules(ThreadVars * const tv,
DetectEngineCtx * const de_ctx, DetectEngineThreadCtx * const det_ctx,
Packet * const p, Flow * const pflow, const DetectRunScratchpad *scratch);
static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet *p,
Flow *f, DetectRunScratchpad *scratch);
static inline void DetectRunPostRules(ThreadVars *tv, DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow,
DetectRunScratchpad *scratch);
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow);
/** \internal
*/
static void DetectRun(ThreadVars *th_v,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
SCEnter();
SCLogDebug("pcap_cnt %"PRIu64, p->pcap_cnt);
/* bail early if packet should not be inspected */
if (p->flags & PKT_NOPACKET_INSPECTION) {
/* nothing to do */
SCReturn;
}
/* Load the Packet's flow early, even though it might not be needed.
* Mark as a constant pointer, although the flow itself can change. */
Flow * const pflow = p->flow;
DetectRunScratchpad scratch = DetectRunSetup(de_ctx, det_ctx, p, pflow);
/* run the IPonly engine */
DetectRunInspectIPOnly(th_v, de_ctx, det_ctx, pflow, p);
/* get our rule group */
DetectRunGetRuleGroup(de_ctx, p, pflow, &scratch);
/* if we didn't get a sig group head, we
* have nothing to do.... */
if (scratch.sgh == NULL) {
SCLogDebug("no sgh for this packet, nothing to match against");
goto end;
}
/* run the prefilters for packets */
DetectRunPrefilterPkt(th_v, de_ctx, det_ctx, p, &scratch);
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_RULES);
/* inspect the rules against the packet */
DetectRulePacketRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_RULES);
/* run tx/state inspection */
if (pflow && pflow->alstate) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_TX);
DetectRunTx(th_v, de_ctx, det_ctx, p, pflow, &scratch);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_TX);
}
end:
DetectRunPostRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
DetectRunCleanup(det_ctx, p, pflow);
SCReturn;
}
static void DetectRunPostMatch(ThreadVars *tv,
DetectEngineThreadCtx *det_ctx, Packet *p,
const Signature *s)
{
/* run the packet match functions */
const SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_POSTMATCH];
if (smd != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_POSTMATCH);
SCLogDebug("running match functions, sm %p", smd);
while (1) {
KEYWORD_PROFILING_START;
(void)sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx);
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (smd->is_last)
break;
smd++;
}
}
DetectReplaceExecute(p, det_ctx);
if (s->flags & SIG_FLAG_FILESTORE)
DetectFilestorePostMatch(tv, det_ctx, p, s);
return;
}
/**
* \brief Get the SigGroupHead for a packet.
*
* \param de_ctx detection engine context
* \param p packet
*
* \retval sgh the SigGroupHead or NULL if non applies to the packet
*/
const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx,
const Packet *p)
{
SCEnter();
int f;
SigGroupHead *sgh = NULL;
/* if the packet proto is 0 (not set), we're inspecting it against
* the decoder events sgh we have. */
if (p->proto == 0 && p->events.cnt > 0) {
SCReturnPtr(de_ctx->decoder_event_sgh, "SigGroupHead");
} else if (p->proto == 0) {
if (!(PKT_IS_IPV4(p) || PKT_IS_IPV6(p))) {
/* not IP, so nothing to do */
SCReturnPtr(NULL, "SigGroupHead");
}
}
/* select the flow_gh */
if (p->flowflags & FLOW_PKT_TOCLIENT)
f = 0;
else
f = 1;
int proto = IP_GET_IPPROTO(p);
if (proto == IPPROTO_TCP) {
DetectPort *list = de_ctx->flow_gh[f].tcp;
SCLogDebug("tcp toserver %p, tcp toclient %p: going to use %p",
de_ctx->flow_gh[1].tcp, de_ctx->flow_gh[0].tcp, de_ctx->flow_gh[f].tcp);
uint16_t port = f ? p->dp : p->sp;
SCLogDebug("tcp port %u -> %u:%u", port, p->sp, p->dp);
DetectPort *sghport = DetectPortLookupGroup(list, port);
if (sghport != NULL)
sgh = sghport->sh;
SCLogDebug("TCP list %p, port %u, direction %s, sghport %p, sgh %p",
list, port, f ? "toserver" : "toclient", sghport, sgh);
} else if (proto == IPPROTO_UDP) {
DetectPort *list = de_ctx->flow_gh[f].udp;
uint16_t port = f ? p->dp : p->sp;
DetectPort *sghport = DetectPortLookupGroup(list, port);
if (sghport != NULL)
sgh = sghport->sh;
SCLogDebug("UDP list %p, port %u, direction %s, sghport %p, sgh %p",
list, port, f ? "toserver" : "toclient", sghport, sgh);
} else {
sgh = de_ctx->flow_gh[f].sgh[proto];
}
SCReturnPtr(sgh, "SigGroupHead");
}
static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx)
{
SigIntId mpm, nonmpm;
det_ctx->match_array_cnt = 0;
SigIntId *mpm_ptr = det_ctx->pmq.rule_id_array;
SigIntId *nonmpm_ptr = det_ctx->non_pf_id_array;
uint32_t m_cnt = det_ctx->pmq.rule_id_array_cnt;
uint32_t n_cnt = det_ctx->non_pf_id_cnt;
SigIntId *final_ptr;
uint32_t final_cnt;
SigIntId id;
SigIntId previous_id = (SigIntId)-1;
Signature **sig_array = de_ctx->sig_array;
Signature **match_array = det_ctx->match_array;
Signature *s;
SCLogDebug("PMQ rule id array count %d", det_ctx->pmq.rule_id_array_cnt);
/* Load first values. */
if (likely(m_cnt)) {
mpm = *mpm_ptr;
} else {
/* mpm list is empty */
final_ptr = nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
if (likely(n_cnt)) {
nonmpm = *nonmpm_ptr;
} else {
/* non-mpm list is empty. */
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
while (1) {
if (mpm < nonmpm) {
/* Take from mpm list */
id = mpm;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
if (unlikely(--m_cnt == 0)) {
/* mpm list is now empty */
final_ptr = nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
mpm_ptr++;
mpm = *mpm_ptr;
} else if (mpm > nonmpm) {
id = nonmpm;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
if (unlikely(--n_cnt == 0)) {
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
nonmpm_ptr++;
nonmpm = *nonmpm_ptr;
} else { /* implied mpm == nonmpm */
/* special case: if on both lists, it's a negated mpm pattern */
/* mpm list may have dups, so skip past them here */
while (--m_cnt != 0) {
mpm_ptr++;
mpm = *mpm_ptr;
if (mpm != nonmpm)
break;
}
/* if mpm is done, update nonmpm_ptrs and jump to final */
if (unlikely(m_cnt == 0)) {
n_cnt--;
/* mpm list is now empty */
final_ptr = ++nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
/* otherwise, if nonmpm is done jump to final for mpm
* mpm ptrs alrady updated */
if (unlikely(--n_cnt == 0)) {
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
/* not at end of the lists, update nonmpm. Mpm already
* updated in while loop above. */
nonmpm_ptr++;
nonmpm = *nonmpm_ptr;
}
}
final: /* Only one list remaining. Just walk that list. */
while (final_cnt-- > 0) {
id = *final_ptr++;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
}
det_ctx->match_array_cnt = match_array - det_ctx->match_array;
BUG_ON((det_ctx->pmq.rule_id_array_cnt + det_ctx->non_pf_id_cnt) < det_ctx->match_array_cnt);
}
static inline void
DetectPrefilterBuildNonPrefilterList(DetectEngineThreadCtx *det_ctx, SignatureMask mask, uint8_t alproto)
{
uint32_t x = 0;
for (x = 0; x < det_ctx->non_pf_store_cnt; x++) {
/* only if the mask matches this rule can possibly match,
* so build the non_mpm array only for match candidates */
const SignatureMask rule_mask = det_ctx->non_pf_store_ptr[x].mask;
const uint8_t rule_alproto = det_ctx->non_pf_store_ptr[x].alproto;
if ((rule_mask & mask) == rule_mask && (rule_alproto == 0 || rule_alproto == alproto)) { // TODO dce?
det_ctx->non_pf_id_array[det_ctx->non_pf_id_cnt++] = det_ctx->non_pf_store_ptr[x].id;
}
}
}
/** \internal
* \brief select non-mpm list
* Based on the packet properties, select the non-mpm list to use
* \todo move non_pf_store* into scratchpad */
static inline void
DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch)
{
if ((p->proto == IPPROTO_TCP) && (p->tcph != NULL) && (p->tcph->th_flags & TH_SYN)) {
det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_syn_store_array;
det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_syn_store_cnt;
} else {
det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_other_store_array;
det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_other_store_cnt;
}
SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)",
det_ctx->non_pf_store_ptr, det_ctx->non_pf_store_cnt,
scratch->sgh->non_pf_syn_store_array, scratch->sgh->non_pf_syn_store_cnt,
scratch->sgh->non_pf_other_store_array, scratch->sgh->non_pf_other_store_cnt);
}
/** \internal
* \brief update flow's file tracking flags based on the detection engine
*/
static inline void
DetectPostInspectFileFlagsUpdate(Flow *pflow, const SigGroupHead *sgh, uint8_t direction)
{
/* see if this sgh requires us to consider file storing */
if (!FileForceFilestore() && (sgh == NULL ||
sgh->filestore_cnt == 0))
{
FileDisableStoring(pflow, direction);
}
#ifdef HAVE_MAGIC
/* see if this sgh requires us to consider file magic */
if (!FileForceMagic() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMAGIC)))
{
SCLogDebug("disabling magic for flow");
FileDisableMagic(pflow, direction);
}
#endif
/* see if this sgh requires us to consider file md5 */
if (!FileForceMd5() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMD5)))
{
SCLogDebug("disabling md5 for flow");
FileDisableMd5(pflow, direction);
}
/* see if this sgh requires us to consider file sha1 */
if (!FileForceSha1() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA1)))
{
SCLogDebug("disabling sha1 for flow");
FileDisableSha1(pflow, direction);
}
/* see if this sgh requires us to consider file sha256 */
if (!FileForceSha256() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA256)))
{
SCLogDebug("disabling sha256 for flow");
FileDisableSha256(pflow, direction);
}
/* see if this sgh requires us to consider filesize */
if (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVEFILESIZE))
{
SCLogDebug("disabling filesize for flow");
FileDisableFilesize(pflow, direction);
}
}
static inline void
DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead *sgh)
{
if ((p->flowflags & FLOW_PKT_TOSERVER) && !(pflow->flags & FLOW_SGH_TOSERVER)) {
/* first time we see this toserver sgh, store it */
pflow->sgh_toserver = sgh;
pflow->flags |= FLOW_SGH_TOSERVER;
if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
if (pflow->protoctx != NULL) {
TcpSession *ssn = pflow->protoctx;
SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.client");
ssn->client.flags |= STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
}
DetectPostInspectFileFlagsUpdate(pflow,
pflow->sgh_toserver, STREAM_TOSERVER);
} else if ((p->flowflags & FLOW_PKT_TOCLIENT) && !(pflow->flags & FLOW_SGH_TOCLIENT)) {
pflow->sgh_toclient = sgh;
pflow->flags |= FLOW_SGH_TOCLIENT;
if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
if (pflow->protoctx != NULL) {
TcpSession *ssn = pflow->protoctx;
SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.server");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
}
DetectPostInspectFileFlagsUpdate(pflow,
pflow->sgh_toclient, STREAM_TOCLIENT);
}
}
static inline void DetectRunGetRuleGroup(
const DetectEngineCtx *de_ctx,
Packet * const p, Flow * const pflow,
DetectRunScratchpad *scratch)
{
const SigGroupHead *sgh = NULL;
if (pflow) {
bool use_flow_sgh = false;
/* Get the stored sgh from the flow (if any). Make sure we're not using
* the sgh for icmp error packets part of the same stream. */
if (IP_GET_IPPROTO(p) == pflow->proto) { /* filter out icmp */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
if ((p->flowflags & FLOW_PKT_TOSERVER) && (pflow->flags & FLOW_SGH_TOSERVER)) {
sgh = pflow->sgh_toserver;
SCLogDebug("sgh = pflow->sgh_toserver; => %p", sgh);
use_flow_sgh = true;
} else if ((p->flowflags & FLOW_PKT_TOCLIENT) && (pflow->flags & FLOW_SGH_TOCLIENT)) {
sgh = pflow->sgh_toclient;
SCLogDebug("sgh = pflow->sgh_toclient; => %p", sgh);
use_flow_sgh = true;
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
}
if (!(use_flow_sgh)) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
sgh = SigMatchSignaturesGetSgh(de_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
/* HACK: prevent the wrong sgh (or NULL) from being stored in the
* flow's sgh pointers */
if (PKT_IS_ICMPV4(p) && ICMPV4_DEST_UNREACH_IS_VALID(p)) {
; /* no-op */
} else {
/* store the found sgh (or NULL) in the flow to save us
* from looking it up again for the next packet.
* Also run other tasks */
DetectRunPostGetFirstRuleGroup(p, pflow, sgh);
}
}
} else { /* p->flags & PKT_HAS_FLOW */
/* no flow */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
sgh = SigMatchSignaturesGetSgh(de_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
}
scratch->sgh = sgh;
}
static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Flow * const pflow, Packet * const p)
{
if (pflow) {
/* set the iponly stuff */
if (pflow->flags & FLOW_TOCLIENT_IPONLY_SET)
p->flowflags |= FLOW_PKT_TOCLIENT_IPONLY_SET;
if (pflow->flags & FLOW_TOSERVER_IPONLY_SET)
p->flowflags |= FLOW_PKT_TOSERVER_IPONLY_SET;
if (((p->flowflags & FLOW_PKT_TOSERVER) && !(p->flowflags & FLOW_PKT_TOSERVER_IPONLY_SET)) ||
((p->flowflags & FLOW_PKT_TOCLIENT) && !(p->flowflags & FLOW_PKT_TOCLIENT_IPONLY_SET)))
{
SCLogDebug("testing against \"ip-only\" signatures");
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_IPONLY);
IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx, &det_ctx->io_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_IPONLY);
/* save in the flow that we scanned this direction... */
FlowSetIPOnlyFlag(pflow, p->flowflags & FLOW_PKT_TOSERVER ? 1 : 0);
} else if (((p->flowflags & FLOW_PKT_TOSERVER) &&
(pflow->flags & FLOW_TOSERVER_IPONLY_SET)) ||
((p->flowflags & FLOW_PKT_TOCLIENT) &&
(pflow->flags & FLOW_TOCLIENT_IPONLY_SET)))
{
/* If we have a drop from IP only module,
* we will drop the rest of the flow packets
* This will apply only to inline/IPS */
if (pflow->flags & FLOW_ACTION_DROP) {
PACKET_DROP(p);
}
}
} else { /* p->flags & PKT_HAS_FLOW */
/* no flow */
/* Even without flow we should match the packet src/dst */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_IPONLY);
IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx,
&det_ctx->io_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_IPONLY);
}
}
/* returns 0 if no match, 1 if match */
static inline int DetectRunInspectRuleHeader(
const Packet *p,
const Flow *f,
const Signature *s,
const uint32_t sflags,
const uint8_t s_proto_flags)
{
/* check if this signature has a requirement for flowvars of some type
* and if so, if we actually have any in the flow. If not, the sig
* can't match and we skip it. */
if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) {
int m = f->flowvar ? 1 : 0;
/* no flowvars? skip this sig */
if (m == 0) {
SCLogDebug("skipping sig as the flow has no flowvars and sig "
"has SIG_FLAG_REQUIRE_FLOWVAR flag set.");
return 0;
}
}
if ((s_proto_flags & DETECT_PROTO_IPV4) && !PKT_IS_IPV4(p)) {
SCLogDebug("ip version didn't match");
return 0;
}
if ((s_proto_flags & DETECT_PROTO_IPV6) && !PKT_IS_IPV6(p)) {
SCLogDebug("ip version didn't match");
return 0;
}
if (DetectProtoContainsProto(&s->proto, IP_GET_IPPROTO(p)) == 0) {
SCLogDebug("proto didn't match");
return 0;
}
/* check the source & dst port in the sig */
if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) {
if (!(sflags & SIG_FLAG_DP_ANY)) {
if (p->flags & PKT_IS_FRAGMENT)
return 0;
DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp);
if (dport == NULL) {
SCLogDebug("dport didn't match.");
return 0;
}
}
if (!(sflags & SIG_FLAG_SP_ANY)) {
if (p->flags & PKT_IS_FRAGMENT)
return 0;
DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp);
if (sport == NULL) {
SCLogDebug("sport didn't match.");
return 0;
}
}
} else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) {
SCLogDebug("port-less protocol and sig needs ports");
return 0;
}
/* check the destination address */
if (!(sflags & SIG_FLAG_DST_ANY)) {
if (PKT_IS_IPV4(p)) {
if (DetectAddressMatchIPv4(s->addr_dst_match4, s->addr_dst_match4_cnt, &p->dst) == 0)
return 0;
} else if (PKT_IS_IPV6(p)) {
if (DetectAddressMatchIPv6(s->addr_dst_match6, s->addr_dst_match6_cnt, &p->dst) == 0)
return 0;
}
}
/* check the source address */
if (!(sflags & SIG_FLAG_SRC_ANY)) {
if (PKT_IS_IPV4(p)) {
if (DetectAddressMatchIPv4(s->addr_src_match4, s->addr_src_match4_cnt, &p->src) == 0)
return 0;
} else if (PKT_IS_IPV6(p)) {
if (DetectAddressMatchIPv6(s->addr_src_match6, s->addr_src_match6_cnt, &p->src) == 0)
return 0;
}
}
return 1;
}
/* returns 0 if no match, 1 if match */
static inline int DetectRunInspectRulePacketMatches(
ThreadVars *tv,
DetectEngineThreadCtx *det_ctx,
Packet *p,
const Flow *f,
const Signature *s)
{
/* run the packet match functions */
if (s->sm_arrays[DETECT_SM_LIST_MATCH] != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_MATCH);
SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_MATCH];
SCLogDebug("running match functions, sm %p", smd);
if (smd != NULL) {
while (1) {
KEYWORD_PROFILING_START;
if (sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx) <= 0) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCLogDebug("no match");
return 0;
}
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (smd->is_last) {
SCLogDebug("match and is_last");
break;
}
smd++;
}
}
}
return 1;
}
/** \internal
* \brief run packet/stream prefilter engines
*/
static inline void DetectRunPrefilterPkt(
ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
DetectRunScratchpad *scratch
)
{
DetectPrefilterSetNonPrefilterList(p, det_ctx, scratch);
/* create our prefilter mask */
PacketCreateMask(p, &scratch->pkt_mask, scratch->alproto, scratch->app_decoder_events);
/* build and prefilter non_pf list against the mask of the packet */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_NONMPMLIST);
det_ctx->non_pf_id_cnt = 0;
if (likely(det_ctx->non_pf_store_cnt > 0)) {
DetectPrefilterBuildNonPrefilterList(det_ctx, scratch->pkt_mask, scratch->alproto);
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_NONMPMLIST);
/* run the prefilter engines */
Prefilter(det_ctx, scratch->sgh, p, scratch->flow_flags);
/* create match list if we have non-pf and/or pf */
if (det_ctx->non_pf_store_cnt || det_ctx->pmq.rule_id_array_cnt) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_SORT2);
DetectPrefilterMergeSort(de_ctx, det_ctx);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_PF_SORT2);
}
#ifdef PROFILING
if (tv) {
StatsAddUI64(tv, det_ctx->counter_mpm_list,
(uint64_t)det_ctx->pmq.rule_id_array_cnt);
StatsAddUI64(tv, det_ctx->counter_nonmpm_list,
(uint64_t)det_ctx->non_pf_store_cnt);
/* non mpm sigs after mask prefilter */
StatsAddUI64(tv, det_ctx->counter_fnonmpm_list,
(uint64_t)det_ctx->non_pf_id_cnt);
}
#endif
}
static inline void DetectRulePacketRules(
ThreadVars * const tv,
DetectEngineCtx * const de_ctx,
DetectEngineThreadCtx * const det_ctx,
Packet * const p,
Flow * const pflow,
const DetectRunScratchpad *scratch
)
{
const Signature *s = NULL;
const Signature *next_s = NULL;
/* inspect the sigs against the packet */
/* Prefetch the next signature. */
SigIntId match_cnt = det_ctx->match_array_cnt;
#ifdef PROFILING
if (tv) {
StatsAddUI64(tv, det_ctx->counter_match_list,
(uint64_t)match_cnt);
}
#endif
Signature **match_array = det_ctx->match_array;
SGH_PROFILING_RECORD(det_ctx, scratch->sgh);
#ifdef PROFILING
#ifdef HAVE_LIBJANSSON
if (match_cnt >= de_ctx->profile_match_logging_threshold)
RulesDumpMatchArray(det_ctx, scratch->sgh, p);
#endif
#endif
uint32_t sflags, next_sflags = 0;
if (match_cnt) {
next_s = *match_array++;
next_sflags = next_s->flags;
}
while (match_cnt--) {
RULE_PROFILING_START(p);
uint8_t alert_flags = 0;
bool state_alert = false;
#ifdef PROFILING
bool smatch = false; /* signature match */
#endif
s = next_s;
sflags = next_sflags;
if (match_cnt) {
next_s = *match_array++;
next_sflags = next_s->flags;
}
const uint8_t s_proto_flags = s->proto.flags;
SCLogDebug("inspecting signature id %"PRIu32"", s->id);
if (sflags & SIG_FLAG_STATE_MATCH) {
goto next; // TODO skip and handle in DetectRunTx
}
/* don't run mask check for stateful rules.
* There we depend on prefilter */
if ((s->mask & scratch->pkt_mask) != s->mask) {
SCLogDebug("mask mismatch %x & %x != %x", s->mask, scratch->pkt_mask, s->mask);
goto next;
}
if (unlikely(sflags & SIG_FLAG_DSIZE)) {
if (likely(p->payload_len < s->dsize_low || p->payload_len > s->dsize_high)) {
SCLogDebug("kicked out as p->payload_len %u, dsize low %u, hi %u",
p->payload_len, s->dsize_low, s->dsize_high);
goto next;
}
}
/* if the sig has alproto and the session as well they should match */
if (likely(sflags & SIG_FLAG_APPLAYER)) {
if (s->alproto != ALPROTO_UNKNOWN && s->alproto != scratch->alproto) {
if (s->alproto == ALPROTO_DCERPC) {
if (scratch->alproto != ALPROTO_SMB && scratch->alproto != ALPROTO_SMB2) {
SCLogDebug("DCERPC sig, alproto not SMB or SMB2");
goto next;
}
} else {
SCLogDebug("alproto mismatch");
goto next;
}
}
}
if (DetectRunInspectRuleHeader(p, pflow, s, sflags, s_proto_flags) == 0) {
goto next;
}
/* Check the payload keywords. If we are a MPM sig and we've made
* to here, we've had at least one of the patterns match */
if (!(sflags & SIG_FLAG_STATE_MATCH) && s->sm_arrays[DETECT_SM_LIST_PMATCH] != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_PMATCH);
/* if we have stream msgs, inspect against those first,
* but not for a "dsize" signature */
if (sflags & SIG_FLAG_REQUIRE_STREAM) {
int pmatch = 0;
if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
pmatch = DetectEngineInspectStreamPayload(de_ctx, det_ctx, s, pflow, p);
if (pmatch) {
det_ctx->flags |= DETECT_ENGINE_THREAD_CTX_STREAM_CONTENT_MATCH;
/* Tell the engine that this reassembled stream can drop the
* rest of the pkts with no further inspection */
if (s->action & ACTION_DROP)
alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
alert_flags |= PACKET_ALERT_FLAG_STREAM_MATCH;
}
}
/* no match? then inspect packet payload */
if (pmatch == 0) {
SCLogDebug("no match in stream, fall back to packet payload");
/* skip if we don't have to inspect the packet and segment was
* added to stream */
if (!(sflags & SIG_FLAG_REQUIRE_PACKET) && (p->flags & PKT_STREAM_ADD)) {
goto next;
}
if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
goto next;
}
}
} else {
if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
goto next;
}
}
}
if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, pflow, s) == 0)
goto next;
#ifdef PROFILING
smatch = true;
#endif
DetectRunPostMatch(tv, det_ctx, p, s);
if (!(sflags & SIG_FLAG_NOALERT)) {
/* stateful sigs call PacketAlertAppend from DeStateDetectStartDetection */
if (!state_alert)
PacketAlertAppend(det_ctx, s, p, 0, alert_flags);
} else {
/* apply actions even if not alerting */
DetectSignatureApplyActions(p, s, alert_flags);
}
next:
DetectVarProcessList(det_ctx, pflow, p);
DetectReplaceFree(det_ctx);
RULE_PROFILING_END(det_ctx, s, smatch, p);
det_ctx->flags = 0;
continue;
}
}
static DetectRunScratchpad DetectRunSetup(
const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet * const p, Flow * const pflow)
{
AppProto alproto = ALPROTO_UNKNOWN;
uint8_t flow_flags = 0; /* flow/state flags */
bool app_decoder_events = false;
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_SETUP);
#ifdef UNITTESTS
p->alerts.cnt = 0;
#endif
det_ctx->ticker++;
det_ctx->filestore_cnt = 0;
det_ctx->base64_decoded_len = 0;
det_ctx->raw_stream_progress = 0;
#ifdef DEBUG
if (p->flags & PKT_STREAM_ADD) {
det_ctx->pkt_stream_add_cnt++;
}
#endif
/* grab the protocol state we will detect on */
if (p->flags & PKT_HAS_FLOW) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flow_flags = STREAM_TOSERVER;
SCLogDebug("flag STREAM_TOSERVER set");
} else if (p->flowflags & FLOW_PKT_TOCLIENT) {
flow_flags = STREAM_TOCLIENT;
SCLogDebug("flag STREAM_TOCLIENT set");
}
SCLogDebug("p->flowflags 0x%02x", p->flowflags);
if (p->flags & PKT_STREAM_EOF) {
flow_flags |= STREAM_EOF;
SCLogDebug("STREAM_EOF set");
}
/* store tenant_id in the flow so that we can use it
* for creating pseudo packets */
if (p->tenant_id > 0 && pflow->tenant_id == 0) {
pflow->tenant_id = p->tenant_id;
}
/* live ruleswap check for flow updates */
if (pflow->de_ctx_version == 0) {
/* first time this flow is inspected, set id */
pflow->de_ctx_version = de_ctx->version;
} else if (pflow->de_ctx_version != de_ctx->version) {
/* first time we inspect flow with this de_ctx, reset */
pflow->flags &= ~FLOW_SGH_TOSERVER;
pflow->flags &= ~FLOW_SGH_TOCLIENT;
pflow->sgh_toserver = NULL;
pflow->sgh_toclient = NULL;
pflow->de_ctx_version = de_ctx->version;
GenericVarFree(pflow->flowvar);
pflow->flowvar = NULL;
DetectEngineStateResetTxs(pflow);
}
/* Retrieve the app layer state and protocol and the tcp reassembled
* stream chunks. */
if ((p->proto == IPPROTO_TCP && (p->flags & PKT_STREAM_EST)) ||
(p->proto == IPPROTO_UDP) ||
(p->proto == IPPROTO_SCTP && (p->flowflags & FLOW_PKT_ESTABLISHED)))
{
/* update flow flags with knowledge on disruptions */
flow_flags = FlowGetDisruptionFlags(pflow, flow_flags);
alproto = FlowGetAppProtocol(pflow);
if (p->proto == IPPROTO_TCP && pflow->protoctx &&
StreamReassembleRawHasDataReady(pflow->protoctx, p)) {
p->flags |= PKT_DETECT_HAS_STREAMDATA;
}
SCLogDebug("alproto %u", alproto);
} else {
SCLogDebug("packet doesn't have established flag set (proto %d)", p->proto);
}
app_decoder_events = AppLayerParserHasDecoderEvents(pflow->alparser);
}
DetectRunScratchpad pad = { alproto, flow_flags, app_decoder_events, NULL, 0 };
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_SETUP);
return pad;
}
static inline void DetectRunPostRules(
ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet * const p,
Flow * const pflow,
DetectRunScratchpad *scratch)
{
/* see if we need to increment the inspect_id and reset the de_state */
if (pflow && pflow->alstate && AppLayerParserProtocolSupportsTxs(p->proto, scratch->alproto)) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_TX_UPDATE);
DeStateUpdateInspectTransactionId(pflow, scratch->flow_flags, (scratch->sgh == NULL));
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_TX_UPDATE);
}
/* so now let's iterate the alerts and remove the ones after a pass rule
* matched (if any). This is done inside PacketAlertFinalize() */
/* PR: installed "tag" keywords are handled after the threshold inspection */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_ALERT);
PacketAlertFinalize(de_ctx, det_ctx, p);
if (p->alerts.cnt > 0) {
StatsAddUI64(tv, det_ctx->counter_alerts, (uint64_t)p->alerts.cnt);
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_ALERT);
}
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow)
{
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);
/* cleanup pkt specific part of the patternmatcher */
PacketPatternCleanup(det_ctx);
if (pflow != NULL) {
/* update inspected tracker for raw reassembly */
if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {
StreamReassembleRawUpdateProgress(pflow->protoctx, p,
det_ctx->raw_stream_progress);
DetectEngineCleanHCBDBuffers(det_ctx);
DetectEngineCleanHSBDBuffers(det_ctx);
DetectEngineCleanFiledataBuffers(det_ctx);
}
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);
SCReturn;
}
void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size)
{
DEBUG_VALIDATE_BUG_ON(det_ctx->tx_candidates);
det_ctx->tx_candidates = SCCalloc(size, sizeof(RuleMatchCandidateTx));
if (det_ctx->tx_candidates == NULL) {
FatalError(SC_ERR_MEM_ALLOC, "failed to allocate %"PRIu64" bytes",
(uint64_t)(size * sizeof(RuleMatchCandidateTx)));
}
det_ctx->tx_candidates_size = size;
SCLogDebug("array initialized to %u elements (%"PRIu64" bytes)",
size, (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
}
void RuleMatchCandidateTxArrayFree(DetectEngineThreadCtx *det_ctx)
{
SCFree(det_ctx->tx_candidates);
det_ctx->tx_candidates_size = 0;
}
/* if size >= cur_space */
static inline bool RuleMatchCandidateTxArrayHasSpace(const DetectEngineThreadCtx *det_ctx,
const uint32_t need)
{
if (det_ctx->tx_candidates_size >= need)
return 1;
return 0;
}
/* realloc */
static int RuleMatchCandidateTxArrayExpand(DetectEngineThreadCtx *det_ctx, const uint32_t needed)
{
const uint32_t old_size = det_ctx->tx_candidates_size;
uint32_t new_size = needed;
void *ptmp = SCRealloc(det_ctx->tx_candidates, (new_size * sizeof(RuleMatchCandidateTx)));
if (ptmp == NULL) {
FatalError(SC_ERR_MEM_ALLOC, "failed to expand to %"PRIu64" bytes",
(uint64_t)(new_size * sizeof(RuleMatchCandidateTx)));
// TODO can this be handled more gracefully?
}
det_ctx->tx_candidates = ptmp;
det_ctx->tx_candidates_size = new_size;
SCLogDebug("array expanded from %u to %u elements (%"PRIu64" bytes -> %"PRIu64" bytes)",
old_size, new_size, (uint64_t)(old_size * sizeof(RuleMatchCandidateTx)),
(uint64_t)(new_size * sizeof(RuleMatchCandidateTx))); (void)old_size;
return 1;
}
/* TODO maybe let one with flags win if equal? */
static int
DetectRunTxSortHelper(const void *a, const void *b)
{
const RuleMatchCandidateTx *s0 = a;
const RuleMatchCandidateTx *s1 = b;
if (s1->id == s0->id)
return 0;
else
return s0->id > s1->id ? -1 : 1;
}
#if 0
#define TRACE_SID_TXS(sid,txs,...) \
do { \
char _trace_buf[2048]; \
snprintf(_trace_buf, sizeof(_trace_buf), __VA_ARGS__); \
SCLogNotice("%p/%"PRIu64"/%u: %s", txs->tx_ptr, txs->tx_id, sid, _trace_buf); \
} while(0)
#else
#define TRACE_SID_TXS(sid,txs,...)
#endif
/** \internal
* \brief inspect a rule against a transaction
*
* Inspect a rule. New detection or continued stateful
* detection.
*
* \param stored_flags pointer to stored flags or NULL.
* If stored_flags is set it means we're continueing
* inspection from an earlier run.
*
* \retval bool true sig matched, false didn't match
*/
static bool DetectRunTxInspectRule(ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
Flow *f,
const uint8_t flow_flags, // direction, EOF, etc
void *alstate,
DetectTransaction *tx,
const Signature *s,
uint32_t *stored_flags,
RuleMatchCandidateTx *can,
DetectRunScratchpad *scratch)
{
const int direction = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
uint32_t inspect_flags = stored_flags ? *stored_flags : 0;
int total_matches = 0;
int file_no_match = 0;
bool retval = false;
bool mpm_before_progress = false; // is mpm engine before progress?
bool mpm_in_progress = false; // is mpm engine in a buffer we will revisit?
TRACE_SID_TXS(s->id, tx, "starting %s", direction ? "toclient" : "toserver");
/* for a new inspection we inspect pkt header and packet matches */
if (likely(stored_flags == NULL)) {
TRACE_SID_TXS(s->id, tx, "first inspect, run packet matches");
if (DetectRunInspectRuleHeader(p, f, s, s->flags, s->proto.flags) == 0) {
TRACE_SID_TXS(s->id, tx, "DetectRunInspectRuleHeader() no match");
return false;
}
if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, f, s) == 0) {
TRACE_SID_TXS(s->id, tx, "DetectRunInspectRulePacketMatches no match");
return false;
}
/* stream mpm and negated mpm sigs can end up here with wrong proto */
if (!(f->alproto == s->alproto || s->alproto == ALPROTO_UNKNOWN)) {
TRACE_SID_TXS(s->id, tx, "alproto mismatch");
return false;
}
}
const DetectEngineAppInspectionEngine *engine = s->app_inspect;
while (engine != NULL) { // TODO could be do {} while as s->app_inspect cannot be null
TRACE_SID_TXS(s->id, tx, "engine %p inspect_flags %x", engine, inspect_flags);
if (!(inspect_flags & BIT_U32(engine->id)) &&
direction == engine->dir)
{
/* engines are sorted per progress, except that the one with
* mpm/prefilter enabled is first */
if (tx->tx_progress < engine->progress) {
SCLogDebug("tx progress %d < engine progress %d",
tx->tx_progress, engine->progress);
break;
}
if (engine->mpm) {
if (tx->tx_progress > engine->progress) {
mpm_before_progress = true;
} else if (tx->tx_progress == engine->progress) {
mpm_in_progress = true;
}
}
/* run callback: but bypass stream callback if we can */
int match;
if (unlikely(engine->stream && can->stream_stored)) {
match = can->stream_result;
TRACE_SID_TXS(s->id, tx, "stream skipped, stored result %d used instead", match);
/* special case: file_data on 'alert tcp' will have engines
* in the list that are not for us. Bypass with assume match */
} else if (unlikely(engine->alproto != 0 && engine->alproto != f->alproto)) {
inspect_flags |= BIT_U32(engine->id);
engine = engine->next;
total_matches++;
continue;
} else {
KEYWORD_PROFILING_SET_LIST(det_ctx, engine->sm_list);
match = engine->Callback(tv, de_ctx, det_ctx,
s, engine->smd, f, flow_flags, alstate, tx->tx_ptr, tx->tx_id);
TRACE_SID_TXS(s->id, tx, "engine %p match %d", engine, match);
if (engine->stream) {
can->stream_stored = true;
can->stream_result = match;
TRACE_SID_TXS(s->id, tx, "stream ran, store result %d for next tx (if any)", match);
}
}
if (match == DETECT_ENGINE_INSPECT_SIG_MATCH) {
inspect_flags |= BIT_U32(engine->id);
engine = engine->next;
total_matches++;
continue;
} else if (match == DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES) {
/* if the file engine matched, but indicated more
* files are still in progress, we don't set inspect
* flags as these would end inspection for this tx */
engine = engine->next;
total_matches++;
continue;
} else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
} else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
file_no_match = 1;
}
/* implied DETECT_ENGINE_INSPECT_SIG_NO_MATCH */
if (engine->mpm && mpm_before_progress) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
}
break;
}
engine = engine->next;
}
TRACE_SID_TXS(s->id, tx, "inspect_flags %x, total_matches %u, engine %p",
inspect_flags, total_matches, engine);
if (engine == NULL && total_matches) {
inspect_flags |= DE_STATE_FLAG_FULL_INSPECT;
TRACE_SID_TXS(s->id, tx, "MATCH");
retval = true;
}
if (stored_flags) {
*stored_flags = inspect_flags;
TRACE_SID_TXS(s->id, tx, "continue inspect flags %08x", inspect_flags);
} else {
// store... or? If tx is done we might not want to come back to this tx
// also... if mpmid tracking is enabled, we won't do a sig again for this tx...
TRACE_SID_TXS(s->id, tx, "start inspect flags %08x", inspect_flags);
if (inspect_flags & DE_STATE_FLAG_SIG_CANT_MATCH) {
if (file_no_match) {
/* if we have a mismatch on a file sig, we need to keep state.
* We may get another file on the same tx (for http and smtp
* at least), so for a new file we need to re-eval the sig.
* Thoughts / TODO:
* - not for some protos that have 1 file per tx (e.g. nfs)
* - maybe we only need this for file sigs that mix with
* other matches? E.g. 'POST + filename', is different than
* just 'filename'.
*/
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
} else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) && mpm_before_progress) {
TRACE_SID_TXS(s->id, tx, "no need to store match sig, "
"mpm won't trigger for it anymore");
if (inspect_flags & DE_STATE_FLAG_FILE_INSPECT) {
TRACE_SID_TXS(s->id, tx, "except that for new files, "
"we may have to revisit anyway");
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
} else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) == 0 && mpm_in_progress) {
TRACE_SID_TXS(s->id, tx, "no need to store no-match sig, "
"mpm will revisit it");
} else {
TRACE_SID_TXS(s->id, tx, "storing state: flags %08x", inspect_flags);
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
}
return retval;
}
/** \internal
* \brief get a DetectTransaction object
* \retval struct filled with relevant info or all nulls/0s
*/
static DetectTransaction GetTx(const uint8_t ipproto, const AppProto alproto,
void *alstate, const uint64_t tx_id, const int tx_end_state,
const uint8_t flow_flags)
{
void *tx_ptr = AppLayerParserGetTx(ipproto, alproto, alstate, tx_id);
if (tx_ptr == NULL) {
DetectTransaction no_tx = { NULL, 0, NULL, 0, 0, 0, 0, 0, };
return no_tx;
}
const uint64_t detect_flags = AppLayerParserGetTxDetectFlags(ipproto, alproto, tx_ptr, flow_flags);
if (detect_flags & APP_LAYER_TX_INSPECTED_FLAG) {
SCLogDebug("%"PRIu64" tx already fully inspected for %s. Flags %016"PRIx64,
tx_id, flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
detect_flags);
DetectTransaction no_tx = { NULL, 0, NULL, 0, 0, 0, 0, 0, };
return no_tx;
}
const int tx_progress = AppLayerParserGetStateProgress(ipproto, alproto, tx_ptr, flow_flags);
const int dir_int = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
DetectEngineState *tx_de_state = AppLayerParserGetTxDetectState(ipproto, alproto, tx_ptr);
DetectEngineStateDirection *tx_dir_state = tx_de_state ? &tx_de_state->dir_state[dir_int] : NULL;
uint64_t prefilter_flags = detect_flags & APP_LAYER_TX_PREFILTER_MASK;
DetectTransaction tx = {
.tx_ptr = tx_ptr,
.tx_id = tx_id,
.de_state = tx_dir_state,
.detect_flags = detect_flags,
.prefilter_flags = prefilter_flags,
.prefilter_flags_orig = prefilter_flags,
.tx_progress = tx_progress,
.tx_end_state = tx_end_state,
};
return tx;
}
static void DetectRunTx(ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
Flow *f,
DetectRunScratchpad *scratch)
{
const uint8_t flow_flags = scratch->flow_flags;
const SigGroupHead * const sgh = scratch->sgh;
void * const alstate = f->alstate;
const uint8_t ipproto = f->proto;
const AppProto alproto = f->alproto;
const uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate);
uint64_t tx_id = AppLayerParserGetTransactionInspectId(f->alparser, flow_flags);
const int tx_end_state = AppLayerParserGetStateProgressCompletionStatus(alproto, flow_flags);
for ( ; tx_id < total_txs; tx_id++) {
DetectTransaction tx = GetTx(ipproto, alproto,
alstate, tx_id, tx_end_state, flow_flags);
if (tx.tx_ptr == NULL) {
SCLogDebug("%p/%"PRIu64" no transaction to inspect",
tx.tx_ptr, tx_id);
continue;
}
uint32_t array_idx = 0;
uint32_t total_rules = det_ctx->match_array_cnt;
total_rules += (tx.de_state ? tx.de_state->cnt : 0);
/* run prefilter engines and merge results into a candidates array */
if (sgh->tx_engines) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_TX);
DetectRunPrefilterTx(det_ctx, sgh, p, ipproto, flow_flags, alproto,
alstate, &tx);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_PF_TX);
SCLogDebug("%p/%"PRIu64" rules added from prefilter: %u candidates",
tx.tx_ptr, tx_id, det_ctx->pmq.rule_id_array_cnt);
total_rules += det_ctx->pmq.rule_id_array_cnt;
if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
}
for (uint32_t i = 0; i < det_ctx->pmq.rule_id_array_cnt; i++) {
const Signature *s = de_ctx->sig_array[det_ctx->pmq.rule_id_array[i]];
const SigIntId id = s->num;
det_ctx->tx_candidates[array_idx].s = s;
det_ctx->tx_candidates[array_idx].id = id;
det_ctx->tx_candidates[array_idx].flags = NULL;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
}
} else {
if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
}
}
/* merge 'state' rules from the regular prefilter */
uint32_t x = array_idx;
for (uint32_t i = 0; i < det_ctx->match_array_cnt; i++) {
const Signature *s = det_ctx->match_array[i];
if (s->flags & SIG_FLAG_STATE_MATCH) {
const SigIntId id = s->num;
det_ctx->tx_candidates[array_idx].s = s;
det_ctx->tx_candidates[array_idx].id = id;
det_ctx->tx_candidates[array_idx].flags = NULL;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
SCLogDebug("%p/%"PRIu64" rule %u (%u) added from 'match' list",
tx.tx_ptr, tx_id, s->id, id);
}
}
SCLogDebug("%p/%"PRIu64" rules added from 'match' list: %u",
tx.tx_ptr, tx_id, array_idx - x); (void)x;
/* merge stored state into results */
if (tx.de_state != NULL) {
const uint32_t old = array_idx;
/* if tx.de_state->flags has 'new file' set and sig below has
* 'file inspected' flag, reset the file part of the state */
const bool have_new_file = (tx.de_state->flags & DETECT_ENGINE_STATE_FLAG_FILE_NEW);
if (have_new_file) {
SCLogDebug("%p/%"PRIu64" destate: need to consider new file",
tx.tx_ptr, tx_id);
tx.de_state->flags &= ~DETECT_ENGINE_STATE_FLAG_FILE_NEW;
}
SigIntId state_cnt = 0;
DeStateStore *tx_store = tx.de_state->head;
for (; tx_store != NULL; tx_store = tx_store->next) {
SCLogDebug("tx_store %p", tx_store);
SigIntId store_cnt = 0;
for (store_cnt = 0;
store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < tx.de_state->cnt;
store_cnt++, state_cnt++)
{
DeStateStoreItem *item = &tx_store->store[store_cnt];
SCLogDebug("rule id %u, inspect_flags %u", item->sid, item->flags);
if (have_new_file && (item->flags & DE_STATE_FLAG_FILE_INSPECT)) {
/* remove part of the state. File inspect engine will now
* be able to run again */
item->flags &= ~(DE_STATE_FLAG_SIG_CANT_MATCH|DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_FILE_INSPECT);
SCLogDebug("rule id %u, post file reset inspect_flags %u", item->sid, item->flags);
}
det_ctx->tx_candidates[array_idx].s = de_ctx->sig_array[item->sid];
det_ctx->tx_candidates[array_idx].id = item->sid;
det_ctx->tx_candidates[array_idx].flags = &item->flags;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
}
}
if (old && old != array_idx) {
qsort(det_ctx->tx_candidates, array_idx, sizeof(RuleMatchCandidateTx),
DetectRunTxSortHelper);
SCLogDebug("%p/%"PRIu64" rules added from 'continue' list: %u",
tx.tx_ptr, tx_id, array_idx - old);
}
}
det_ctx->tx_id = tx_id;
det_ctx->tx_id_set = 1;
det_ctx->p = p;
/* run rules: inspect the match candidates */
for (uint32_t i = 0; i < array_idx; i++) {
RuleMatchCandidateTx *can = &det_ctx->tx_candidates[i];
const Signature *s = det_ctx->tx_candidates[i].s;
uint32_t *inspect_flags = det_ctx->tx_candidates[i].flags;
/* deduplicate: rules_array is sorted, but not deduplicated:
* both mpm and stored state could give us the same sid.
* As they are back to back in that case we can check for it
* here. We select the stored state one. */
if ((i + 1) < array_idx) {
if (det_ctx->tx_candidates[i].s == det_ctx->tx_candidates[i+1].s) {
if (det_ctx->tx_candidates[i].flags != NULL) {
i++;
SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
} else if (det_ctx->tx_candidates[i+1].flags != NULL) {
SCLogDebug("%p/%"PRIu64" inspecting SKIP CURRENT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
continue;
} else {
// if it's all the same, inspect the current one and skip next.
i++;
SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
}
}
}
SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
if (inspect_flags) {
if (*inspect_flags & (DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_SIG_CANT_MATCH)) {
SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x ALREADY COMPLETE",
tx.tx_ptr, tx_id, s->id, s->num, *inspect_flags);
continue;
}
}
if (inspect_flags) {
/* continue previous inspection */
SCLogDebug("%p/%"PRIu64" Continueing sid %u", tx.tx_ptr, tx_id, s->id);
} else {
/* start new inspection */
SCLogDebug("%p/%"PRIu64" Start sid %u", tx.tx_ptr, tx_id, s->id);
}
/* call individual rule inspection */
RULE_PROFILING_START(p);
const int r = DetectRunTxInspectRule(tv, de_ctx, det_ctx, p, f, flow_flags,
alstate, &tx, s, inspect_flags, can, scratch);
if (r == 1) {
/* match */
DetectRunPostMatch(tv, det_ctx, p, s);
uint8_t alert_flags = (PACKET_ALERT_FLAG_STATE_MATCH|PACKET_ALERT_FLAG_TX);
if (s->action & ACTION_DROP)
alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
SCLogDebug("%p/%"PRIu64" sig %u (%u) matched", tx.tx_ptr, tx_id, s->id, s->num);
if (!(s->flags & SIG_FLAG_NOALERT)) {
PacketAlertAppend(det_ctx, s, p, tx_id, alert_flags);
} else {
DetectSignatureApplyActions(p, s, alert_flags);
}
}
DetectVarProcessList(det_ctx, p->flow, p);
RULE_PROFILING_END(det_ctx, s, r, p);
}
det_ctx->tx_id = 0;
det_ctx->tx_id_set = 0;
det_ctx->p = NULL;
/* see if we have any updated state to store in the tx */
uint64_t new_detect_flags = 0;
/* this side of the tx is done */
if (tx.tx_progress >= tx.tx_end_state) {
new_detect_flags |= APP_LAYER_TX_INSPECTED_FLAG;
SCLogDebug("%p/%"PRIu64" tx is done for direction %s. Flag %016"PRIx64,
tx.tx_ptr, tx_id,
flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
new_detect_flags);
}
if (tx.prefilter_flags != tx.prefilter_flags_orig) {
new_detect_flags |= tx.prefilter_flags;
SCLogDebug("%p/%"PRIu64" updated prefilter flags %016"PRIx64" "
"(was: %016"PRIx64") for direction %s. Flag %016"PRIx64,
tx.tx_ptr, tx_id, tx.prefilter_flags, tx.prefilter_flags_orig,
flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
new_detect_flags);
}
if (new_detect_flags != 0 &&
(new_detect_flags | tx.detect_flags) != tx.detect_flags)
{
new_detect_flags |= tx.detect_flags;
SCLogDebug("%p/%"PRIu64" Storing new flags %016"PRIx64" (was %016"PRIx64")",
tx.tx_ptr, tx_id, new_detect_flags, tx.detect_flags);
AppLayerParserSetTxDetectFlags(ipproto, alproto, tx.tx_ptr,
flow_flags, new_detect_flags);
}
}
}
/** \brief Apply action(s) and Set 'drop' sig info,
* if applicable */
void DetectSignatureApplyActions(Packet *p,
const Signature *s, const uint8_t alert_flags)
{
PACKET_UPDATE_ACTION(p, s->action);
if (s->action & ACTION_DROP) {
if (p->alerts.drop.action == 0) {
p->alerts.drop.num = s->num;
p->alerts.drop.action = s->action;
p->alerts.drop.s = (Signature *)s;
}
} else if (s->action & ACTION_PASS) {
/* if an stream/app-layer match we enforce the pass for the flow */
if ((p->flow != NULL) &&
(alert_flags & (PACKET_ALERT_FLAG_STATE_MATCH|PACKET_ALERT_FLAG_STREAM_MATCH)))
{
FlowSetNoPacketInspectionFlag(p->flow);
}
}
}
static DetectEngineThreadCtx *GetTenantById(HashTable *h, uint32_t id)
{
/* technically we need to pass a DetectEngineThreadCtx struct with the
* tentant_id member. But as that member is the first in the struct, we
* can use the id directly. */
return HashTableLookup(h, &id, 0);
}
static void DetectFlow(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
if (p->flags & PKT_NOPACKET_INSPECTION) {
/* hack: if we are in pass the entire flow mode, we need to still
* update the inspect_id forward. So test for the condition here,
* and call the update code if necessary. */
const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION));
const AppProto alproto = FlowGetAppProtocol(p->flow);
if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) {
uint8_t flags;
if (p->flowflags & FLOW_PKT_TOSERVER) {
flags = STREAM_TOSERVER;
} else {
flags = STREAM_TOCLIENT;
}
flags = FlowGetDisruptionFlags(p->flow, flags);
DeStateUpdateInspectTransactionId(p->flow, flags, true);
}
SCLogDebug("p->pcap %"PRIu64": no detection on packet, "
"PKT_NOPACKET_INSPECTION is set", p->pcap_cnt);
return;
}
/* see if the packet matches one or more of the sigs */
(void)DetectRun(tv, de_ctx, det_ctx, p);
}
static void DetectNoFlow(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
/* No need to perform any detection on this packet, if the the given flag is set.*/
if ((p->flags & PKT_NOPACKET_INSPECTION) ||
(PACKET_TEST_ACTION(p, ACTION_DROP)))
{
return;
}
/* see if the packet matches one or more of the sigs */
DetectRun(tv, de_ctx, det_ctx, p);
return;
}
/** \brief Detection engine thread wrapper.
* \param tv thread vars
* \param p packet to inspect
* \param data thread specific data
* \param pq packet queue
* \retval TM_ECODE_FAILED error
* \retval TM_ECODE_OK ok
*/
TmEcode Detect(ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
DEBUG_VALIDATE_PACKET(p);
DetectEngineCtx *de_ctx = NULL;
DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
if (det_ctx == NULL) {
printf("ERROR: Detect has no thread ctx\n");
goto error;
}
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("Detect Engine using new det_ctx - %p",
det_ctx);
}
/* if in MT mode _and_ we have tenants registered, use
* MT logic. */
if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL)
{
uint32_t tenant_id = p->tenant_id;
if (tenant_id == 0)
tenant_id = det_ctx->TenantGetId(det_ctx, p);
if (tenant_id > 0 && tenant_id < det_ctx->mt_det_ctxs_cnt) {
p->tenant_id = tenant_id;
det_ctx = GetTenantById(det_ctx->mt_det_ctxs_hash, tenant_id);
if (det_ctx == NULL)
return TM_ECODE_OK;
de_ctx = det_ctx->de_ctx;
if (de_ctx == NULL)
return TM_ECODE_OK;
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("MT de_ctx %p det_ctx %p (tenant %u)", de_ctx, det_ctx, tenant_id);
}
} else {
/* use default if no tenants are registered for this packet */
de_ctx = det_ctx->de_ctx;
}
} else {
de_ctx = det_ctx->de_ctx;
}
if (p->flow) {
DetectFlow(tv, de_ctx, det_ctx, p);
} else {
DetectNoFlow(tv, de_ctx, det_ctx, p);
}
return TM_ECODE_OK;
error:
return TM_ECODE_FAILED;
}
/** \brief disable file features we don't need
* Called if we have no detection engine.
*/
void DisableDetectFlowFileFlags(Flow *f)
{
DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOSERVER);
DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOCLIENT);
}
#ifdef UNITTESTS
/**
* \brief wrapper for old tests
*/
void SigMatchSignatures(ThreadVars *th_v,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
DetectRun(th_v, de_ctx, det_ctx, p);
}
#endif
/*
* TESTS
*/
#ifdef UNITTESTS
#include "tests/detect.c"
#endif
| ./CrossVul/dataset_final_sorted/CWE-693/c/good_616_0 |
crossvul-cpp_data_bad_616_0 | /* Copyright (C) 2007-2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
*
* Basic detection engine
*/
#include "suricata-common.h"
#include "suricata.h"
#include "conf.h"
#include "decode.h"
#include "flow.h"
#include "stream-tcp.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "detect.h"
#include "detect-engine.h"
#include "detect-engine-profile.h"
#include "detect-engine-alert.h"
#include "detect-engine-siggroup.h"
#include "detect-engine-address.h"
#include "detect-engine-proto.h"
#include "detect-engine-port.h"
#include "detect-engine-mpm.h"
#include "detect-engine-iponly.h"
#include "detect-engine-threshold.h"
#include "detect-engine-prefilter.h"
#include "detect-engine-state.h"
#include "detect-engine-analyzer.h"
#include "detect-engine-filedata.h"
#include "detect-engine-payload.h"
#include "detect-engine-event.h"
#include "detect-engine-hcbd.h"
#include "detect-engine-hsbd.h"
#include "detect-filestore.h"
#include "detect-flowvar.h"
#include "detect-replace.h"
#include "util-validate.h"
#include "util-detect.h"
typedef struct DetectRunScratchpad {
const AppProto alproto;
const uint8_t flow_flags; /* flow/state flags: STREAM_* */
const bool app_decoder_events;
const SigGroupHead *sgh;
SignatureMask pkt_mask;
} DetectRunScratchpad;
/* prototypes */
static DetectRunScratchpad DetectRunSetup(const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow);
static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Flow * const pflow, Packet * const p);
static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx,
Packet * const p, Flow * const pflow, DetectRunScratchpad *scratch);
static inline void DetectRunPrefilterPkt(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p,
DetectRunScratchpad *scratch);
static inline void DetectRulePacketRules(ThreadVars * const tv,
DetectEngineCtx * const de_ctx, DetectEngineThreadCtx * const det_ctx,
Packet * const p, Flow * const pflow, const DetectRunScratchpad *scratch);
static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet *p,
Flow *f, DetectRunScratchpad *scratch);
static inline void DetectRunPostRules(ThreadVars *tv, DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow,
DetectRunScratchpad *scratch);
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow);
/** \internal
*/
static void DetectRun(ThreadVars *th_v,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
SCEnter();
SCLogDebug("pcap_cnt %"PRIu64, p->pcap_cnt);
/* bail early if packet should not be inspected */
if (p->flags & PKT_NOPACKET_INSPECTION) {
/* nothing to do */
SCReturn;
}
/* Load the Packet's flow early, even though it might not be needed.
* Mark as a constant pointer, although the flow itself can change. */
Flow * const pflow = p->flow;
DetectRunScratchpad scratch = DetectRunSetup(de_ctx, det_ctx, p, pflow);
/* run the IPonly engine */
DetectRunInspectIPOnly(th_v, de_ctx, det_ctx, pflow, p);
/* get our rule group */
DetectRunGetRuleGroup(de_ctx, p, pflow, &scratch);
/* if we didn't get a sig group head, we
* have nothing to do.... */
if (scratch.sgh == NULL) {
SCLogDebug("no sgh for this packet, nothing to match against");
goto end;
}
/* run the prefilters for packets */
DetectRunPrefilterPkt(th_v, de_ctx, det_ctx, p, &scratch);
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_RULES);
/* inspect the rules against the packet */
DetectRulePacketRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_RULES);
/* run tx/state inspection */
if (pflow && pflow->alstate) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_TX);
DetectRunTx(th_v, de_ctx, det_ctx, p, pflow, &scratch);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_TX);
}
end:
DetectRunPostRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
DetectRunCleanup(det_ctx, p, pflow);
SCReturn;
}
static void DetectRunPostMatch(ThreadVars *tv,
DetectEngineThreadCtx *det_ctx, Packet *p,
const Signature *s)
{
/* run the packet match functions */
const SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_POSTMATCH];
if (smd != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_POSTMATCH);
SCLogDebug("running match functions, sm %p", smd);
while (1) {
KEYWORD_PROFILING_START;
(void)sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx);
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (smd->is_last)
break;
smd++;
}
}
DetectReplaceExecute(p, det_ctx);
if (s->flags & SIG_FLAG_FILESTORE)
DetectFilestorePostMatch(tv, det_ctx, p, s);
return;
}
/**
* \brief Get the SigGroupHead for a packet.
*
* \param de_ctx detection engine context
* \param p packet
*
* \retval sgh the SigGroupHead or NULL if non applies to the packet
*/
const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx,
const Packet *p)
{
SCEnter();
int f;
SigGroupHead *sgh = NULL;
/* if the packet proto is 0 (not set), we're inspecting it against
* the decoder events sgh we have. */
if (p->proto == 0 && p->events.cnt > 0) {
SCReturnPtr(de_ctx->decoder_event_sgh, "SigGroupHead");
} else if (p->proto == 0) {
if (!(PKT_IS_IPV4(p) || PKT_IS_IPV6(p))) {
/* not IP, so nothing to do */
SCReturnPtr(NULL, "SigGroupHead");
}
}
/* select the flow_gh */
if (p->flowflags & FLOW_PKT_TOCLIENT)
f = 0;
else
f = 1;
int proto = IP_GET_IPPROTO(p);
if (proto == IPPROTO_TCP) {
DetectPort *list = de_ctx->flow_gh[f].tcp;
SCLogDebug("tcp toserver %p, tcp toclient %p: going to use %p",
de_ctx->flow_gh[1].tcp, de_ctx->flow_gh[0].tcp, de_ctx->flow_gh[f].tcp);
uint16_t port = f ? p->dp : p->sp;
SCLogDebug("tcp port %u -> %u:%u", port, p->sp, p->dp);
DetectPort *sghport = DetectPortLookupGroup(list, port);
if (sghport != NULL)
sgh = sghport->sh;
SCLogDebug("TCP list %p, port %u, direction %s, sghport %p, sgh %p",
list, port, f ? "toserver" : "toclient", sghport, sgh);
} else if (proto == IPPROTO_UDP) {
DetectPort *list = de_ctx->flow_gh[f].udp;
uint16_t port = f ? p->dp : p->sp;
DetectPort *sghport = DetectPortLookupGroup(list, port);
if (sghport != NULL)
sgh = sghport->sh;
SCLogDebug("UDP list %p, port %u, direction %s, sghport %p, sgh %p",
list, port, f ? "toserver" : "toclient", sghport, sgh);
} else {
sgh = de_ctx->flow_gh[f].sgh[proto];
}
SCReturnPtr(sgh, "SigGroupHead");
}
static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx)
{
SigIntId mpm, nonmpm;
det_ctx->match_array_cnt = 0;
SigIntId *mpm_ptr = det_ctx->pmq.rule_id_array;
SigIntId *nonmpm_ptr = det_ctx->non_pf_id_array;
uint32_t m_cnt = det_ctx->pmq.rule_id_array_cnt;
uint32_t n_cnt = det_ctx->non_pf_id_cnt;
SigIntId *final_ptr;
uint32_t final_cnt;
SigIntId id;
SigIntId previous_id = (SigIntId)-1;
Signature **sig_array = de_ctx->sig_array;
Signature **match_array = det_ctx->match_array;
Signature *s;
SCLogDebug("PMQ rule id array count %d", det_ctx->pmq.rule_id_array_cnt);
/* Load first values. */
if (likely(m_cnt)) {
mpm = *mpm_ptr;
} else {
/* mpm list is empty */
final_ptr = nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
if (likely(n_cnt)) {
nonmpm = *nonmpm_ptr;
} else {
/* non-mpm list is empty. */
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
while (1) {
if (mpm < nonmpm) {
/* Take from mpm list */
id = mpm;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
if (unlikely(--m_cnt == 0)) {
/* mpm list is now empty */
final_ptr = nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
mpm_ptr++;
mpm = *mpm_ptr;
} else if (mpm > nonmpm) {
id = nonmpm;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
if (unlikely(--n_cnt == 0)) {
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
nonmpm_ptr++;
nonmpm = *nonmpm_ptr;
} else { /* implied mpm == nonmpm */
/* special case: if on both lists, it's a negated mpm pattern */
/* mpm list may have dups, so skip past them here */
while (--m_cnt != 0) {
mpm_ptr++;
mpm = *mpm_ptr;
if (mpm != nonmpm)
break;
}
/* if mpm is done, update nonmpm_ptrs and jump to final */
if (unlikely(m_cnt == 0)) {
n_cnt--;
/* mpm list is now empty */
final_ptr = ++nonmpm_ptr;
final_cnt = n_cnt;
goto final;
}
/* otherwise, if nonmpm is done jump to final for mpm
* mpm ptrs alrady updated */
if (unlikely(--n_cnt == 0)) {
final_ptr = mpm_ptr;
final_cnt = m_cnt;
goto final;
}
/* not at end of the lists, update nonmpm. Mpm already
* updated in while loop above. */
nonmpm_ptr++;
nonmpm = *nonmpm_ptr;
}
}
final: /* Only one list remaining. Just walk that list. */
while (final_cnt-- > 0) {
id = *final_ptr++;
s = sig_array[id];
/* As the mpm list can contain duplicates, check for that here. */
if (likely(id != previous_id)) {
*match_array++ = s;
previous_id = id;
}
}
det_ctx->match_array_cnt = match_array - det_ctx->match_array;
BUG_ON((det_ctx->pmq.rule_id_array_cnt + det_ctx->non_pf_id_cnt) < det_ctx->match_array_cnt);
}
static inline void
DetectPrefilterBuildNonPrefilterList(DetectEngineThreadCtx *det_ctx, SignatureMask mask, uint8_t alproto)
{
uint32_t x = 0;
for (x = 0; x < det_ctx->non_pf_store_cnt; x++) {
/* only if the mask matches this rule can possibly match,
* so build the non_mpm array only for match candidates */
const SignatureMask rule_mask = det_ctx->non_pf_store_ptr[x].mask;
const uint8_t rule_alproto = det_ctx->non_pf_store_ptr[x].alproto;
if ((rule_mask & mask) == rule_mask && (rule_alproto == 0 || rule_alproto == alproto)) { // TODO dce?
det_ctx->non_pf_id_array[det_ctx->non_pf_id_cnt++] = det_ctx->non_pf_store_ptr[x].id;
}
}
}
/** \internal
* \brief select non-mpm list
* Based on the packet properties, select the non-mpm list to use
* \todo move non_pf_store* into scratchpad */
static inline void
DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch)
{
if ((p->proto == IPPROTO_TCP) && (p->tcph != NULL) && (p->tcph->th_flags & TH_SYN)) {
det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_syn_store_array;
det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_syn_store_cnt;
} else {
det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_other_store_array;
det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_other_store_cnt;
}
SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)",
det_ctx->non_pf_store_ptr, det_ctx->non_pf_store_cnt,
scratch->sgh->non_pf_syn_store_array, scratch->sgh->non_pf_syn_store_cnt,
scratch->sgh->non_pf_other_store_array, scratch->sgh->non_pf_other_store_cnt);
}
/** \internal
* \brief update flow's file tracking flags based on the detection engine
*/
static inline void
DetectPostInspectFileFlagsUpdate(Flow *pflow, const SigGroupHead *sgh, uint8_t direction)
{
/* see if this sgh requires us to consider file storing */
if (!FileForceFilestore() && (sgh == NULL ||
sgh->filestore_cnt == 0))
{
FileDisableStoring(pflow, direction);
}
#ifdef HAVE_MAGIC
/* see if this sgh requires us to consider file magic */
if (!FileForceMagic() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMAGIC)))
{
SCLogDebug("disabling magic for flow");
FileDisableMagic(pflow, direction);
}
#endif
/* see if this sgh requires us to consider file md5 */
if (!FileForceMd5() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMD5)))
{
SCLogDebug("disabling md5 for flow");
FileDisableMd5(pflow, direction);
}
/* see if this sgh requires us to consider file sha1 */
if (!FileForceSha1() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA1)))
{
SCLogDebug("disabling sha1 for flow");
FileDisableSha1(pflow, direction);
}
/* see if this sgh requires us to consider file sha256 */
if (!FileForceSha256() && (sgh == NULL ||
!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA256)))
{
SCLogDebug("disabling sha256 for flow");
FileDisableSha256(pflow, direction);
}
/* see if this sgh requires us to consider filesize */
if (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVEFILESIZE))
{
SCLogDebug("disabling filesize for flow");
FileDisableFilesize(pflow, direction);
}
}
static inline void
DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead *sgh)
{
if ((p->flowflags & FLOW_PKT_TOSERVER) && !(pflow->flags & FLOW_SGH_TOSERVER)) {
/* first time we see this toserver sgh, store it */
pflow->sgh_toserver = sgh;
pflow->flags |= FLOW_SGH_TOSERVER;
if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
if (pflow->protoctx != NULL) {
TcpSession *ssn = pflow->protoctx;
SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.client");
ssn->client.flags |= STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
}
DetectPostInspectFileFlagsUpdate(pflow,
pflow->sgh_toserver, STREAM_TOSERVER);
} else if ((p->flowflags & FLOW_PKT_TOCLIENT) && !(pflow->flags & FLOW_SGH_TOCLIENT)) {
pflow->sgh_toclient = sgh;
pflow->flags |= FLOW_SGH_TOCLIENT;
if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
if (pflow->protoctx != NULL) {
TcpSession *ssn = pflow->protoctx;
SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.server");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
}
DetectPostInspectFileFlagsUpdate(pflow,
pflow->sgh_toclient, STREAM_TOCLIENT);
}
}
static inline void DetectRunGetRuleGroup(
const DetectEngineCtx *de_ctx,
Packet * const p, Flow * const pflow,
DetectRunScratchpad *scratch)
{
const SigGroupHead *sgh = NULL;
if (pflow) {
bool use_flow_sgh = false;
/* Get the stored sgh from the flow (if any). Make sure we're not using
* the sgh for icmp error packets part of the same stream. */
if (IP_GET_IPPROTO(p) == pflow->proto) { /* filter out icmp */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
if ((p->flowflags & FLOW_PKT_TOSERVER) && (pflow->flags & FLOW_SGH_TOSERVER)) {
sgh = pflow->sgh_toserver;
SCLogDebug("sgh = pflow->sgh_toserver; => %p", sgh);
use_flow_sgh = true;
} else if ((p->flowflags & FLOW_PKT_TOCLIENT) && (pflow->flags & FLOW_SGH_TOCLIENT)) {
sgh = pflow->sgh_toclient;
SCLogDebug("sgh = pflow->sgh_toclient; => %p", sgh);
use_flow_sgh = true;
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
}
if (!(use_flow_sgh)) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
sgh = SigMatchSignaturesGetSgh(de_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
/* HACK: prevent the wrong sgh (or NULL) from being stored in the
* flow's sgh pointers */
if (PKT_IS_ICMPV4(p) && ICMPV4_DEST_UNREACH_IS_VALID(p)) {
; /* no-op */
} else {
/* store the found sgh (or NULL) in the flow to save us
* from looking it up again for the next packet.
* Also run other tasks */
DetectRunPostGetFirstRuleGroup(p, pflow, sgh);
}
}
} else { /* p->flags & PKT_HAS_FLOW */
/* no flow */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_GETSGH);
sgh = SigMatchSignaturesGetSgh(de_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_GETSGH);
}
scratch->sgh = sgh;
}
static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Flow * const pflow, Packet * const p)
{
if (pflow) {
/* set the iponly stuff */
if (pflow->flags & FLOW_TOCLIENT_IPONLY_SET)
p->flowflags |= FLOW_PKT_TOCLIENT_IPONLY_SET;
if (pflow->flags & FLOW_TOSERVER_IPONLY_SET)
p->flowflags |= FLOW_PKT_TOSERVER_IPONLY_SET;
if (((p->flowflags & FLOW_PKT_TOSERVER) && !(p->flowflags & FLOW_PKT_TOSERVER_IPONLY_SET)) ||
((p->flowflags & FLOW_PKT_TOCLIENT) && !(p->flowflags & FLOW_PKT_TOCLIENT_IPONLY_SET)))
{
SCLogDebug("testing against \"ip-only\" signatures");
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_IPONLY);
IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx, &det_ctx->io_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_IPONLY);
/* save in the flow that we scanned this direction... */
FlowSetIPOnlyFlag(pflow, p->flowflags & FLOW_PKT_TOSERVER ? 1 : 0);
} else if (((p->flowflags & FLOW_PKT_TOSERVER) &&
(pflow->flags & FLOW_TOSERVER_IPONLY_SET)) ||
((p->flowflags & FLOW_PKT_TOCLIENT) &&
(pflow->flags & FLOW_TOCLIENT_IPONLY_SET)))
{
/* If we have a drop from IP only module,
* we will drop the rest of the flow packets
* This will apply only to inline/IPS */
if (pflow->flags & FLOW_ACTION_DROP) {
PACKET_DROP(p);
}
}
} else { /* p->flags & PKT_HAS_FLOW */
/* no flow */
/* Even without flow we should match the packet src/dst */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_IPONLY);
IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx,
&det_ctx->io_ctx, p);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_IPONLY);
}
}
/* returns 0 if no match, 1 if match */
static inline int DetectRunInspectRuleHeader(
const Packet *p,
const Flow *f,
const Signature *s,
const uint32_t sflags,
const uint8_t s_proto_flags)
{
/* check if this signature has a requirement for flowvars of some type
* and if so, if we actually have any in the flow. If not, the sig
* can't match and we skip it. */
if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) {
int m = f->flowvar ? 1 : 0;
/* no flowvars? skip this sig */
if (m == 0) {
SCLogDebug("skipping sig as the flow has no flowvars and sig "
"has SIG_FLAG_REQUIRE_FLOWVAR flag set.");
return 0;
}
}
if ((s_proto_flags & DETECT_PROTO_IPV4) && !PKT_IS_IPV4(p)) {
SCLogDebug("ip version didn't match");
return 0;
}
if ((s_proto_flags & DETECT_PROTO_IPV6) && !PKT_IS_IPV6(p)) {
SCLogDebug("ip version didn't match");
return 0;
}
if (DetectProtoContainsProto(&s->proto, IP_GET_IPPROTO(p)) == 0) {
SCLogDebug("proto didn't match");
return 0;
}
/* check the source & dst port in the sig */
if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) {
if (!(sflags & SIG_FLAG_DP_ANY)) {
if (p->flags & PKT_IS_FRAGMENT)
return 0;
DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp);
if (dport == NULL) {
SCLogDebug("dport didn't match.");
return 0;
}
}
if (!(sflags & SIG_FLAG_SP_ANY)) {
if (p->flags & PKT_IS_FRAGMENT)
return 0;
DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp);
if (sport == NULL) {
SCLogDebug("sport didn't match.");
return 0;
}
}
} else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) {
SCLogDebug("port-less protocol and sig needs ports");
return 0;
}
/* check the destination address */
if (!(sflags & SIG_FLAG_DST_ANY)) {
if (PKT_IS_IPV4(p)) {
if (DetectAddressMatchIPv4(s->addr_dst_match4, s->addr_dst_match4_cnt, &p->dst) == 0)
return 0;
} else if (PKT_IS_IPV6(p)) {
if (DetectAddressMatchIPv6(s->addr_dst_match6, s->addr_dst_match6_cnt, &p->dst) == 0)
return 0;
}
}
/* check the source address */
if (!(sflags & SIG_FLAG_SRC_ANY)) {
if (PKT_IS_IPV4(p)) {
if (DetectAddressMatchIPv4(s->addr_src_match4, s->addr_src_match4_cnt, &p->src) == 0)
return 0;
} else if (PKT_IS_IPV6(p)) {
if (DetectAddressMatchIPv6(s->addr_src_match6, s->addr_src_match6_cnt, &p->src) == 0)
return 0;
}
}
return 1;
}
/* returns 0 if no match, 1 if match */
static inline int DetectRunInspectRulePacketMatches(
ThreadVars *tv,
DetectEngineThreadCtx *det_ctx,
Packet *p,
const Flow *f,
const Signature *s)
{
/* run the packet match functions */
if (s->sm_arrays[DETECT_SM_LIST_MATCH] != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_MATCH);
SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_MATCH];
SCLogDebug("running match functions, sm %p", smd);
if (smd != NULL) {
while (1) {
KEYWORD_PROFILING_START;
if (sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx) <= 0) {
KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
SCLogDebug("no match");
return 0;
}
KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
if (smd->is_last) {
SCLogDebug("match and is_last");
break;
}
smd++;
}
}
}
return 1;
}
/** \internal
* \brief run packet/stream prefilter engines
*/
static inline void DetectRunPrefilterPkt(
ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
DetectRunScratchpad *scratch
)
{
DetectPrefilterSetNonPrefilterList(p, det_ctx, scratch);
/* create our prefilter mask */
PacketCreateMask(p, &scratch->pkt_mask, scratch->alproto, scratch->app_decoder_events);
/* build and prefilter non_pf list against the mask of the packet */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_NONMPMLIST);
det_ctx->non_pf_id_cnt = 0;
if (likely(det_ctx->non_pf_store_cnt > 0)) {
DetectPrefilterBuildNonPrefilterList(det_ctx, scratch->pkt_mask, scratch->alproto);
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_NONMPMLIST);
/* run the prefilter engines */
Prefilter(det_ctx, scratch->sgh, p, scratch->flow_flags);
/* create match list if we have non-pf and/or pf */
if (det_ctx->non_pf_store_cnt || det_ctx->pmq.rule_id_array_cnt) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_SORT2);
DetectPrefilterMergeSort(de_ctx, det_ctx);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_PF_SORT2);
}
#ifdef PROFILING
if (tv) {
StatsAddUI64(tv, det_ctx->counter_mpm_list,
(uint64_t)det_ctx->pmq.rule_id_array_cnt);
StatsAddUI64(tv, det_ctx->counter_nonmpm_list,
(uint64_t)det_ctx->non_pf_store_cnt);
/* non mpm sigs after mask prefilter */
StatsAddUI64(tv, det_ctx->counter_fnonmpm_list,
(uint64_t)det_ctx->non_pf_id_cnt);
}
#endif
}
static inline void DetectRulePacketRules(
ThreadVars * const tv,
DetectEngineCtx * const de_ctx,
DetectEngineThreadCtx * const det_ctx,
Packet * const p,
Flow * const pflow,
const DetectRunScratchpad *scratch
)
{
const Signature *s = NULL;
const Signature *next_s = NULL;
/* inspect the sigs against the packet */
/* Prefetch the next signature. */
SigIntId match_cnt = det_ctx->match_array_cnt;
#ifdef PROFILING
if (tv) {
StatsAddUI64(tv, det_ctx->counter_match_list,
(uint64_t)match_cnt);
}
#endif
Signature **match_array = det_ctx->match_array;
SGH_PROFILING_RECORD(det_ctx, scratch->sgh);
#ifdef PROFILING
#ifdef HAVE_LIBJANSSON
if (match_cnt >= de_ctx->profile_match_logging_threshold)
RulesDumpMatchArray(det_ctx, scratch->sgh, p);
#endif
#endif
uint32_t sflags, next_sflags = 0;
if (match_cnt) {
next_s = *match_array++;
next_sflags = next_s->flags;
}
while (match_cnt--) {
RULE_PROFILING_START(p);
uint8_t alert_flags = 0;
bool state_alert = false;
#ifdef PROFILING
bool smatch = false; /* signature match */
#endif
s = next_s;
sflags = next_sflags;
if (match_cnt) {
next_s = *match_array++;
next_sflags = next_s->flags;
}
const uint8_t s_proto_flags = s->proto.flags;
SCLogDebug("inspecting signature id %"PRIu32"", s->id);
if (sflags & SIG_FLAG_STATE_MATCH) {
goto next; // TODO skip and handle in DetectRunTx
}
/* don't run mask check for stateful rules.
* There we depend on prefilter */
if ((s->mask & scratch->pkt_mask) != s->mask) {
SCLogDebug("mask mismatch %x & %x != %x", s->mask, scratch->pkt_mask, s->mask);
goto next;
}
if (unlikely(sflags & SIG_FLAG_DSIZE)) {
if (likely(p->payload_len < s->dsize_low || p->payload_len > s->dsize_high)) {
SCLogDebug("kicked out as p->payload_len %u, dsize low %u, hi %u",
p->payload_len, s->dsize_low, s->dsize_high);
goto next;
}
}
/* if the sig has alproto and the session as well they should match */
if (likely(sflags & SIG_FLAG_APPLAYER)) {
if (s->alproto != ALPROTO_UNKNOWN && s->alproto != scratch->alproto) {
if (s->alproto == ALPROTO_DCERPC) {
if (scratch->alproto != ALPROTO_SMB && scratch->alproto != ALPROTO_SMB2) {
SCLogDebug("DCERPC sig, alproto not SMB or SMB2");
goto next;
}
} else {
SCLogDebug("alproto mismatch");
goto next;
}
}
}
if (DetectRunInspectRuleHeader(p, pflow, s, sflags, s_proto_flags) == 0) {
goto next;
}
/* Check the payload keywords. If we are a MPM sig and we've made
* to here, we've had at least one of the patterns match */
if (!(sflags & SIG_FLAG_STATE_MATCH) && s->sm_arrays[DETECT_SM_LIST_PMATCH] != NULL) {
KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_PMATCH);
/* if we have stream msgs, inspect against those first,
* but not for a "dsize" signature */
if (sflags & SIG_FLAG_REQUIRE_STREAM) {
int pmatch = 0;
if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
pmatch = DetectEngineInspectStreamPayload(de_ctx, det_ctx, s, pflow, p);
if (pmatch) {
det_ctx->flags |= DETECT_ENGINE_THREAD_CTX_STREAM_CONTENT_MATCH;
/* Tell the engine that this reassembled stream can drop the
* rest of the pkts with no further inspection */
if (s->action & ACTION_DROP)
alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
alert_flags |= PACKET_ALERT_FLAG_STREAM_MATCH;
}
}
/* no match? then inspect packet payload */
if (pmatch == 0) {
SCLogDebug("no match in stream, fall back to packet payload");
/* skip if we don't have to inspect the packet and segment was
* added to stream */
if (!(sflags & SIG_FLAG_REQUIRE_PACKET) && (p->flags & PKT_STREAM_ADD)) {
goto next;
}
if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
goto next;
}
}
} else {
if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
goto next;
}
}
}
if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, pflow, s) == 0)
goto next;
#ifdef PROFILING
smatch = true;
#endif
DetectRunPostMatch(tv, det_ctx, p, s);
if (!(sflags & SIG_FLAG_NOALERT)) {
/* stateful sigs call PacketAlertAppend from DeStateDetectStartDetection */
if (!state_alert)
PacketAlertAppend(det_ctx, s, p, 0, alert_flags);
} else {
/* apply actions even if not alerting */
DetectSignatureApplyActions(p, s, alert_flags);
}
next:
DetectVarProcessList(det_ctx, pflow, p);
DetectReplaceFree(det_ctx);
RULE_PROFILING_END(det_ctx, s, smatch, p);
det_ctx->flags = 0;
continue;
}
}
static DetectRunScratchpad DetectRunSetup(
const DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet * const p, Flow * const pflow)
{
AppProto alproto = ALPROTO_UNKNOWN;
uint8_t flow_flags = 0; /* flow/state flags */
bool app_decoder_events = false;
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_SETUP);
#ifdef UNITTESTS
p->alerts.cnt = 0;
#endif
det_ctx->ticker++;
det_ctx->filestore_cnt = 0;
det_ctx->base64_decoded_len = 0;
det_ctx->raw_stream_progress = 0;
#ifdef DEBUG
if (p->flags & PKT_STREAM_ADD) {
det_ctx->pkt_stream_add_cnt++;
}
#endif
/* grab the protocol state we will detect on */
if (p->flags & PKT_HAS_FLOW) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flow_flags = STREAM_TOSERVER;
SCLogDebug("flag STREAM_TOSERVER set");
} else if (p->flowflags & FLOW_PKT_TOCLIENT) {
flow_flags = STREAM_TOCLIENT;
SCLogDebug("flag STREAM_TOCLIENT set");
}
SCLogDebug("p->flowflags 0x%02x", p->flowflags);
if (p->flags & PKT_STREAM_EOF) {
flow_flags |= STREAM_EOF;
SCLogDebug("STREAM_EOF set");
}
/* store tenant_id in the flow so that we can use it
* for creating pseudo packets */
if (p->tenant_id > 0 && pflow->tenant_id == 0) {
pflow->tenant_id = p->tenant_id;
}
/* live ruleswap check for flow updates */
if (pflow->de_ctx_version == 0) {
/* first time this flow is inspected, set id */
pflow->de_ctx_version = de_ctx->version;
} else if (pflow->de_ctx_version != de_ctx->version) {
/* first time we inspect flow with this de_ctx, reset */
pflow->flags &= ~FLOW_SGH_TOSERVER;
pflow->flags &= ~FLOW_SGH_TOCLIENT;
pflow->sgh_toserver = NULL;
pflow->sgh_toclient = NULL;
pflow->de_ctx_version = de_ctx->version;
GenericVarFree(pflow->flowvar);
pflow->flowvar = NULL;
DetectEngineStateResetTxs(pflow);
}
/* Retrieve the app layer state and protocol and the tcp reassembled
* stream chunks. */
if ((p->proto == IPPROTO_TCP && (p->flags & PKT_STREAM_EST)) ||
(p->proto == IPPROTO_UDP) ||
(p->proto == IPPROTO_SCTP && (p->flowflags & FLOW_PKT_ESTABLISHED)))
{
/* update flow flags with knowledge on disruptions */
flow_flags = FlowGetDisruptionFlags(pflow, flow_flags);
alproto = FlowGetAppProtocol(pflow);
if (p->proto == IPPROTO_TCP && pflow->protoctx &&
StreamReassembleRawHasDataReady(pflow->protoctx, p)) {
p->flags |= PKT_DETECT_HAS_STREAMDATA;
}
SCLogDebug("alproto %u", alproto);
} else {
SCLogDebug("packet doesn't have established flag set (proto %d)", p->proto);
}
app_decoder_events = AppLayerParserHasDecoderEvents(pflow->alparser);
}
DetectRunScratchpad pad = { alproto, flow_flags, app_decoder_events, NULL, 0 };
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_SETUP);
return pad;
}
static inline void DetectRunPostRules(
ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet * const p,
Flow * const pflow,
DetectRunScratchpad *scratch)
{
/* see if we need to increment the inspect_id and reset the de_state */
if (pflow && pflow->alstate && AppLayerParserProtocolSupportsTxs(p->proto, scratch->alproto)) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_TX_UPDATE);
DeStateUpdateInspectTransactionId(pflow, scratch->flow_flags, (scratch->sgh == NULL));
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_TX_UPDATE);
}
/* so now let's iterate the alerts and remove the ones after a pass rule
* matched (if any). This is done inside PacketAlertFinalize() */
/* PR: installed "tag" keywords are handled after the threshold inspection */
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_ALERT);
PacketAlertFinalize(de_ctx, det_ctx, p);
if (p->alerts.cnt > 0) {
StatsAddUI64(tv, det_ctx->counter_alerts, (uint64_t)p->alerts.cnt);
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_ALERT);
}
static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow)
{
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);
/* cleanup pkt specific part of the patternmatcher */
PacketPatternCleanup(det_ctx);
if (pflow != NULL) {
/* update inspected tracker for raw reassembly */
if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {
StreamReassembleRawUpdateProgress(pflow->protoctx, p,
det_ctx->raw_stream_progress);
DetectEngineCleanHCBDBuffers(det_ctx);
DetectEngineCleanHSBDBuffers(det_ctx);
DetectEngineCleanFiledataBuffers(det_ctx);
}
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);
SCReturn;
}
void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size)
{
DEBUG_VALIDATE_BUG_ON(det_ctx->tx_candidates);
det_ctx->tx_candidates = SCCalloc(size, sizeof(RuleMatchCandidateTx));
if (det_ctx->tx_candidates == NULL) {
FatalError(SC_ERR_MEM_ALLOC, "failed to allocate %"PRIu64" bytes",
(uint64_t)(size * sizeof(RuleMatchCandidateTx)));
}
det_ctx->tx_candidates_size = size;
SCLogDebug("array initialized to %u elements (%"PRIu64" bytes)",
size, (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
}
void RuleMatchCandidateTxArrayFree(DetectEngineThreadCtx *det_ctx)
{
SCFree(det_ctx->tx_candidates);
det_ctx->tx_candidates_size = 0;
}
/* if size >= cur_space */
static inline bool RuleMatchCandidateTxArrayHasSpace(const DetectEngineThreadCtx *det_ctx,
const uint32_t need)
{
if (det_ctx->tx_candidates_size >= need)
return 1;
return 0;
}
/* realloc */
static int RuleMatchCandidateTxArrayExpand(DetectEngineThreadCtx *det_ctx, const uint32_t needed)
{
const uint32_t old_size = det_ctx->tx_candidates_size;
uint32_t new_size = needed;
void *ptmp = SCRealloc(det_ctx->tx_candidates, (new_size * sizeof(RuleMatchCandidateTx)));
if (ptmp == NULL) {
FatalError(SC_ERR_MEM_ALLOC, "failed to expand to %"PRIu64" bytes",
(uint64_t)(new_size * sizeof(RuleMatchCandidateTx)));
// TODO can this be handled more gracefully?
}
det_ctx->tx_candidates = ptmp;
det_ctx->tx_candidates_size = new_size;
SCLogDebug("array expanded from %u to %u elements (%"PRIu64" bytes -> %"PRIu64" bytes)",
old_size, new_size, (uint64_t)(old_size * sizeof(RuleMatchCandidateTx)),
(uint64_t)(new_size * sizeof(RuleMatchCandidateTx))); (void)old_size;
return 1;
}
/* TODO maybe let one with flags win if equal? */
static int
DetectRunTxSortHelper(const void *a, const void *b)
{
const RuleMatchCandidateTx *s0 = a;
const RuleMatchCandidateTx *s1 = b;
if (s1->id == s0->id)
return 0;
else
return s0->id > s1->id ? -1 : 1;
}
#if 0
#define TRACE_SID_TXS(sid,txs,...) \
do { \
char _trace_buf[2048]; \
snprintf(_trace_buf, sizeof(_trace_buf), __VA_ARGS__); \
SCLogNotice("%p/%"PRIu64"/%u: %s", txs->tx_ptr, txs->tx_id, sid, _trace_buf); \
} while(0)
#else
#define TRACE_SID_TXS(sid,txs,...)
#endif
/** \internal
* \brief inspect a rule against a transaction
*
* Inspect a rule. New detection or continued stateful
* detection.
*
* \param stored_flags pointer to stored flags or NULL.
* If stored_flags is set it means we're continueing
* inspection from an earlier run.
*
* \retval bool true sig matched, false didn't match
*/
static bool DetectRunTxInspectRule(ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
Flow *f,
const uint8_t flow_flags, // direction, EOF, etc
void *alstate,
DetectTransaction *tx,
const Signature *s,
uint32_t *stored_flags,
RuleMatchCandidateTx *can,
DetectRunScratchpad *scratch)
{
const int direction = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
uint32_t inspect_flags = stored_flags ? *stored_flags : 0;
int total_matches = 0;
int file_no_match = 0;
bool retval = false;
bool mpm_before_progress = false; // is mpm engine before progress?
bool mpm_in_progress = false; // is mpm engine in a buffer we will revisit?
TRACE_SID_TXS(s->id, tx, "starting %s", direction ? "toclient" : "toserver");
/* for a new inspection we inspect pkt header and packet matches */
if (likely(stored_flags == NULL)) {
TRACE_SID_TXS(s->id, tx, "first inspect, run packet matches");
if (DetectRunInspectRuleHeader(p, f, s, s->flags, s->proto.flags) == 0) {
TRACE_SID_TXS(s->id, tx, "DetectRunInspectRuleHeader() no match");
return false;
}
if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, f, s) == 0) {
TRACE_SID_TXS(s->id, tx, "DetectRunInspectRulePacketMatches no match");
return false;
}
/* stream mpm and negated mpm sigs can end up here with wrong proto */
if (!(f->alproto == s->alproto || s->alproto == ALPROTO_UNKNOWN)) {
TRACE_SID_TXS(s->id, tx, "alproto mismatch");
return false;
}
}
const DetectEngineAppInspectionEngine *engine = s->app_inspect;
while (engine != NULL) { // TODO could be do {} while as s->app_inspect cannot be null
TRACE_SID_TXS(s->id, tx, "engine %p inspect_flags %x", engine, inspect_flags);
if (!(inspect_flags & BIT_U32(engine->id)) &&
direction == engine->dir)
{
/* engines are sorted per progress, except that the one with
* mpm/prefilter enabled is first */
if (tx->tx_progress < engine->progress) {
SCLogDebug("tx progress %d < engine progress %d",
tx->tx_progress, engine->progress);
break;
}
if (engine->mpm) {
if (tx->tx_progress > engine->progress) {
mpm_before_progress = true;
} else if (tx->tx_progress == engine->progress) {
mpm_in_progress = true;
}
}
/* run callback: but bypass stream callback if we can */
int match;
if (unlikely(engine->stream && can->stream_stored)) {
match = can->stream_result;
TRACE_SID_TXS(s->id, tx, "stream skipped, stored result %d used instead", match);
/* special case: file_data on 'alert tcp' will have engines
* in the list that are not for us. Bypass with assume match */
} else if (unlikely(engine->alproto != 0 && engine->alproto != f->alproto)) {
inspect_flags |= BIT_U32(engine->id);
engine = engine->next;
total_matches++;
continue;
} else {
KEYWORD_PROFILING_SET_LIST(det_ctx, engine->sm_list);
match = engine->Callback(tv, de_ctx, det_ctx,
s, engine->smd, f, flow_flags, alstate, tx->tx_ptr, tx->tx_id);
TRACE_SID_TXS(s->id, tx, "engine %p match %d", engine, match);
if (engine->stream) {
can->stream_stored = true;
can->stream_result = match;
TRACE_SID_TXS(s->id, tx, "stream ran, store result %d for next tx (if any)", match);
}
}
if (match == DETECT_ENGINE_INSPECT_SIG_MATCH) {
inspect_flags |= BIT_U32(engine->id);
engine = engine->next;
total_matches++;
continue;
} else if (match == DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES) {
/* if the file engine matched, but indicated more
* files are still in progress, we don't set inspect
* flags as these would end inspection for this tx */
engine = engine->next;
total_matches++;
continue;
} else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
} else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
file_no_match = 1;
}
/* implied DETECT_ENGINE_INSPECT_SIG_NO_MATCH */
if (engine->mpm && mpm_before_progress) {
inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
inspect_flags |= BIT_U32(engine->id);
}
break;
}
engine = engine->next;
}
TRACE_SID_TXS(s->id, tx, "inspect_flags %x, total_matches %u, engine %p",
inspect_flags, total_matches, engine);
if (engine == NULL && total_matches) {
inspect_flags |= DE_STATE_FLAG_FULL_INSPECT;
TRACE_SID_TXS(s->id, tx, "MATCH");
retval = true;
}
if (stored_flags) {
*stored_flags = inspect_flags;
TRACE_SID_TXS(s->id, tx, "continue inspect flags %08x", inspect_flags);
} else {
// store... or? If tx is done we might not want to come back to this tx
// also... if mpmid tracking is enabled, we won't do a sig again for this tx...
TRACE_SID_TXS(s->id, tx, "start inspect flags %08x", inspect_flags);
if (inspect_flags & DE_STATE_FLAG_SIG_CANT_MATCH) {
if (file_no_match) {
/* if we have a mismatch on a file sig, we need to keep state.
* We may get another file on the same tx (for http and smtp
* at least), so for a new file we need to re-eval the sig.
* Thoughts / TODO:
* - not for some protos that have 1 file per tx (e.g. nfs)
* - maybe we only need this for file sigs that mix with
* other matches? E.g. 'POST + filename', is different than
* just 'filename'.
*/
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
} else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) && mpm_before_progress) {
TRACE_SID_TXS(s->id, tx, "no need to store match sig, "
"mpm won't trigger for it anymore");
if (inspect_flags & DE_STATE_FLAG_FILE_INSPECT) {
TRACE_SID_TXS(s->id, tx, "except that for new files, "
"we may have to revisit anyway");
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
} else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) == 0 && mpm_in_progress) {
TRACE_SID_TXS(s->id, tx, "no need to store no-match sig, "
"mpm will revisit it");
} else {
TRACE_SID_TXS(s->id, tx, "storing state: flags %08x", inspect_flags);
DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
inspect_flags, flow_flags, file_no_match);
}
}
return retval;
}
/** \internal
* \brief get a DetectTransaction object
* \retval struct filled with relevant info or all nulls/0s
*/
static DetectTransaction GetTx(const uint8_t ipproto, const AppProto alproto,
void *alstate, const uint64_t tx_id, const int tx_end_state,
const uint8_t flow_flags)
{
void *tx_ptr = AppLayerParserGetTx(ipproto, alproto, alstate, tx_id);
if (tx_ptr == NULL) {
DetectTransaction no_tx = { NULL, 0, NULL, 0, 0, 0, 0, 0, };
return no_tx;
}
const uint64_t detect_flags = AppLayerParserGetTxDetectFlags(ipproto, alproto, tx_ptr, flow_flags);
if (detect_flags & APP_LAYER_TX_INSPECTED_FLAG) {
SCLogDebug("%"PRIu64" tx already fully inspected for %s. Flags %016"PRIx64,
tx_id, flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
detect_flags);
DetectTransaction no_tx = { NULL, 0, NULL, 0, 0, 0, 0, 0, };
return no_tx;
}
const int tx_progress = AppLayerParserGetStateProgress(ipproto, alproto, tx_ptr, flow_flags);
const int dir_int = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
DetectEngineState *tx_de_state = AppLayerParserGetTxDetectState(ipproto, alproto, tx_ptr);
DetectEngineStateDirection *tx_dir_state = tx_de_state ? &tx_de_state->dir_state[dir_int] : NULL;
uint64_t prefilter_flags = detect_flags & APP_LAYER_TX_PREFILTER_MASK;
DetectTransaction tx = {
.tx_ptr = tx_ptr,
.tx_id = tx_id,
.de_state = tx_dir_state,
.detect_flags = detect_flags,
.prefilter_flags = prefilter_flags,
.prefilter_flags_orig = prefilter_flags,
.tx_progress = tx_progress,
.tx_end_state = tx_end_state,
};
return tx;
}
static void DetectRunTx(ThreadVars *tv,
DetectEngineCtx *de_ctx,
DetectEngineThreadCtx *det_ctx,
Packet *p,
Flow *f,
DetectRunScratchpad *scratch)
{
const uint8_t flow_flags = scratch->flow_flags;
const SigGroupHead * const sgh = scratch->sgh;
void * const alstate = f->alstate;
const uint8_t ipproto = f->proto;
const AppProto alproto = f->alproto;
const uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate);
uint64_t tx_id = AppLayerParserGetTransactionInspectId(f->alparser, flow_flags);
const int tx_end_state = AppLayerParserGetStateProgressCompletionStatus(alproto, flow_flags);
for ( ; tx_id < total_txs; tx_id++) {
DetectTransaction tx = GetTx(ipproto, alproto,
alstate, tx_id, tx_end_state, flow_flags);
if (tx.tx_ptr == NULL) {
SCLogDebug("%p/%"PRIu64" no transaction to inspect",
tx.tx_ptr, tx_id);
continue;
}
uint32_t array_idx = 0;
uint32_t total_rules = det_ctx->match_array_cnt;
total_rules += (tx.de_state ? tx.de_state->cnt : 0);
/* run prefilter engines and merge results into a candidates array */
if (sgh->tx_engines) {
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_TX);
DetectRunPrefilterTx(det_ctx, sgh, p, ipproto, flow_flags, alproto,
alstate, &tx);
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_PF_TX);
SCLogDebug("%p/%"PRIu64" rules added from prefilter: %u candidates",
tx.tx_ptr, tx_id, det_ctx->pmq.rule_id_array_cnt);
total_rules += det_ctx->pmq.rule_id_array_cnt;
if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
}
for (uint32_t i = 0; i < det_ctx->pmq.rule_id_array_cnt; i++) {
const Signature *s = de_ctx->sig_array[det_ctx->pmq.rule_id_array[i]];
const SigIntId id = s->num;
det_ctx->tx_candidates[array_idx].s = s;
det_ctx->tx_candidates[array_idx].id = id;
det_ctx->tx_candidates[array_idx].flags = NULL;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
}
} else {
if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
}
}
/* merge 'state' rules from the regular prefilter */
uint32_t x = array_idx;
for (uint32_t i = 0; i < det_ctx->match_array_cnt; i++) {
const Signature *s = det_ctx->match_array[i];
if (s->flags & SIG_FLAG_STATE_MATCH) {
const SigIntId id = s->num;
det_ctx->tx_candidates[array_idx].s = s;
det_ctx->tx_candidates[array_idx].id = id;
det_ctx->tx_candidates[array_idx].flags = NULL;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
SCLogDebug("%p/%"PRIu64" rule %u (%u) added from 'match' list",
tx.tx_ptr, tx_id, s->id, id);
}
}
SCLogDebug("%p/%"PRIu64" rules added from 'match' list: %u",
tx.tx_ptr, tx_id, array_idx - x); (void)x;
/* merge stored state into results */
if (tx.de_state != NULL) {
const uint32_t old = array_idx;
/* if tx.de_state->flags has 'new file' set and sig below has
* 'file inspected' flag, reset the file part of the state */
const bool have_new_file = (tx.de_state->flags & DETECT_ENGINE_STATE_FLAG_FILE_NEW);
if (have_new_file) {
SCLogDebug("%p/%"PRIu64" destate: need to consider new file",
tx.tx_ptr, tx_id);
tx.de_state->flags &= ~DETECT_ENGINE_STATE_FLAG_FILE_NEW;
}
SigIntId state_cnt = 0;
DeStateStore *tx_store = tx.de_state->head;
for (; tx_store != NULL; tx_store = tx_store->next) {
SCLogDebug("tx_store %p", tx_store);
SigIntId store_cnt = 0;
for (store_cnt = 0;
store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < tx.de_state->cnt;
store_cnt++, state_cnt++)
{
DeStateStoreItem *item = &tx_store->store[store_cnt];
SCLogDebug("rule id %u, inspect_flags %u", item->sid, item->flags);
if (have_new_file && (item->flags & DE_STATE_FLAG_FILE_INSPECT)) {
/* remove part of the state. File inspect engine will now
* be able to run again */
item->flags &= ~(DE_STATE_FLAG_SIG_CANT_MATCH|DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_FILE_INSPECT);
SCLogDebug("rule id %u, post file reset inspect_flags %u", item->sid, item->flags);
}
det_ctx->tx_candidates[array_idx].s = de_ctx->sig_array[item->sid];
det_ctx->tx_candidates[array_idx].id = item->sid;
det_ctx->tx_candidates[array_idx].flags = &item->flags;
det_ctx->tx_candidates[array_idx].stream_reset = 0;
array_idx++;
}
}
if (old && old != array_idx) {
qsort(det_ctx->tx_candidates, array_idx, sizeof(RuleMatchCandidateTx),
DetectRunTxSortHelper);
SCLogDebug("%p/%"PRIu64" rules added from 'continue' list: %u",
tx.tx_ptr, tx_id, array_idx - old);
}
}
det_ctx->tx_id = tx_id;
det_ctx->tx_id_set = 1;
det_ctx->p = p;
/* run rules: inspect the match candidates */
for (uint32_t i = 0; i < array_idx; i++) {
RuleMatchCandidateTx *can = &det_ctx->tx_candidates[i];
const Signature *s = det_ctx->tx_candidates[i].s;
uint32_t *inspect_flags = det_ctx->tx_candidates[i].flags;
/* deduplicate: rules_array is sorted, but not deduplicated:
* both mpm and stored state could give us the same sid.
* As they are back to back in that case we can check for it
* here. We select the stored state one. */
if ((i + 1) < array_idx) {
if (det_ctx->tx_candidates[i].s == det_ctx->tx_candidates[i+1].s) {
if (det_ctx->tx_candidates[i].flags != NULL) {
i++;
SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
} else if (det_ctx->tx_candidates[i+1].flags != NULL) {
SCLogDebug("%p/%"PRIu64" inspecting SKIP CURRENT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
continue;
} else {
// if it's all the same, inspect the current one and skip next.
i++;
SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
}
}
}
SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x",
tx.tx_ptr, tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
if (inspect_flags) {
if (*inspect_flags & (DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_SIG_CANT_MATCH)) {
SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x ALREADY COMPLETE",
tx.tx_ptr, tx_id, s->id, s->num, *inspect_flags);
continue;
}
}
if (inspect_flags) {
/* continue previous inspection */
SCLogDebug("%p/%"PRIu64" Continueing sid %u", tx.tx_ptr, tx_id, s->id);
} else {
/* start new inspection */
SCLogDebug("%p/%"PRIu64" Start sid %u", tx.tx_ptr, tx_id, s->id);
}
/* call individual rule inspection */
RULE_PROFILING_START(p);
const int r = DetectRunTxInspectRule(tv, de_ctx, det_ctx, p, f, flow_flags,
alstate, &tx, s, inspect_flags, can, scratch);
if (r == 1) {
/* match */
DetectRunPostMatch(tv, det_ctx, p, s);
uint8_t alert_flags = (PACKET_ALERT_FLAG_STATE_MATCH|PACKET_ALERT_FLAG_TX);
if (s->action & ACTION_DROP)
alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
SCLogDebug("%p/%"PRIu64" sig %u (%u) matched", tx.tx_ptr, tx_id, s->id, s->num);
if (!(s->flags & SIG_FLAG_NOALERT)) {
PacketAlertAppend(det_ctx, s, p, tx_id, alert_flags);
} else {
DetectSignatureApplyActions(p, s, alert_flags);
}
}
DetectVarProcessList(det_ctx, p->flow, p);
RULE_PROFILING_END(det_ctx, s, r, p);
}
det_ctx->tx_id = 0;
det_ctx->tx_id_set = 0;
det_ctx->p = NULL;
/* see if we have any updated state to store in the tx */
uint64_t new_detect_flags = 0;
/* this side of the tx is done */
if (tx.tx_progress >= tx.tx_end_state) {
new_detect_flags |= APP_LAYER_TX_INSPECTED_FLAG;
SCLogDebug("%p/%"PRIu64" tx is done for direction %s. Flag %016"PRIx64,
tx.tx_ptr, tx_id,
flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
new_detect_flags);
}
if (tx.prefilter_flags != tx.prefilter_flags_orig) {
new_detect_flags |= tx.prefilter_flags;
SCLogDebug("%p/%"PRIu64" updated prefilter flags %016"PRIx64" "
"(was: %016"PRIx64") for direction %s. Flag %016"PRIx64,
tx.tx_ptr, tx_id, tx.prefilter_flags, tx.prefilter_flags_orig,
flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
new_detect_flags);
}
if (new_detect_flags != 0 &&
(new_detect_flags | tx.detect_flags) != tx.detect_flags)
{
new_detect_flags |= tx.detect_flags;
SCLogDebug("%p/%"PRIu64" Storing new flags %016"PRIx64" (was %016"PRIx64")",
tx.tx_ptr, tx_id, new_detect_flags, tx.detect_flags);
AppLayerParserSetTxDetectFlags(ipproto, alproto, tx.tx_ptr,
flow_flags, new_detect_flags);
}
}
}
/** \brief Apply action(s) and Set 'drop' sig info,
* if applicable */
void DetectSignatureApplyActions(Packet *p,
const Signature *s, const uint8_t alert_flags)
{
PACKET_UPDATE_ACTION(p, s->action);
if (s->action & ACTION_DROP) {
if (p->alerts.drop.action == 0) {
p->alerts.drop.num = s->num;
p->alerts.drop.action = s->action;
p->alerts.drop.s = (Signature *)s;
}
} else if (s->action & ACTION_PASS) {
/* if an stream/app-layer match we enforce the pass for the flow */
if ((p->flow != NULL) &&
(alert_flags & (PACKET_ALERT_FLAG_STATE_MATCH|PACKET_ALERT_FLAG_STREAM_MATCH)))
{
FlowSetNoPacketInspectionFlag(p->flow);
}
}
}
static DetectEngineThreadCtx *GetTenantById(HashTable *h, uint32_t id)
{
/* technically we need to pass a DetectEngineThreadCtx struct with the
* tentant_id member. But as that member is the first in the struct, we
* can use the id directly. */
return HashTableLookup(h, &id, 0);
}
static void DetectFlow(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
/* No need to perform any detection on this packet, if the the given flag is set.*/
if ((p->flags & PKT_NOPACKET_INSPECTION) ||
(PACKET_TEST_ACTION(p, ACTION_DROP)))
{
/* hack: if we are in pass the entire flow mode, we need to still
* update the inspect_id forward. So test for the condition here,
* and call the update code if necessary. */
const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION));
const AppProto alproto = FlowGetAppProtocol(p->flow);
if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) {
uint8_t flags;
if (p->flowflags & FLOW_PKT_TOSERVER) {
flags = STREAM_TOSERVER;
} else {
flags = STREAM_TOCLIENT;
}
flags = FlowGetDisruptionFlags(p->flow, flags);
DeStateUpdateInspectTransactionId(p->flow, flags, true);
}
return;
}
/* see if the packet matches one or more of the sigs */
(void)DetectRun(tv, de_ctx, det_ctx, p);
}
static void DetectNoFlow(ThreadVars *tv,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
/* No need to perform any detection on this packet, if the the given flag is set.*/
if ((p->flags & PKT_NOPACKET_INSPECTION) ||
(PACKET_TEST_ACTION(p, ACTION_DROP)))
{
return;
}
/* see if the packet matches one or more of the sigs */
DetectRun(tv, de_ctx, det_ctx, p);
return;
}
/** \brief Detection engine thread wrapper.
* \param tv thread vars
* \param p packet to inspect
* \param data thread specific data
* \param pq packet queue
* \retval TM_ECODE_FAILED error
* \retval TM_ECODE_OK ok
*/
TmEcode Detect(ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
DEBUG_VALIDATE_PACKET(p);
DetectEngineCtx *de_ctx = NULL;
DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
if (det_ctx == NULL) {
printf("ERROR: Detect has no thread ctx\n");
goto error;
}
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("Detect Engine using new det_ctx - %p",
det_ctx);
}
/* if in MT mode _and_ we have tenants registered, use
* MT logic. */
if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL)
{
uint32_t tenant_id = p->tenant_id;
if (tenant_id == 0)
tenant_id = det_ctx->TenantGetId(det_ctx, p);
if (tenant_id > 0 && tenant_id < det_ctx->mt_det_ctxs_cnt) {
p->tenant_id = tenant_id;
det_ctx = GetTenantById(det_ctx->mt_det_ctxs_hash, tenant_id);
if (det_ctx == NULL)
return TM_ECODE_OK;
de_ctx = det_ctx->de_ctx;
if (de_ctx == NULL)
return TM_ECODE_OK;
if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
(void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
SCLogDebug("MT de_ctx %p det_ctx %p (tenant %u)", de_ctx, det_ctx, tenant_id);
}
} else {
/* use default if no tenants are registered for this packet */
de_ctx = det_ctx->de_ctx;
}
} else {
de_ctx = det_ctx->de_ctx;
}
if (p->flow) {
DetectFlow(tv, de_ctx, det_ctx, p);
} else {
DetectNoFlow(tv, de_ctx, det_ctx, p);
}
return TM_ECODE_OK;
error:
return TM_ECODE_FAILED;
}
/** \brief disable file features we don't need
* Called if we have no detection engine.
*/
void DisableDetectFlowFileFlags(Flow *f)
{
DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOSERVER);
DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOCLIENT);
}
#ifdef UNITTESTS
/**
* \brief wrapper for old tests
*/
void SigMatchSignatures(ThreadVars *th_v,
DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
Packet *p)
{
DetectRun(th_v, de_ctx, det_ctx, p);
}
#endif
/*
* TESTS
*/
#ifdef UNITTESTS
#include "tests/detect.c"
#endif
| ./CrossVul/dataset_final_sorted/CWE-693/c/bad_616_0 |
crossvul-cpp_data_good_1298_0 | /*
* pkcs15-prkey.c: PKCS #15 private key 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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#ifdef ENABLE_OPENSSL
#include <openssl/opensslv.h>
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#endif
#endif
#endif
#include "internal.h"
#include "asn1.h"
#include "pkcs15.h"
#include "common/compat_strlcpy.h"
#include "aux-data.h"
/*
* in src/libopensc/types.h SC_MAX_SUPPORTED_ALGORITHMS defined as 8
*/
#define C_ASN1_SUPPORTED_ALGORITHMS_SIZE (SC_MAX_SUPPORTED_ALGORITHMS + 1)
static const struct sc_asn1_entry c_asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE] = {
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_COM_KEY_ATTR_SIZE 7
static const struct sc_asn1_entry c_asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE] = {
{ "iD", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL },
{ "usage", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, 0, NULL, NULL },
{ "native", SC_ASN1_BOOLEAN, SC_ASN1_TAG_BOOLEAN, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessFlags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "keyReference",SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
/* Absent in PKCS#15-v1.1 but present in ISO 7816-15(2004-01-15)*/
{ "algReference", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_COM_PRKEY_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE] = {
{ "subjectName", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS,
SC_ASN1_EMPTY_ALLOWED | SC_ASN1_ALLOC | SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_RSAKEY_ATTR_SIZE 4
static const struct sc_asn1_entry c_asn1_rsakey_attr[] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_EMPTY_ALLOWED, NULL, NULL },
{ "modulusLength", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "keyInfo", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_RSA_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE] = {
{ "privateRSAKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_GOSTR3410KEY_ATTR_SIZE 5
static const struct sc_asn1_entry c_asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "params_r3410", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "params_r3411", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "params_28147", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_GOSTR3410_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE] = {
{ "privateGOSTR3410KeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_I_P_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE] = {
{ "path", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_VALUE_ATTR_SIZE 3
static const struct sc_asn1_entry c_asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE] = {
{ "path", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "pathProtected",SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL},
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE] = {
{ "value", SC_ASN1_CHOICE, 0, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_DSA_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE] = {
{ "privateDSAKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
/*
* The element fieldSize is a proprietary extension to ISO 7816-15, providing to the middleware
* the size of the underlying ECC field. This value is required for determine a proper size for
* buffer allocations. The field follows the definition for modulusLength in RSA keys
*/
#define C_ASN1_ECCKEY_ATTR 4
static const struct sc_asn1_entry c_asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_EMPTY_ALLOWED, NULL, NULL },
{ "fieldSize", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "keyInfo", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_ECC_ATTR 2
static const struct sc_asn1_entry c_asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR] = {
{ "privateECCKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRKEY_SIZE 5
static const struct sc_asn1_entry c_asn1_prkey[C_ASN1_PRKEY_SIZE] = {
{ "privateRSAKey", SC_ASN1_PKCS15_OBJECT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateECCKey", SC_ASN1_PKCS15_OBJECT, 0 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateDSAKey", SC_ASN1_PKCS15_OBJECT, 2 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateGOSTR3410Key", SC_ASN1_PKCS15_OBJECT, 4 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 ** buf, size_t *buflen)
{
sc_context_t *ctx = p15card->card->ctx;
struct sc_pkcs15_prkey_info info;
int r, i, gostr3410_params[3];
struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
size_t usage_len = sizeof(info.usage);
size_t af_len = sizeof(info.access_flags);
struct sc_asn1_entry asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_rsakey_attr[C_ASN1_RSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE];
struct sc_asn1_entry asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE];
struct sc_asn1_entry asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR];
struct sc_asn1_entry asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR];
struct sc_asn1_entry asn1_prkey[C_ASN1_PRKEY_SIZE];
struct sc_asn1_entry asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE];
struct sc_asn1_pkcs15_object rsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_rsa_attr};
struct sc_asn1_pkcs15_object dsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_dsa_attr};
struct sc_asn1_pkcs15_object gostr3410_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_gostr3410_attr};
struct sc_asn1_pkcs15_object ecc_prkey_obj = { obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_ecc_attr };
sc_copy_asn1_entry(c_asn1_prkey, asn1_prkey);
sc_copy_asn1_entry(c_asn1_supported_algorithms, asn1_supported_algorithms);
sc_copy_asn1_entry(c_asn1_prk_rsa_attr, asn1_prk_rsa_attr);
sc_copy_asn1_entry(c_asn1_rsakey_attr, asn1_rsakey_attr);
sc_copy_asn1_entry(c_asn1_prk_dsa_attr, asn1_prk_dsa_attr);
sc_copy_asn1_entry(c_asn1_dsakey_attr, asn1_dsakey_attr);
sc_copy_asn1_entry(c_asn1_dsakey_value_attr, asn1_dsakey_value_attr);
sc_copy_asn1_entry(c_asn1_dsakey_i_p_attr, asn1_dsakey_i_p_attr);
sc_copy_asn1_entry(c_asn1_prk_gostr3410_attr, asn1_prk_gostr3410_attr);
sc_copy_asn1_entry(c_asn1_gostr3410key_attr, asn1_gostr3410key_attr);
sc_copy_asn1_entry(c_asn1_prk_ecc_attr, asn1_prk_ecc_attr);
sc_copy_asn1_entry(c_asn1_ecckey_attr, asn1_ecckey_attr);
sc_copy_asn1_entry(c_asn1_com_prkey_attr, asn1_com_prkey_attr);
sc_copy_asn1_entry(c_asn1_com_key_attr, asn1_com_key_attr);
sc_format_asn1_entry(asn1_prkey + 0, &rsa_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 1, &ecc_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 2, &dsa_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 3, &gostr3410_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prk_rsa_attr + 0, asn1_rsakey_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_dsa_attr + 0, asn1_dsakey_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_gostr3410_attr + 0, asn1_gostr3410key_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_ecc_attr + 0, asn1_ecckey_attr, NULL, 0);
sc_format_asn1_entry(asn1_rsakey_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_rsakey_attr + 1, &info.modulus_length, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_attr + 0, asn1_dsakey_value_attr, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_value_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_value_attr + 1, asn1_dsakey_i_p_attr, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_i_p_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 1, &gostr3410_params[0], NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 2, &gostr3410_params[1], NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 3, &gostr3410_params[2], NULL, 0);
sc_format_asn1_entry(asn1_ecckey_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_ecckey_attr + 1, &info.field_length, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 0, &info.id, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 1, &info.usage, &usage_len, 0);
sc_format_asn1_entry(asn1_com_key_attr + 2, &info.native, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 3, &info.access_flags, &af_len, 0);
sc_format_asn1_entry(asn1_com_key_attr + 4, &info.key_reference, NULL, 0);
for (i=0; i<SC_MAX_SUPPORTED_ALGORITHMS && (asn1_supported_algorithms + i)->name; i++)
sc_format_asn1_entry(asn1_supported_algorithms + i, &info.algo_refs[i], NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 5, asn1_supported_algorithms, NULL, 0);
sc_format_asn1_entry(asn1_com_prkey_attr + 0, &info.subject.value, &info.subject.len, 0);
/* Fill in defaults */
memset(&info, 0, sizeof(info));
info.key_reference = -1;
info.native = 1;
memset(gostr3410_params, 0, sizeof(gostr3410_params));
r = sc_asn1_decode_choice(ctx, asn1_prkey, *buf, *buflen, buf, buflen);
if (r < 0) {
/* This might have allocated something. If so, clear it now */
free(info.subject.value);
}
if (r == SC_ERROR_ASN1_END_OF_CONTENTS)
return r;
LOG_TEST_RET(ctx, r, "PrKey DF ASN.1 decoding failed");
if (asn1_prkey[0].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_RSA;
}
else if (asn1_prkey[1].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_EC;
}
else if (asn1_prkey[2].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_DSA;
/* If the value was indirect-protected, mark the path */
if (asn1_dsakey_i_p_attr[0].flags & SC_ASN1_PRESENT)
info.path.type = SC_PATH_TYPE_PATH_PROT;
}
else if (asn1_prkey[3].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_GOSTR3410;
assert(info.modulus_length == 0);
info.modulus_length = SC_PKCS15_GOSTR3410_KEYSIZE;
assert(info.params.len == 0);
info.params.len = sizeof(struct sc_pkcs15_keyinfo_gostparams);
info.params.data = malloc(info.params.len);
if (info.params.data == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
assert(sizeof(*keyinfo_gostparams) == info.params.len);
keyinfo_gostparams = info.params.data;
keyinfo_gostparams->gostr3410 = gostr3410_params[0];
keyinfo_gostparams->gostr3411 = gostr3410_params[1];
keyinfo_gostparams->gost28147 = gostr3410_params[2];
}
else {
sc_log(ctx, "Neither RSA or DSA or GOSTR3410 or ECC key in PrKDF entry.");
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ASN1_OBJECT);
}
if (!p15card->app || !p15card->app->ddo.aid.len) {
r = sc_pkcs15_make_absolute_path(&p15card->file_app->path, &info.path);
if (r < 0) {
sc_pkcs15_free_key_params(&info.params);
return r;
}
}
else {
info.path.aid = p15card->app->ddo.aid;
}
sc_log(ctx, "PrivKey path '%s'", sc_print_path(&info.path));
/* OpenSC 0.11.4 and older encoded "keyReference" as a negative value.
* Fixed in 0.11.5 we need to add a hack, so old cards continue to work. */
if (info.key_reference < -1)
info.key_reference += 256;
/* Check the auth_id - if not present, try and find it in access rules */
if ((obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) && (obj->auth_id.len == 0)) {
sc_log(ctx, "Private key %s has no auth ID - checking AccessControlRules",
sc_pkcs15_print_id(&info.id));
/* Search in the access_rules for an appropriate auth ID */
for (i = 0; i < SC_PKCS15_MAX_ACCESS_RULES; i++) {
/* If access_mode is one of the private key usage modes */
if (obj->access_rules[i].access_mode &
(SC_PKCS15_ACCESS_RULE_MODE_EXECUTE |
SC_PKCS15_ACCESS_RULE_MODE_PSO_CDS |
SC_PKCS15_ACCESS_RULE_MODE_PSO_DECRYPT |
SC_PKCS15_ACCESS_RULE_MODE_INT_AUTH)) {
if (obj->access_rules[i].auth_id.len != 0) {
/* Found an auth ID to use for private key access */
obj->auth_id = obj->access_rules[i].auth_id;
sc_log(ctx, "Auth ID found - %s",
sc_pkcs15_print_id(&obj->auth_id));
break;
}
}
}
/* No auth ID found */
if (i == SC_PKCS15_MAX_ACCESS_RULES)
sc_log(ctx, "Warning: No auth ID found");
}
obj->data = malloc(sizeof(info));
if (obj->data == NULL) {
sc_pkcs15_free_key_params(&info.params);
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
}
memcpy(obj->data, &info, sizeof(info));
sc_log(ctx, "Key Subject %s", sc_dump_hex(info.subject.value, info.subject.len));
sc_log(ctx, "Key path %s", sc_print_path(&info.path));
return 0;
}
int sc_pkcs15_encode_prkdf_entry(sc_context_t *ctx, const struct sc_pkcs15_object *obj,
u8 **buf, size_t *buflen)
{
struct sc_asn1_entry asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_rsakey_attr[C_ASN1_RSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE];
struct sc_asn1_entry asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE];
struct sc_asn1_entry asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR];
struct sc_asn1_entry asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR];
struct sc_asn1_entry asn1_prkey[C_ASN1_PRKEY_SIZE];
struct sc_asn1_entry asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE];
struct sc_asn1_pkcs15_object rsa_prkey_obj = {
(struct sc_pkcs15_object *) obj, asn1_com_key_attr,
asn1_com_prkey_attr, asn1_prk_rsa_attr
};
struct sc_asn1_pkcs15_object dsa_prkey_obj = {
(struct sc_pkcs15_object *) obj, asn1_com_key_attr,
asn1_com_prkey_attr, asn1_prk_dsa_attr
};
struct sc_asn1_pkcs15_object gostr3410_prkey_obj = {
(struct sc_pkcs15_object *) obj,
asn1_com_key_attr, asn1_com_prkey_attr,
asn1_prk_gostr3410_attr
};
struct sc_asn1_pkcs15_object ecc_prkey_obj = {
(struct sc_pkcs15_object *) obj,
asn1_com_key_attr, asn1_com_prkey_attr,
asn1_prk_ecc_attr
};
struct sc_pkcs15_prkey_info *prkey = (struct sc_pkcs15_prkey_info *) obj->data;
struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
int r, i;
size_t af_len, usage_len;
sc_copy_asn1_entry(c_asn1_prkey, asn1_prkey);
sc_copy_asn1_entry(c_asn1_supported_algorithms, asn1_supported_algorithms);
sc_copy_asn1_entry(c_asn1_prk_rsa_attr, asn1_prk_rsa_attr);
sc_copy_asn1_entry(c_asn1_rsakey_attr, asn1_rsakey_attr);
sc_copy_asn1_entry(c_asn1_prk_dsa_attr, asn1_prk_dsa_attr);
sc_copy_asn1_entry(c_asn1_dsakey_attr, asn1_dsakey_attr);
sc_copy_asn1_entry(c_asn1_dsakey_value_attr, asn1_dsakey_value_attr);
sc_copy_asn1_entry(c_asn1_dsakey_i_p_attr, asn1_dsakey_i_p_attr);
sc_copy_asn1_entry(c_asn1_prk_gostr3410_attr, asn1_prk_gostr3410_attr);
sc_copy_asn1_entry(c_asn1_gostr3410key_attr, asn1_gostr3410key_attr);
sc_copy_asn1_entry(c_asn1_prk_ecc_attr, asn1_prk_ecc_attr);
sc_copy_asn1_entry(c_asn1_ecckey_attr, asn1_ecckey_attr);
sc_copy_asn1_entry(c_asn1_com_prkey_attr, asn1_com_prkey_attr);
sc_copy_asn1_entry(c_asn1_com_key_attr, asn1_com_key_attr);
switch (obj->type) {
case SC_PKCS15_TYPE_PRKEY_RSA:
sc_format_asn1_entry(asn1_prkey + 0, &rsa_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_rsa_attr + 0, asn1_rsakey_attr, NULL, 1);
sc_format_asn1_entry(asn1_rsakey_attr + 0, &prkey->path, NULL, 1);
sc_format_asn1_entry(asn1_rsakey_attr + 1, &prkey->modulus_length, NULL, 1);
break;
case SC_PKCS15_TYPE_PRKEY_EC:
sc_format_asn1_entry(asn1_prkey + 1, &ecc_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_ecc_attr + 0, asn1_ecckey_attr, NULL, 1);
sc_format_asn1_entry(asn1_ecckey_attr + 0, &prkey->path, NULL, 1);
sc_format_asn1_entry(asn1_ecckey_attr + 1, &prkey->field_length, NULL, 1);
break;
case SC_PKCS15_TYPE_PRKEY_DSA:
sc_format_asn1_entry(asn1_prkey + 2, &dsa_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_dsa_attr + 0, asn1_dsakey_value_attr, NULL, 1);
if (prkey->path.type != SC_PATH_TYPE_PATH_PROT) {
/* indirect: just add the path */
sc_format_asn1_entry(asn1_dsakey_value_attr + 0, &prkey->path, NULL, 1);
}
else {
/* indirect-protected */
sc_format_asn1_entry(asn1_dsakey_value_attr + 1, asn1_dsakey_i_p_attr, NULL, 1);
sc_format_asn1_entry(asn1_dsakey_i_p_attr + 0, &prkey->path, NULL, 1);
}
break;
case SC_PKCS15_TYPE_PRKEY_GOSTR3410:
sc_format_asn1_entry(asn1_prkey + 3, &gostr3410_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_gostr3410_attr + 0, asn1_gostr3410key_attr, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 0, &prkey->path, NULL, 1);
if (prkey->params.len == sizeof(*keyinfo_gostparams)) {
keyinfo_gostparams = prkey->params.data;
sc_format_asn1_entry(asn1_gostr3410key_attr + 1, &keyinfo_gostparams->gostr3410, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 2, &keyinfo_gostparams->gostr3411, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 3, &keyinfo_gostparams->gost28147, NULL, 1);
}
break;
default:
sc_log(ctx, "Invalid private key type: %X", obj->type);
LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
break;
}
sc_format_asn1_entry(asn1_com_key_attr + 0, &prkey->id, NULL, 1);
usage_len = sizeof(prkey->usage);
sc_format_asn1_entry(asn1_com_key_attr + 1, &prkey->usage, &usage_len, 1);
if (prkey->native == 0)
sc_format_asn1_entry(asn1_com_key_attr + 2, &prkey->native, NULL, 1);
if (prkey->access_flags) {
af_len = sizeof(prkey->access_flags);
sc_format_asn1_entry(asn1_com_key_attr + 3, &prkey->access_flags, &af_len, 1);
}
if (prkey->key_reference >= 0)
sc_format_asn1_entry(asn1_com_key_attr + 4, &prkey->key_reference, NULL, 1);
for (i=0; i<SC_MAX_SUPPORTED_ALGORITHMS && prkey->algo_refs[i]; i++) {
sc_log(ctx, "Encode algorithm(%i) %i", i, prkey->algo_refs[i]);
sc_format_asn1_entry(asn1_supported_algorithms + i, &prkey->algo_refs[i], NULL, 1);
}
sc_format_asn1_entry(asn1_com_key_attr + 5, asn1_supported_algorithms, NULL, prkey->algo_refs[0] != 0);
if (prkey->subject.value && prkey->subject.len)
sc_format_asn1_entry(asn1_com_prkey_attr + 0, prkey->subject.value, &prkey->subject.len, 1);
else
memset(asn1_com_prkey_attr, 0, sizeof(asn1_com_prkey_attr));
r = sc_asn1_encode(ctx, asn1_prkey, buf, buflen);
sc_log(ctx, "Key path %s", sc_print_path(&prkey->path));
return r;
}
int
sc_pkcs15_prkey_attrs_from_cert(struct sc_pkcs15_card *p15card, struct sc_pkcs15_object *cert_object,
struct sc_pkcs15_object **out_key_object)
{
struct sc_context *ctx = p15card->card->ctx;
#ifdef ENABLE_OPENSSL
struct sc_pkcs15_object *key_object = NULL;
struct sc_pkcs15_prkey_info *key_info = NULL;
X509 *x = NULL;
BIO *mem = NULL;
unsigned char *buff = NULL, *ptr = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (out_key_object)
*out_key_object = NULL;
rv = sc_pkcs15_find_prkey_by_id(p15card, &((struct sc_pkcs15_cert_info *)cert_object->data)->id, &key_object);
if (rv == SC_ERROR_OBJECT_NOT_FOUND)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_TEST_RET(ctx, rv, "Find private key error");
key_info = (struct sc_pkcs15_prkey_info *) key_object->data;
ERR_load_ERR_strings();
ERR_load_crypto_strings();
sc_log(ctx, "CertValue(%"SC_FORMAT_LEN_SIZE_T"u) %p",
cert_object->content.len, cert_object->content.value);
mem = BIO_new_mem_buf(cert_object->content.value, cert_object->content.len);
if (!mem)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "MEM buffer allocation error");
x = d2i_X509_bio(mem, NULL);
if (!x)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "x509 parse error");
buff = OPENSSL_malloc(i2d_X509(x,NULL) + EVP_MAX_MD_SIZE);
if (!buff)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "OpenSSL allocation error");
ptr = buff;
rv = i2d_X509_NAME(X509_get_subject_name(x), &ptr);
if (rv <= 0)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Get subject name error");
key_info->subject.value = malloc(rv);
if (!key_info->subject.value)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Subject allocation error");
memcpy(key_info->subject.value, buff, rv);
key_info->subject.len = rv;
strlcpy(key_object->label, cert_object->label, sizeof(key_object->label));
rv = 0;
if (x)
X509_free(x);
if (mem)
BIO_free(mem);
if (buff)
OPENSSL_free(buff);
ERR_clear_error();
ERR_free_strings();
if (out_key_object)
*out_key_object = key_object;
sc_log(ctx, "Subject %s", sc_dump_hex(key_info->subject.value, key_info->subject.len));
LOG_FUNC_RETURN(ctx, rv);
#else
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
#endif
}
void
sc_pkcs15_free_prkey(struct sc_pkcs15_prkey *key)
{
if (!key)
return;
switch (key->algorithm) {
case SC_ALGORITHM_RSA:
free(key->u.rsa.modulus.data);
free(key->u.rsa.exponent.data);
free(key->u.rsa.d.data);
free(key->u.rsa.p.data);
free(key->u.rsa.q.data);
free(key->u.rsa.iqmp.data);
free(key->u.rsa.dmp1.data);
free(key->u.rsa.dmq1.data);
break;
case SC_ALGORITHM_DSA:
free(key->u.dsa.pub.data);
free(key->u.dsa.p.data);
free(key->u.dsa.q.data);
free(key->u.dsa.g.data);
free(key->u.dsa.priv.data);
break;
case SC_ALGORITHM_GOSTR3410:
assert(key->u.gostr3410.d.data);
free(key->u.gostr3410.d.data);
break;
case SC_ALGORITHM_EC:
if (key->u.ec.params.der.value)
free(key->u.ec.params.der.value);
if (key->u.ec.params.named_curve)
free(key->u.ec.params.named_curve);
if (key->u.ec.privateD.data)
free(key->u.ec.privateD.data);
if (key->u.ec.ecpointQ.value)
free(key->u.ec.ecpointQ.value);
break;
}
}
void sc_pkcs15_free_prkey_info(sc_pkcs15_prkey_info_t *key)
{
if (key->subject.value)
free(key->subject.value);
sc_pkcs15_free_key_params(&key->params);
sc_aux_data_free(&key->aux_data);
free(key);
}
int
sc_pkcs15_convert_bignum(sc_pkcs15_bignum_t *dst, const void *src)
{
#ifdef ENABLE_OPENSSL
const BIGNUM *bn = (const BIGNUM *)src;
if (bn == 0)
return 0;
dst->len = BN_num_bytes(bn);
dst->data = malloc(dst->len);
if (!dst->data)
return 0;
BN_bn2bin(bn, dst->data);
return 1;
#else
return 0;
#endif
}
int
sc_pkcs15_convert_prkey(struct sc_pkcs15_prkey *pkcs15_key, void *evp_key)
{
#ifdef ENABLE_OPENSSL
EVP_PKEY *pk = (EVP_PKEY *)evp_key;
int pk_type;
pk_type = EVP_PKEY_base_id(pk);
switch (pk_type) {
case EVP_PKEY_RSA: {
struct sc_pkcs15_prkey_rsa *dst = &pkcs15_key->u.rsa;
RSA *src = EVP_PKEY_get1_RSA(pk);
const BIGNUM *src_n, *src_e, *src_d, *src_p, *src_q, *src_iqmp, *src_dmp1, *src_dmq1;
RSA_get0_key(src, &src_n, &src_e, &src_d);
RSA_get0_factors(src, &src_p, &src_q);
RSA_get0_crt_params(src, &src_dmp1, &src_dmq1, &src_iqmp);
pkcs15_key->algorithm = SC_ALGORITHM_RSA;
if (!sc_pkcs15_convert_bignum(&dst->modulus, src_n)
|| !sc_pkcs15_convert_bignum(&dst->exponent, src_e)
|| !sc_pkcs15_convert_bignum(&dst->d, src_d)
|| !sc_pkcs15_convert_bignum(&dst->p, src_p)
|| !sc_pkcs15_convert_bignum(&dst->q, src_q))
return SC_ERROR_NOT_SUPPORTED;
if (src_iqmp && src_dmp1 && src_dmq1) {
sc_pkcs15_convert_bignum(&dst->iqmp, src_iqmp);
sc_pkcs15_convert_bignum(&dst->dmp1, src_dmp1);
sc_pkcs15_convert_bignum(&dst->dmq1, src_dmq1);
}
RSA_free(src);
break;
}
case EVP_PKEY_DSA: {
struct sc_pkcs15_prkey_dsa *dst = &pkcs15_key->u.dsa;
DSA *src = EVP_PKEY_get1_DSA(pk);
const BIGNUM *src_pub_key, *src_p, *src_q, *src_g, *src_priv_key;
DSA_get0_key(src, &src_pub_key, &src_priv_key);
DSA_get0_pqg(src, &src_p, &src_q, &src_g);
pkcs15_key->algorithm = SC_ALGORITHM_DSA;
sc_pkcs15_convert_bignum(&dst->pub, src_pub_key);
sc_pkcs15_convert_bignum(&dst->p, src_p);
sc_pkcs15_convert_bignum(&dst->q, src_q);
sc_pkcs15_convert_bignum(&dst->g, src_g);
sc_pkcs15_convert_bignum(&dst->priv, src_priv_key);
DSA_free(src);
break;
}
#if OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_EC)
case NID_id_GostR3410_2001: {
struct sc_pkcs15_prkey_gostr3410 *dst = &pkcs15_key->u.gostr3410;
EC_KEY *src = EVP_PKEY_get0(pk);
assert(src);
pkcs15_key->algorithm = SC_ALGORITHM_GOSTR3410;
assert(EC_KEY_get0_private_key(src));
sc_pkcs15_convert_bignum(&dst->d, EC_KEY_get0_private_key(src));
break;
}
case EVP_PKEY_EC: {
struct sc_pkcs15_prkey_ec *dst = &pkcs15_key->u.ec;
EC_KEY *src = NULL;
const EC_GROUP *grp = NULL;
unsigned char buf[255];
size_t buflen = 255;
int nid;
src = EVP_PKEY_get0(pk);
assert(src);
assert(EC_KEY_get0_private_key(src));
assert(EC_KEY_get0_public_key(src));
pkcs15_key->algorithm = SC_ALGORITHM_EC;
if (!sc_pkcs15_convert_bignum(&dst->privateD, EC_KEY_get0_private_key(src)))
return SC_ERROR_INCOMPATIBLE_KEY;
grp = EC_KEY_get0_group(src);
if(grp == 0)
return SC_ERROR_INCOMPATIBLE_KEY;
/* get curve name */
nid = EC_GROUP_get_curve_name(grp);
if(nid != 0) {
const char *sn = OBJ_nid2sn(nid);
if (sn)
dst->params.named_curve = strdup(sn);
}
/* Decode EC_POINT from a octet string */
buflen = EC_POINT_point2oct(grp, (const EC_POINT *) EC_KEY_get0_public_key(src),
POINT_CONVERSION_UNCOMPRESSED, buf, buflen, NULL);
if (!buflen)
return SC_ERROR_INCOMPATIBLE_KEY;
/* copy the public key */
dst->ecpointQ.value = malloc(buflen);
if (!dst->ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(dst->ecpointQ.value, buf, buflen);
dst->ecpointQ.len = buflen;
/*
* In OpenSC the field_length is in bits. Not all curves are a mutiple of 8.
* EC_POINT_point2oct handles this and returns octstrings that can handle
* these curves. Get real field_length from OpenSSL.
*/
dst->params.field_length = EC_GROUP_get_degree(grp);
/* Octetstring may need leading zeros if BN is to short */
if (dst->privateD.len < (dst->params.field_length + 7) / 8) {
size_t d = (dst->params.field_length + 7) / 8 - dst->privateD.len;
dst->privateD.data = realloc(dst->privateD.data, dst->privateD.len + d);
if (!dst->privateD.data)
return SC_ERROR_OUT_OF_MEMORY;
memmove(dst->privateD.data + d, dst->privateD.data, dst->privateD.len);
memset(dst->privateD.data, 0, d);
dst->privateD.len += d;
}
break;
}
#endif /* OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_EC) */
default:
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
#else
return SC_ERROR_NOT_IMPLEMENTED;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-672/c/good_1298_0 |
crossvul-cpp_data_bad_1298_0 | /*
* pkcs15-prkey.c: PKCS #15 private key 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 <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#ifdef ENABLE_OPENSSL
#include <openssl/opensslv.h>
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
#ifndef OPENSSL_NO_EC
#include <openssl/ec.h>
#endif
#endif
#endif
#include "internal.h"
#include "asn1.h"
#include "pkcs15.h"
#include "common/compat_strlcpy.h"
#include "aux-data.h"
/*
* in src/libopensc/types.h SC_MAX_SUPPORTED_ALGORITHMS defined as 8
*/
#define C_ASN1_SUPPORTED_ALGORITHMS_SIZE (SC_MAX_SUPPORTED_ALGORITHMS + 1)
static const struct sc_asn1_entry c_asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE] = {
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "algorithmReference", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_COM_KEY_ATTR_SIZE 7
static const struct sc_asn1_entry c_asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE] = {
{ "iD", SC_ASN1_PKCS15_ID, SC_ASN1_TAG_OCTET_STRING, 0, NULL, NULL },
{ "usage", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, 0, NULL, NULL },
{ "native", SC_ASN1_BOOLEAN, SC_ASN1_TAG_BOOLEAN, SC_ASN1_OPTIONAL, NULL, NULL },
{ "accessFlags", SC_ASN1_BIT_FIELD, SC_ASN1_TAG_BIT_STRING, SC_ASN1_OPTIONAL, NULL, NULL },
{ "keyReference",SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
/* Absent in PKCS#15-v1.1 but present in ISO 7816-15(2004-01-15)*/
{ "algReference", SC_ASN1_STRUCT, SC_ASN1_CONS | SC_ASN1_CTX | 1, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_COM_PRKEY_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE] = {
{ "subjectName", SC_ASN1_OCTET_STRING, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS,
SC_ASN1_EMPTY_ALLOWED | SC_ASN1_ALLOC | SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_RSAKEY_ATTR_SIZE 4
static const struct sc_asn1_entry c_asn1_rsakey_attr[] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_EMPTY_ALLOWED, NULL, NULL },
{ "modulusLength", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "keyInfo", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_RSA_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE] = {
{ "privateRSAKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_GOSTR3410KEY_ATTR_SIZE 5
static const struct sc_asn1_entry c_asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "params_r3410", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, 0, NULL, NULL },
{ "params_r3411", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "params_28147", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_GOSTR3410_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE] = {
{ "privateGOSTR3410KeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_I_P_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE] = {
{ "path", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_VALUE_ATTR_SIZE 3
static const struct sc_asn1_entry c_asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE] = {
{ "path", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ "pathProtected",SC_ASN1_STRUCT, SC_ASN1_CTX | 1 | SC_ASN1_CONS, 0, NULL, NULL},
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_DSAKEY_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE] = {
{ "value", SC_ASN1_CHOICE, 0, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_DSA_ATTR_SIZE 2
static const struct sc_asn1_entry c_asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE] = {
{ "privateDSAKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
/*
* The element fieldSize is a proprietary extension to ISO 7816-15, providing to the middleware
* the size of the underlying ECC field. This value is required for determine a proper size for
* buffer allocations. The field follows the definition for modulusLength in RSA keys
*/
#define C_ASN1_ECCKEY_ATTR 4
static const struct sc_asn1_entry c_asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR] = {
{ "value", SC_ASN1_PATH, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_EMPTY_ALLOWED, NULL, NULL },
{ "fieldSize", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ "keyInfo", SC_ASN1_INTEGER, SC_ASN1_TAG_INTEGER, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRK_ECC_ATTR 2
static const struct sc_asn1_entry c_asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR] = {
{ "privateECCKeyAttributes", SC_ASN1_STRUCT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, 0, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
#define C_ASN1_PRKEY_SIZE 5
static const struct sc_asn1_entry c_asn1_prkey[C_ASN1_PRKEY_SIZE] = {
{ "privateRSAKey", SC_ASN1_PKCS15_OBJECT, SC_ASN1_TAG_SEQUENCE | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateECCKey", SC_ASN1_PKCS15_OBJECT, 0 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateDSAKey", SC_ASN1_PKCS15_OBJECT, 2 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ "privateGOSTR3410Key", SC_ASN1_PKCS15_OBJECT, 4 | SC_ASN1_CTX | SC_ASN1_CONS, SC_ASN1_OPTIONAL, NULL, NULL },
{ NULL, 0, 0, 0, NULL, NULL }
};
int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card,
struct sc_pkcs15_object *obj,
const u8 ** buf, size_t *buflen)
{
sc_context_t *ctx = p15card->card->ctx;
struct sc_pkcs15_prkey_info info;
int r, i, gostr3410_params[3];
struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
size_t usage_len = sizeof(info.usage);
size_t af_len = sizeof(info.access_flags);
struct sc_asn1_entry asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_rsakey_attr[C_ASN1_RSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE];
struct sc_asn1_entry asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE];
struct sc_asn1_entry asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR];
struct sc_asn1_entry asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR];
struct sc_asn1_entry asn1_prkey[C_ASN1_PRKEY_SIZE];
struct sc_asn1_entry asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE];
struct sc_asn1_pkcs15_object rsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_rsa_attr};
struct sc_asn1_pkcs15_object dsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_dsa_attr};
struct sc_asn1_pkcs15_object gostr3410_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_gostr3410_attr};
struct sc_asn1_pkcs15_object ecc_prkey_obj = { obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_ecc_attr };
sc_copy_asn1_entry(c_asn1_prkey, asn1_prkey);
sc_copy_asn1_entry(c_asn1_supported_algorithms, asn1_supported_algorithms);
sc_copy_asn1_entry(c_asn1_prk_rsa_attr, asn1_prk_rsa_attr);
sc_copy_asn1_entry(c_asn1_rsakey_attr, asn1_rsakey_attr);
sc_copy_asn1_entry(c_asn1_prk_dsa_attr, asn1_prk_dsa_attr);
sc_copy_asn1_entry(c_asn1_dsakey_attr, asn1_dsakey_attr);
sc_copy_asn1_entry(c_asn1_dsakey_value_attr, asn1_dsakey_value_attr);
sc_copy_asn1_entry(c_asn1_dsakey_i_p_attr, asn1_dsakey_i_p_attr);
sc_copy_asn1_entry(c_asn1_prk_gostr3410_attr, asn1_prk_gostr3410_attr);
sc_copy_asn1_entry(c_asn1_gostr3410key_attr, asn1_gostr3410key_attr);
sc_copy_asn1_entry(c_asn1_prk_ecc_attr, asn1_prk_ecc_attr);
sc_copy_asn1_entry(c_asn1_ecckey_attr, asn1_ecckey_attr);
sc_copy_asn1_entry(c_asn1_com_prkey_attr, asn1_com_prkey_attr);
sc_copy_asn1_entry(c_asn1_com_key_attr, asn1_com_key_attr);
sc_format_asn1_entry(asn1_prkey + 0, &rsa_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 1, &ecc_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 2, &dsa_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prkey + 3, &gostr3410_prkey_obj, NULL, 0);
sc_format_asn1_entry(asn1_prk_rsa_attr + 0, asn1_rsakey_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_dsa_attr + 0, asn1_dsakey_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_gostr3410_attr + 0, asn1_gostr3410key_attr, NULL, 0);
sc_format_asn1_entry(asn1_prk_ecc_attr + 0, asn1_ecckey_attr, NULL, 0);
sc_format_asn1_entry(asn1_rsakey_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_rsakey_attr + 1, &info.modulus_length, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_attr + 0, asn1_dsakey_value_attr, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_value_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_value_attr + 1, asn1_dsakey_i_p_attr, NULL, 0);
sc_format_asn1_entry(asn1_dsakey_i_p_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 1, &gostr3410_params[0], NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 2, &gostr3410_params[1], NULL, 0);
sc_format_asn1_entry(asn1_gostr3410key_attr + 3, &gostr3410_params[2], NULL, 0);
sc_format_asn1_entry(asn1_ecckey_attr + 0, &info.path, NULL, 0);
sc_format_asn1_entry(asn1_ecckey_attr + 1, &info.field_length, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 0, &info.id, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 1, &info.usage, &usage_len, 0);
sc_format_asn1_entry(asn1_com_key_attr + 2, &info.native, NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 3, &info.access_flags, &af_len, 0);
sc_format_asn1_entry(asn1_com_key_attr + 4, &info.key_reference, NULL, 0);
for (i=0; i<SC_MAX_SUPPORTED_ALGORITHMS && (asn1_supported_algorithms + i)->name; i++)
sc_format_asn1_entry(asn1_supported_algorithms + i, &info.algo_refs[i], NULL, 0);
sc_format_asn1_entry(asn1_com_key_attr + 5, asn1_supported_algorithms, NULL, 0);
sc_format_asn1_entry(asn1_com_prkey_attr + 0, &info.subject.value, &info.subject.len, 0);
/* Fill in defaults */
memset(&info, 0, sizeof(info));
info.key_reference = -1;
info.native = 1;
memset(gostr3410_params, 0, sizeof(gostr3410_params));
r = sc_asn1_decode_choice(ctx, asn1_prkey, *buf, *buflen, buf, buflen);
if (r < 0) {
/* This might have allocated something. If so, clear it now */
if (asn1_com_prkey_attr->flags & SC_ASN1_PRESENT &&
asn1_com_prkey_attr[0].flags & SC_ASN1_PRESENT) {
free(asn1_com_prkey_attr[0].parm);
}
}
if (r == SC_ERROR_ASN1_END_OF_CONTENTS)
return r;
LOG_TEST_RET(ctx, r, "PrKey DF ASN.1 decoding failed");
if (asn1_prkey[0].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_RSA;
}
else if (asn1_prkey[1].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_EC;
}
else if (asn1_prkey[2].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_DSA;
/* If the value was indirect-protected, mark the path */
if (asn1_dsakey_i_p_attr[0].flags & SC_ASN1_PRESENT)
info.path.type = SC_PATH_TYPE_PATH_PROT;
}
else if (asn1_prkey[3].flags & SC_ASN1_PRESENT) {
obj->type = SC_PKCS15_TYPE_PRKEY_GOSTR3410;
assert(info.modulus_length == 0);
info.modulus_length = SC_PKCS15_GOSTR3410_KEYSIZE;
assert(info.params.len == 0);
info.params.len = sizeof(struct sc_pkcs15_keyinfo_gostparams);
info.params.data = malloc(info.params.len);
if (info.params.data == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
assert(sizeof(*keyinfo_gostparams) == info.params.len);
keyinfo_gostparams = info.params.data;
keyinfo_gostparams->gostr3410 = gostr3410_params[0];
keyinfo_gostparams->gostr3411 = gostr3410_params[1];
keyinfo_gostparams->gost28147 = gostr3410_params[2];
}
else {
sc_log(ctx, "Neither RSA or DSA or GOSTR3410 or ECC key in PrKDF entry.");
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ASN1_OBJECT);
}
if (!p15card->app || !p15card->app->ddo.aid.len) {
r = sc_pkcs15_make_absolute_path(&p15card->file_app->path, &info.path);
if (r < 0) {
sc_pkcs15_free_key_params(&info.params);
return r;
}
}
else {
info.path.aid = p15card->app->ddo.aid;
}
sc_log(ctx, "PrivKey path '%s'", sc_print_path(&info.path));
/* OpenSC 0.11.4 and older encoded "keyReference" as a negative value.
* Fixed in 0.11.5 we need to add a hack, so old cards continue to work. */
if (info.key_reference < -1)
info.key_reference += 256;
/* Check the auth_id - if not present, try and find it in access rules */
if ((obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) && (obj->auth_id.len == 0)) {
sc_log(ctx, "Private key %s has no auth ID - checking AccessControlRules",
sc_pkcs15_print_id(&info.id));
/* Search in the access_rules for an appropriate auth ID */
for (i = 0; i < SC_PKCS15_MAX_ACCESS_RULES; i++) {
/* If access_mode is one of the private key usage modes */
if (obj->access_rules[i].access_mode &
(SC_PKCS15_ACCESS_RULE_MODE_EXECUTE |
SC_PKCS15_ACCESS_RULE_MODE_PSO_CDS |
SC_PKCS15_ACCESS_RULE_MODE_PSO_DECRYPT |
SC_PKCS15_ACCESS_RULE_MODE_INT_AUTH)) {
if (obj->access_rules[i].auth_id.len != 0) {
/* Found an auth ID to use for private key access */
obj->auth_id = obj->access_rules[i].auth_id;
sc_log(ctx, "Auth ID found - %s",
sc_pkcs15_print_id(&obj->auth_id));
break;
}
}
}
/* No auth ID found */
if (i == SC_PKCS15_MAX_ACCESS_RULES)
sc_log(ctx, "Warning: No auth ID found");
}
obj->data = malloc(sizeof(info));
if (obj->data == NULL) {
sc_pkcs15_free_key_params(&info.params);
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
}
memcpy(obj->data, &info, sizeof(info));
sc_log(ctx, "Key Subject %s", sc_dump_hex(info.subject.value, info.subject.len));
sc_log(ctx, "Key path %s", sc_print_path(&info.path));
return 0;
}
int sc_pkcs15_encode_prkdf_entry(sc_context_t *ctx, const struct sc_pkcs15_object *obj,
u8 **buf, size_t *buflen)
{
struct sc_asn1_entry asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_rsakey_attr[C_ASN1_RSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE];
struct sc_asn1_entry asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE];
struct sc_asn1_entry asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE];
struct sc_asn1_entry asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE];
struct sc_asn1_entry asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR];
struct sc_asn1_entry asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR];
struct sc_asn1_entry asn1_prkey[C_ASN1_PRKEY_SIZE];
struct sc_asn1_entry asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE];
struct sc_asn1_pkcs15_object rsa_prkey_obj = {
(struct sc_pkcs15_object *) obj, asn1_com_key_attr,
asn1_com_prkey_attr, asn1_prk_rsa_attr
};
struct sc_asn1_pkcs15_object dsa_prkey_obj = {
(struct sc_pkcs15_object *) obj, asn1_com_key_attr,
asn1_com_prkey_attr, asn1_prk_dsa_attr
};
struct sc_asn1_pkcs15_object gostr3410_prkey_obj = {
(struct sc_pkcs15_object *) obj,
asn1_com_key_attr, asn1_com_prkey_attr,
asn1_prk_gostr3410_attr
};
struct sc_asn1_pkcs15_object ecc_prkey_obj = {
(struct sc_pkcs15_object *) obj,
asn1_com_key_attr, asn1_com_prkey_attr,
asn1_prk_ecc_attr
};
struct sc_pkcs15_prkey_info *prkey = (struct sc_pkcs15_prkey_info *) obj->data;
struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams;
int r, i;
size_t af_len, usage_len;
sc_copy_asn1_entry(c_asn1_prkey, asn1_prkey);
sc_copy_asn1_entry(c_asn1_supported_algorithms, asn1_supported_algorithms);
sc_copy_asn1_entry(c_asn1_prk_rsa_attr, asn1_prk_rsa_attr);
sc_copy_asn1_entry(c_asn1_rsakey_attr, asn1_rsakey_attr);
sc_copy_asn1_entry(c_asn1_prk_dsa_attr, asn1_prk_dsa_attr);
sc_copy_asn1_entry(c_asn1_dsakey_attr, asn1_dsakey_attr);
sc_copy_asn1_entry(c_asn1_dsakey_value_attr, asn1_dsakey_value_attr);
sc_copy_asn1_entry(c_asn1_dsakey_i_p_attr, asn1_dsakey_i_p_attr);
sc_copy_asn1_entry(c_asn1_prk_gostr3410_attr, asn1_prk_gostr3410_attr);
sc_copy_asn1_entry(c_asn1_gostr3410key_attr, asn1_gostr3410key_attr);
sc_copy_asn1_entry(c_asn1_prk_ecc_attr, asn1_prk_ecc_attr);
sc_copy_asn1_entry(c_asn1_ecckey_attr, asn1_ecckey_attr);
sc_copy_asn1_entry(c_asn1_com_prkey_attr, asn1_com_prkey_attr);
sc_copy_asn1_entry(c_asn1_com_key_attr, asn1_com_key_attr);
switch (obj->type) {
case SC_PKCS15_TYPE_PRKEY_RSA:
sc_format_asn1_entry(asn1_prkey + 0, &rsa_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_rsa_attr + 0, asn1_rsakey_attr, NULL, 1);
sc_format_asn1_entry(asn1_rsakey_attr + 0, &prkey->path, NULL, 1);
sc_format_asn1_entry(asn1_rsakey_attr + 1, &prkey->modulus_length, NULL, 1);
break;
case SC_PKCS15_TYPE_PRKEY_EC:
sc_format_asn1_entry(asn1_prkey + 1, &ecc_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_ecc_attr + 0, asn1_ecckey_attr, NULL, 1);
sc_format_asn1_entry(asn1_ecckey_attr + 0, &prkey->path, NULL, 1);
sc_format_asn1_entry(asn1_ecckey_attr + 1, &prkey->field_length, NULL, 1);
break;
case SC_PKCS15_TYPE_PRKEY_DSA:
sc_format_asn1_entry(asn1_prkey + 2, &dsa_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_dsa_attr + 0, asn1_dsakey_value_attr, NULL, 1);
if (prkey->path.type != SC_PATH_TYPE_PATH_PROT) {
/* indirect: just add the path */
sc_format_asn1_entry(asn1_dsakey_value_attr + 0, &prkey->path, NULL, 1);
}
else {
/* indirect-protected */
sc_format_asn1_entry(asn1_dsakey_value_attr + 1, asn1_dsakey_i_p_attr, NULL, 1);
sc_format_asn1_entry(asn1_dsakey_i_p_attr + 0, &prkey->path, NULL, 1);
}
break;
case SC_PKCS15_TYPE_PRKEY_GOSTR3410:
sc_format_asn1_entry(asn1_prkey + 3, &gostr3410_prkey_obj, NULL, 1);
sc_format_asn1_entry(asn1_prk_gostr3410_attr + 0, asn1_gostr3410key_attr, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 0, &prkey->path, NULL, 1);
if (prkey->params.len == sizeof(*keyinfo_gostparams)) {
keyinfo_gostparams = prkey->params.data;
sc_format_asn1_entry(asn1_gostr3410key_attr + 1, &keyinfo_gostparams->gostr3410, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 2, &keyinfo_gostparams->gostr3411, NULL, 1);
sc_format_asn1_entry(asn1_gostr3410key_attr + 3, &keyinfo_gostparams->gost28147, NULL, 1);
}
break;
default:
sc_log(ctx, "Invalid private key type: %X", obj->type);
LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
break;
}
sc_format_asn1_entry(asn1_com_key_attr + 0, &prkey->id, NULL, 1);
usage_len = sizeof(prkey->usage);
sc_format_asn1_entry(asn1_com_key_attr + 1, &prkey->usage, &usage_len, 1);
if (prkey->native == 0)
sc_format_asn1_entry(asn1_com_key_attr + 2, &prkey->native, NULL, 1);
if (prkey->access_flags) {
af_len = sizeof(prkey->access_flags);
sc_format_asn1_entry(asn1_com_key_attr + 3, &prkey->access_flags, &af_len, 1);
}
if (prkey->key_reference >= 0)
sc_format_asn1_entry(asn1_com_key_attr + 4, &prkey->key_reference, NULL, 1);
for (i=0; i<SC_MAX_SUPPORTED_ALGORITHMS && prkey->algo_refs[i]; i++) {
sc_log(ctx, "Encode algorithm(%i) %i", i, prkey->algo_refs[i]);
sc_format_asn1_entry(asn1_supported_algorithms + i, &prkey->algo_refs[i], NULL, 1);
}
sc_format_asn1_entry(asn1_com_key_attr + 5, asn1_supported_algorithms, NULL, prkey->algo_refs[0] != 0);
if (prkey->subject.value && prkey->subject.len)
sc_format_asn1_entry(asn1_com_prkey_attr + 0, prkey->subject.value, &prkey->subject.len, 1);
else
memset(asn1_com_prkey_attr, 0, sizeof(asn1_com_prkey_attr));
r = sc_asn1_encode(ctx, asn1_prkey, buf, buflen);
sc_log(ctx, "Key path %s", sc_print_path(&prkey->path));
return r;
}
int
sc_pkcs15_prkey_attrs_from_cert(struct sc_pkcs15_card *p15card, struct sc_pkcs15_object *cert_object,
struct sc_pkcs15_object **out_key_object)
{
struct sc_context *ctx = p15card->card->ctx;
#ifdef ENABLE_OPENSSL
struct sc_pkcs15_object *key_object = NULL;
struct sc_pkcs15_prkey_info *key_info = NULL;
X509 *x = NULL;
BIO *mem = NULL;
unsigned char *buff = NULL, *ptr = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (out_key_object)
*out_key_object = NULL;
rv = sc_pkcs15_find_prkey_by_id(p15card, &((struct sc_pkcs15_cert_info *)cert_object->data)->id, &key_object);
if (rv == SC_ERROR_OBJECT_NOT_FOUND)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_TEST_RET(ctx, rv, "Find private key error");
key_info = (struct sc_pkcs15_prkey_info *) key_object->data;
ERR_load_ERR_strings();
ERR_load_crypto_strings();
sc_log(ctx, "CertValue(%"SC_FORMAT_LEN_SIZE_T"u) %p",
cert_object->content.len, cert_object->content.value);
mem = BIO_new_mem_buf(cert_object->content.value, cert_object->content.len);
if (!mem)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "MEM buffer allocation error");
x = d2i_X509_bio(mem, NULL);
if (!x)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "x509 parse error");
buff = OPENSSL_malloc(i2d_X509(x,NULL) + EVP_MAX_MD_SIZE);
if (!buff)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "OpenSSL allocation error");
ptr = buff;
rv = i2d_X509_NAME(X509_get_subject_name(x), &ptr);
if (rv <= 0)
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Get subject name error");
key_info->subject.value = malloc(rv);
if (!key_info->subject.value)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Subject allocation error");
memcpy(key_info->subject.value, buff, rv);
key_info->subject.len = rv;
strlcpy(key_object->label, cert_object->label, sizeof(key_object->label));
rv = 0;
if (x)
X509_free(x);
if (mem)
BIO_free(mem);
if (buff)
OPENSSL_free(buff);
ERR_clear_error();
ERR_free_strings();
if (out_key_object)
*out_key_object = key_object;
sc_log(ctx, "Subject %s", sc_dump_hex(key_info->subject.value, key_info->subject.len));
LOG_FUNC_RETURN(ctx, rv);
#else
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
#endif
}
void
sc_pkcs15_free_prkey(struct sc_pkcs15_prkey *key)
{
if (!key)
return;
switch (key->algorithm) {
case SC_ALGORITHM_RSA:
free(key->u.rsa.modulus.data);
free(key->u.rsa.exponent.data);
free(key->u.rsa.d.data);
free(key->u.rsa.p.data);
free(key->u.rsa.q.data);
free(key->u.rsa.iqmp.data);
free(key->u.rsa.dmp1.data);
free(key->u.rsa.dmq1.data);
break;
case SC_ALGORITHM_DSA:
free(key->u.dsa.pub.data);
free(key->u.dsa.p.data);
free(key->u.dsa.q.data);
free(key->u.dsa.g.data);
free(key->u.dsa.priv.data);
break;
case SC_ALGORITHM_GOSTR3410:
assert(key->u.gostr3410.d.data);
free(key->u.gostr3410.d.data);
break;
case SC_ALGORITHM_EC:
if (key->u.ec.params.der.value)
free(key->u.ec.params.der.value);
if (key->u.ec.params.named_curve)
free(key->u.ec.params.named_curve);
if (key->u.ec.privateD.data)
free(key->u.ec.privateD.data);
if (key->u.ec.ecpointQ.value)
free(key->u.ec.ecpointQ.value);
break;
}
}
void sc_pkcs15_free_prkey_info(sc_pkcs15_prkey_info_t *key)
{
if (key->subject.value)
free(key->subject.value);
sc_pkcs15_free_key_params(&key->params);
sc_aux_data_free(&key->aux_data);
free(key);
}
int
sc_pkcs15_convert_bignum(sc_pkcs15_bignum_t *dst, const void *src)
{
#ifdef ENABLE_OPENSSL
const BIGNUM *bn = (const BIGNUM *)src;
if (bn == 0)
return 0;
dst->len = BN_num_bytes(bn);
dst->data = malloc(dst->len);
if (!dst->data)
return 0;
BN_bn2bin(bn, dst->data);
return 1;
#else
return 0;
#endif
}
int
sc_pkcs15_convert_prkey(struct sc_pkcs15_prkey *pkcs15_key, void *evp_key)
{
#ifdef ENABLE_OPENSSL
EVP_PKEY *pk = (EVP_PKEY *)evp_key;
int pk_type;
pk_type = EVP_PKEY_base_id(pk);
switch (pk_type) {
case EVP_PKEY_RSA: {
struct sc_pkcs15_prkey_rsa *dst = &pkcs15_key->u.rsa;
RSA *src = EVP_PKEY_get1_RSA(pk);
const BIGNUM *src_n, *src_e, *src_d, *src_p, *src_q, *src_iqmp, *src_dmp1, *src_dmq1;
RSA_get0_key(src, &src_n, &src_e, &src_d);
RSA_get0_factors(src, &src_p, &src_q);
RSA_get0_crt_params(src, &src_dmp1, &src_dmq1, &src_iqmp);
pkcs15_key->algorithm = SC_ALGORITHM_RSA;
if (!sc_pkcs15_convert_bignum(&dst->modulus, src_n)
|| !sc_pkcs15_convert_bignum(&dst->exponent, src_e)
|| !sc_pkcs15_convert_bignum(&dst->d, src_d)
|| !sc_pkcs15_convert_bignum(&dst->p, src_p)
|| !sc_pkcs15_convert_bignum(&dst->q, src_q))
return SC_ERROR_NOT_SUPPORTED;
if (src_iqmp && src_dmp1 && src_dmq1) {
sc_pkcs15_convert_bignum(&dst->iqmp, src_iqmp);
sc_pkcs15_convert_bignum(&dst->dmp1, src_dmp1);
sc_pkcs15_convert_bignum(&dst->dmq1, src_dmq1);
}
RSA_free(src);
break;
}
case EVP_PKEY_DSA: {
struct sc_pkcs15_prkey_dsa *dst = &pkcs15_key->u.dsa;
DSA *src = EVP_PKEY_get1_DSA(pk);
const BIGNUM *src_pub_key, *src_p, *src_q, *src_g, *src_priv_key;
DSA_get0_key(src, &src_pub_key, &src_priv_key);
DSA_get0_pqg(src, &src_p, &src_q, &src_g);
pkcs15_key->algorithm = SC_ALGORITHM_DSA;
sc_pkcs15_convert_bignum(&dst->pub, src_pub_key);
sc_pkcs15_convert_bignum(&dst->p, src_p);
sc_pkcs15_convert_bignum(&dst->q, src_q);
sc_pkcs15_convert_bignum(&dst->g, src_g);
sc_pkcs15_convert_bignum(&dst->priv, src_priv_key);
DSA_free(src);
break;
}
#if OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_EC)
case NID_id_GostR3410_2001: {
struct sc_pkcs15_prkey_gostr3410 *dst = &pkcs15_key->u.gostr3410;
EC_KEY *src = EVP_PKEY_get0(pk);
assert(src);
pkcs15_key->algorithm = SC_ALGORITHM_GOSTR3410;
assert(EC_KEY_get0_private_key(src));
sc_pkcs15_convert_bignum(&dst->d, EC_KEY_get0_private_key(src));
break;
}
case EVP_PKEY_EC: {
struct sc_pkcs15_prkey_ec *dst = &pkcs15_key->u.ec;
EC_KEY *src = NULL;
const EC_GROUP *grp = NULL;
unsigned char buf[255];
size_t buflen = 255;
int nid;
src = EVP_PKEY_get0(pk);
assert(src);
assert(EC_KEY_get0_private_key(src));
assert(EC_KEY_get0_public_key(src));
pkcs15_key->algorithm = SC_ALGORITHM_EC;
if (!sc_pkcs15_convert_bignum(&dst->privateD, EC_KEY_get0_private_key(src)))
return SC_ERROR_INCOMPATIBLE_KEY;
grp = EC_KEY_get0_group(src);
if(grp == 0)
return SC_ERROR_INCOMPATIBLE_KEY;
/* get curve name */
nid = EC_GROUP_get_curve_name(grp);
if(nid != 0) {
const char *sn = OBJ_nid2sn(nid);
if (sn)
dst->params.named_curve = strdup(sn);
}
/* Decode EC_POINT from a octet string */
buflen = EC_POINT_point2oct(grp, (const EC_POINT *) EC_KEY_get0_public_key(src),
POINT_CONVERSION_UNCOMPRESSED, buf, buflen, NULL);
if (!buflen)
return SC_ERROR_INCOMPATIBLE_KEY;
/* copy the public key */
dst->ecpointQ.value = malloc(buflen);
if (!dst->ecpointQ.value)
return SC_ERROR_OUT_OF_MEMORY;
memcpy(dst->ecpointQ.value, buf, buflen);
dst->ecpointQ.len = buflen;
/*
* In OpenSC the field_length is in bits. Not all curves are a mutiple of 8.
* EC_POINT_point2oct handles this and returns octstrings that can handle
* these curves. Get real field_length from OpenSSL.
*/
dst->params.field_length = EC_GROUP_get_degree(grp);
/* Octetstring may need leading zeros if BN is to short */
if (dst->privateD.len < (dst->params.field_length + 7) / 8) {
size_t d = (dst->params.field_length + 7) / 8 - dst->privateD.len;
dst->privateD.data = realloc(dst->privateD.data, dst->privateD.len + d);
if (!dst->privateD.data)
return SC_ERROR_OUT_OF_MEMORY;
memmove(dst->privateD.data + d, dst->privateD.data, dst->privateD.len);
memset(dst->privateD.data, 0, d);
dst->privateD.len += d;
}
break;
}
#endif /* OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_EC) */
default:
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
#else
return SC_ERROR_NOT_IMPLEMENTED;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-672/c/bad_1298_0 |
crossvul-cpp_data_good_1198_11 | /* shell.c -- GNU's idea of the POSIX shell specification. */
/* Copyright (C) 1987-2017 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Birthdate:
Sunday, January 10th, 1988.
Initial author: Brian Fox
*/
#define INSTALL_DEBUG_MODE
#include "config.h"
#include "bashtypes.h"
#if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
# include <sys/file.h>
#endif
#include "posixstat.h"
#include "posixtime.h"
#include "bashansi.h"
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include "filecntl.h"
#if defined (HAVE_PWD_H)
# include <pwd.h>
#endif
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashintl.h"
#define NEED_SH_SETLINEBUF_DECL /* used in externs.h */
#include "shell.h"
#include "parser.h"
#include "flags.h"
#include "trap.h"
#include "mailcheck.h"
#include "builtins.h"
#include "builtins/common.h"
#if defined (JOB_CONTROL)
#include "jobs.h"
#else
extern int running_in_background;
extern int initialize_job_control __P((int));
extern int get_tty_state __P((void));
#endif /* JOB_CONTROL */
#include "input.h"
#include "execute_cmd.h"
#include "findcmd.h"
#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
# include <malloc/shmalloc.h>
#endif
#if defined (HISTORY)
# include "bashhist.h"
# include <readline/history.h>
#endif
#if defined (READLINE)
# include <readline/readline.h>
# include "bashline.h"
#endif
#include <tilde/tilde.h>
#include <glob/strmatch.h>
#if defined (__OPENNT)
# include <opennt/opennt.h>
#endif
#if !defined (HAVE_GETPW_DECLS)
extern struct passwd *getpwuid ();
#endif /* !HAVE_GETPW_DECLS */
#if !defined (errno)
extern int errno;
#endif
#if defined (NO_MAIN_ENV_ARG)
extern char **environ; /* used if no third argument to main() */
#endif
extern int gnu_error_format;
/* Non-zero means that this shell has already been run; i.e. you should
call shell_reinitialize () if you need to start afresh. */
int shell_initialized = 0;
int bash_argv_initialized = 0;
COMMAND *global_command = (COMMAND *)NULL;
/* Information about the current user. */
struct user_info current_user =
{
(uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
(char *)NULL, (char *)NULL, (char *)NULL
};
/* The current host's name. */
char *current_host_name = (char *)NULL;
/* Non-zero means that this shell is a login shell.
Specifically:
0 = not login shell.
1 = login shell from getty (or equivalent fake out)
-1 = login shell from "--login" (or -l) flag.
-2 = both from getty, and from flag.
*/
int login_shell = 0;
/* Non-zero means that at this moment, the shell is interactive. In
general, this means that the shell is at this moment reading input
from the keyboard. */
int interactive = 0;
/* Non-zero means that the shell was started as an interactive shell. */
int interactive_shell = 0;
/* Non-zero means to send a SIGHUP to all jobs when an interactive login
shell exits. */
int hup_on_exit = 0;
/* Non-zero means to list status of running and stopped jobs at shell exit */
int check_jobs_at_exit = 0;
/* Non-zero means to change to a directory name supplied as a command name */
int autocd = 0;
/* Tells what state the shell was in when it started:
0 = non-interactive shell script
1 = interactive
2 = -c command
3 = wordexp evaluation
This is a superset of the information provided by interactive_shell.
*/
int startup_state = 0;
int reading_shell_script = 0;
/* Special debugging helper. */
int debugging_login_shell = 0;
/* The environment that the shell passes to other commands. */
char **shell_environment;
/* Non-zero when we are executing a top-level command. */
int executing = 0;
/* The number of commands executed so far. */
int current_command_number = 1;
/* Non-zero is the recursion depth for commands. */
int indirection_level = 0;
/* The name of this shell, as taken from argv[0]. */
char *shell_name = (char *)NULL;
/* time in seconds when the shell was started */
time_t shell_start_time;
/* Are we running in an emacs shell window? */
int running_under_emacs;
/* Do we have /dev/fd? */
#ifdef HAVE_DEV_FD
int have_devfd = HAVE_DEV_FD;
#else
int have_devfd = 0;
#endif
/* The name of the .(shell)rc file. */
static char *bashrc_file = DEFAULT_BASHRC;
/* Non-zero means to act more like the Bourne shell on startup. */
static int act_like_sh;
/* Non-zero if this shell is being run by `su'. */
static int su_shell;
/* Non-zero if we have already expanded and sourced $ENV. */
static int sourced_env;
/* Is this shell running setuid? */
static int running_setuid;
/* Values for the long-winded argument names. */
static int debugging; /* Do debugging things. */
static int no_rc; /* Don't execute ~/.bashrc */
static int no_profile; /* Don't execute .profile */
static int do_version; /* Display interesting version info. */
static int make_login_shell; /* Make this shell be a `-bash' shell. */
static int want_initial_help; /* --help option */
int debugging_mode = 0; /* In debugging mode with --debugger */
#if defined (READLINE)
int no_line_editing = 0; /* non-zero -> don't do fancy line editing. */
#else
int no_line_editing = 1; /* can't have line editing without readline */
#endif
int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
int dump_po_strings; /* Dump strings in $"..." in po format */
int wordexp_only = 0; /* Do word expansion only */
int protected_mode = 0; /* No command substitution with --wordexp */
int pretty_print_mode = 0; /* pretty-print a shell script */
#if defined (STRICT_POSIX)
int posixly_correct = 1; /* Non-zero means posix.2 superset. */
#else
int posixly_correct = 0; /* Non-zero means posix.2 superset. */
#endif
/* Some long-winded argument names. These are obviously new. */
#define Int 1
#define Charp 2
static const struct {
const char *name;
int type;
int *int_value;
char **char_value;
} long_args[] = {
{ "debug", Int, &debugging, (char **)0x0 },
#if defined (DEBUGGER)
{ "debugger", Int, &debugging_mode, (char **)0x0 },
#endif
{ "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
{ "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
{ "help", Int, &want_initial_help, (char **)0x0 },
{ "init-file", Charp, (int *)0x0, &bashrc_file },
{ "login", Int, &make_login_shell, (char **)0x0 },
{ "noediting", Int, &no_line_editing, (char **)0x0 },
{ "noprofile", Int, &no_profile, (char **)0x0 },
{ "norc", Int, &no_rc, (char **)0x0 },
{ "posix", Int, &posixly_correct, (char **)0x0 },
{ "pretty-print", Int, &pretty_print_mode, (char **)0x0 },
#if defined (WORDEXP_OPTION)
{ "protected", Int, &protected_mode, (char **)0x0 },
#endif
{ "rcfile", Charp, (int *)0x0, &bashrc_file },
#if defined (RESTRICTED_SHELL)
{ "restricted", Int, &restricted, (char **)0x0 },
#endif
{ "verbose", Int, &verbose_flag, (char **)0x0 },
{ "version", Int, &do_version, (char **)0x0 },
#if defined (WORDEXP_OPTION)
{ "wordexp", Int, &wordexp_only, (char **)0x0 },
#endif
{ (char *)0x0, Int, (int *)0x0, (char **)0x0 }
};
/* These are extern so execute_simple_command can set them, and then
longjmp back to main to execute a shell script, instead of calling
main () again and resulting in indefinite, possibly fatal, stack
growth. */
procenv_t subshell_top_level;
int subshell_argc;
char **subshell_argv;
char **subshell_envp;
char *exec_argv0;
#if defined (BUFFERED_INPUT)
/* The file descriptor from which the shell is reading input. */
int default_buffered_input = -1;
#endif
/* The following two variables are not static so they can show up in $-. */
int read_from_stdin; /* -s flag supplied */
int want_pending_command; /* -c flag supplied */
/* This variable is not static so it can be bound to $BASH_EXECUTION_STRING */
char *command_execution_string; /* argument to -c option */
char *shell_script_filename; /* shell script */
int malloc_trace_at_exit = 0;
static int shell_reinitialized = 0;
static FILE *default_input;
static STRING_INT_ALIST *shopt_alist;
static int shopt_ind = 0, shopt_len = 0;
static int parse_long_options __P((char **, int, int));
static int parse_shell_options __P((char **, int, int));
static int bind_args __P((char **, int, int, int));
static void start_debugger __P((void));
static void add_shopt_to_alist __P((char *, int));
static void run_shopt_alist __P((void));
static void execute_env_file __P((char *));
static void run_startup_files __P((void));
static int open_shell_script __P((char *));
static void set_bash_input __P((void));
static int run_one_command __P((char *));
#if defined (WORDEXP_OPTION)
static int run_wordexp __P((char *));
#endif
static int uidget __P((void));
static void init_interactive __P((void));
static void init_noninteractive __P((void));
static void init_interactive_script __P((void));
static void set_shell_name __P((char *));
static void shell_initialize __P((void));
static void shell_reinitialize __P((void));
static void show_shell_usage __P((FILE *, int));
#ifdef __CYGWIN__
static void
_cygwin32_check_tmp ()
{
struct stat sb;
if (stat ("/tmp", &sb) < 0)
internal_warning (_("could not find /tmp, please create!"));
else
{
if (S_ISDIR (sb.st_mode) == 0)
internal_warning (_("/tmp must be a valid directory name"));
}
}
#endif /* __CYGWIN__ */
#if defined (NO_MAIN_ENV_ARG)
/* systems without third argument to main() */
int
main (argc, argv)
int argc;
char **argv;
#else /* !NO_MAIN_ENV_ARG */
int
main (argc, argv, env)
int argc;
char **argv, **env;
#endif /* !NO_MAIN_ENV_ARG */
{
register int i;
int code, old_errexit_flag;
#if defined (RESTRICTED_SHELL)
int saverst;
#endif
volatile int locally_skip_execution;
volatile int arg_index, top_level_arg_index;
#ifdef __OPENNT
char **env;
env = environ;
#endif /* __OPENNT */
USE_VAR(argc);
USE_VAR(argv);
USE_VAR(env);
USE_VAR(code);
USE_VAR(old_errexit_flag);
#if defined (RESTRICTED_SHELL)
USE_VAR(saverst);
#endif
/* Catch early SIGINTs. */
code = setjmp_nosigs (top_level);
if (code)
exit (2);
xtrace_init ();
#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
malloc_set_register (1); /* XXX - change to 1 for malloc debugging */
#endif
check_dev_tty ();
#ifdef __CYGWIN__
_cygwin32_check_tmp ();
#endif /* __CYGWIN__ */
/* Wait forever if we are debugging a login shell. */
while (debugging_login_shell) sleep (3);
set_default_locale ();
running_setuid = uidget ();
if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
posixly_correct = 1;
#if defined (USE_GNU_MALLOC_LIBRARY)
mcheck (programming_error, (void (*) ())0);
#endif /* USE_GNU_MALLOC_LIBRARY */
if (setjmp_sigs (subshell_top_level))
{
argc = subshell_argc;
argv = subshell_argv;
env = subshell_envp;
sourced_env = 0;
}
shell_reinitialized = 0;
/* Initialize `local' variables for all `invocations' of main (). */
arg_index = 1;
if (arg_index > argc)
arg_index = argc;
command_execution_string = shell_script_filename = (char *)NULL;
want_pending_command = locally_skip_execution = read_from_stdin = 0;
default_input = stdin;
#if defined (BUFFERED_INPUT)
default_buffered_input = -1;
#endif
/* Fix for the `infinite process creation' bug when running shell scripts
from startup files on System V. */
login_shell = make_login_shell = 0;
/* If this shell has already been run, then reinitialize it to a
vanilla state. */
if (shell_initialized || shell_name)
{
/* Make sure that we do not infinitely recurse as a login shell. */
if (*shell_name == '-')
shell_name++;
shell_reinitialize ();
if (setjmp_nosigs (top_level))
exit (2);
}
shell_environment = env;
set_shell_name (argv[0]);
shell_start_time = NOW; /* NOW now defined in general.h */
/* Parse argument flags from the input line. */
/* Find full word arguments first. */
arg_index = parse_long_options (argv, arg_index, argc);
if (want_initial_help)
{
show_shell_usage (stdout, 1);
exit (EXECUTION_SUCCESS);
}
if (do_version)
{
show_shell_version (1);
exit (EXECUTION_SUCCESS);
}
echo_input_at_read = verbose_flag; /* --verbose given */
/* All done with full word options; do standard shell option parsing.*/
this_command_name = shell_name; /* for error reporting */
arg_index = parse_shell_options (argv, arg_index, argc);
/* If user supplied the "--login" (or -l) flag, then set and invert
LOGIN_SHELL. */
if (make_login_shell)
{
login_shell++;
login_shell = -login_shell;
}
set_login_shell ("login_shell", login_shell != 0);
if (dump_po_strings)
dump_translatable_strings = 1;
if (dump_translatable_strings)
read_but_dont_execute = 1;
if (running_setuid && privileged_mode == 0)
disable_priv_mode ();
/* Need to get the argument to a -c option processed in the
above loop. The next arg is a command to execute, and the
following args are $0...$n respectively. */
if (want_pending_command)
{
command_execution_string = argv[arg_index];
if (command_execution_string == 0)
{
report_error (_("%s: option requires an argument"), "-c");
exit (EX_BADUSAGE);
}
arg_index++;
}
this_command_name = (char *)NULL;
/* First, let the outside world know about our interactive status.
A shell is interactive if the `-i' flag was given, or if all of
the following conditions are met:
no -c command
no arguments remaining or the -s flag given
standard input is a terminal
standard error is a terminal
Refer to Posix.2, the description of the `sh' utility. */
if (forced_interactive || /* -i flag */
(!command_execution_string && /* No -c command and ... */
wordexp_only == 0 && /* No --wordexp and ... */
((arg_index == argc) || /* no remaining args or... */
read_from_stdin) && /* -s flag with args, and */
isatty (fileno (stdin)) && /* Input is a terminal and */
isatty (fileno (stderr)))) /* error output is a terminal. */
init_interactive ();
else
init_noninteractive ();
/*
* Some systems have the bad habit of starting login shells with lots of open
* file descriptors. For instance, most systems that have picked up the
* pre-4.0 Sun YP code leave a file descriptor open each time you call one
* of the getpw* functions, and it's set to be open across execs. That
* means one for login, one for xterm, one for shelltool, etc. There are
* also systems that open persistent FDs to other agents or files as part
* of process startup; these need to be set to be close-on-exec.
*/
if (login_shell && interactive_shell)
{
for (i = 3; i < 20; i++)
SET_CLOSE_ON_EXEC (i);
}
/* If we're in a strict Posix.2 mode, turn on interactive comments,
alias expansion in non-interactive shells, and other Posix.2 things. */
if (posixly_correct)
{
bind_variable ("POSIXLY_CORRECT", "y", 0);
sv_strict_posix ("POSIXLY_CORRECT");
}
/* Now we run the shopt_alist and process the options. */
if (shopt_alist)
run_shopt_alist ();
/* From here on in, the shell must be a normal functioning shell.
Variables from the environment are expected to be set, etc. */
shell_initialize ();
set_default_lang ();
set_default_locale_vars ();
/*
* M-x term -> TERM=eterm-color INSIDE_EMACS='251,term:0.96' (eterm)
* M-x shell -> TERM='dumb' INSIDE_EMACS='25.1,comint' (no line editing)
*
* Older versions of Emacs may set EMACS to 't' or to something like
* '22.1 (term:0.96)' instead of (or in addition to) setting INSIDE_EMACS.
* They may set TERM to 'eterm' instead of 'eterm-color'. They may have
* a now-obsolete command that sets neither EMACS nor INSIDE_EMACS:
* M-x terminal -> TERM='emacs-em7955' (line editing)
*/
if (interactive_shell)
{
char *term, *emacs, *inside_emacs;
int emacs_term, in_emacs;
term = get_string_value ("TERM");
emacs = get_string_value ("EMACS");
inside_emacs = get_string_value ("INSIDE_EMACS");
if (inside_emacs)
{
emacs_term = strstr (inside_emacs, ",term:") != 0;
in_emacs = 1;
}
else if (emacs)
{
/* Infer whether we are in an older Emacs. */
emacs_term = strstr (emacs, " (term:") != 0;
in_emacs = emacs_term || STREQ (emacs, "t");
}
else
in_emacs = emacs_term = 0;
/* Not sure any emacs terminal emulator sets TERM=emacs any more */
no_line_editing |= STREQ (term, "emacs");
no_line_editing |= in_emacs && STREQ (term, "dumb");
/* running_under_emacs == 2 for `eterm' */
running_under_emacs = in_emacs || STREQN (term, "emacs", 5);
running_under_emacs += emacs_term && STREQN (term, "eterm", 5);
if (running_under_emacs)
gnu_error_format = 1;
}
top_level_arg_index = arg_index;
old_errexit_flag = exit_immediately_on_error;
/* Give this shell a place to longjmp to before executing the
startup files. This allows users to press C-c to abort the
lengthy startup. */
code = setjmp_sigs (top_level);
if (code)
{
if (code == EXITPROG || code == ERREXIT)
exit_shell (last_command_exit_value);
else
{
#if defined (JOB_CONTROL)
/* Reset job control, since run_startup_files turned it off. */
set_job_control (interactive_shell);
#endif
/* Reset value of `set -e', since it's turned off before running
the startup files. */
exit_immediately_on_error += old_errexit_flag;
locally_skip_execution++;
}
}
arg_index = top_level_arg_index;
/* Execute the start-up scripts. */
if (interactive_shell == 0)
{
unbind_variable ("PS1");
unbind_variable ("PS2");
interactive = 0;
#if 0
/* This has already been done by init_noninteractive */
expand_aliases = posixly_correct;
#endif
}
else
{
change_flag ('i', FLAG_ON);
interactive = 1;
}
#if defined (RESTRICTED_SHELL)
/* Set restricted_shell based on whether the basename of $0 indicates that
the shell should be restricted or if the `-r' option was supplied at
startup. */
restricted_shell = shell_is_restricted (shell_name);
/* If the `-r' option is supplied at invocation, make sure that the shell
is not in restricted mode when running the startup files. */
saverst = restricted;
restricted = 0;
#endif
/* Set positional parameters before running startup files. top_level_arg_index
holds the index of the current argument before setting the positional
parameters, so any changes performed in the startup files won't affect
later option processing. */
if (wordexp_only)
; /* nothing yet */
else if (command_execution_string)
arg_index = bind_args (argv, arg_index, argc, 0); /* $0 ... $n */
else if (arg_index != argc && read_from_stdin == 0)
{
shell_script_filename = argv[arg_index++];
arg_index = bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
}
else
arg_index = bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
/* The startup files are run with `set -e' temporarily disabled. */
if (locally_skip_execution == 0 && running_setuid == 0)
{
old_errexit_flag = exit_immediately_on_error;
exit_immediately_on_error = 0;
run_startup_files ();
exit_immediately_on_error += old_errexit_flag;
}
/* If we are invoked as `sh', turn on Posix mode. */
if (act_like_sh)
{
bind_variable ("POSIXLY_CORRECT", "y", 0);
sv_strict_posix ("POSIXLY_CORRECT");
}
#if defined (RESTRICTED_SHELL)
/* Turn on the restrictions after executing the startup files. This
means that `bash -r' or `set -r' invoked from a startup file will
turn on the restrictions after the startup files are executed. */
restricted = saverst || restricted;
if (shell_reinitialized == 0)
maybe_make_restricted (shell_name);
#endif /* RESTRICTED_SHELL */
#if defined (WORDEXP_OPTION)
if (wordexp_only)
{
startup_state = 3;
last_command_exit_value = run_wordexp (argv[top_level_arg_index]);
exit_shell (last_command_exit_value);
}
#endif
cmd_init (); /* initialize the command object caches */
uwp_init ();
if (command_execution_string)
{
startup_state = 2;
if (debugging_mode)
start_debugger ();
#if defined (ONESHOT)
executing = 1;
run_one_command (command_execution_string);
exit_shell (last_command_exit_value);
#else /* ONESHOT */
with_input_from_string (command_execution_string, "-c");
goto read_and_execute;
#endif /* !ONESHOT */
}
/* Get possible input filename and set up default_buffered_input or
default_input as appropriate. */
if (shell_script_filename)
open_shell_script (shell_script_filename);
else if (interactive == 0)
{
/* In this mode, bash is reading a script from stdin, which is a
pipe or redirected file. */
#if defined (BUFFERED_INPUT)
default_buffered_input = fileno (stdin); /* == 0 */
#else
setbuf (default_input, (char *)NULL);
#endif /* !BUFFERED_INPUT */
read_from_stdin = 1;
}
else if (top_level_arg_index == argc) /* arg index before startup files */
/* "If there are no operands and the -c option is not specified, the -s
option shall be assumed." */
read_from_stdin = 1;
set_bash_input ();
if (debugging_mode && locally_skip_execution == 0 && running_setuid == 0 && (reading_shell_script || interactive_shell == 0))
start_debugger ();
/* Do the things that should be done only for interactive shells. */
if (interactive_shell)
{
/* Set up for checking for presence of mail. */
reset_mail_timer ();
init_mail_dates ();
#if defined (HISTORY)
/* Initialize the interactive history stuff. */
bash_initialize_history ();
/* Don't load the history from the history file if we've already
saved some lines in this session (e.g., by putting `history -s xx'
into one of the startup files). */
if (shell_initialized == 0 && history_lines_this_session == 0)
load_history ();
#endif /* HISTORY */
/* Initialize terminal state for interactive shells after the
.bash_profile and .bashrc are interpreted. */
get_tty_state ();
}
#if !defined (ONESHOT)
read_and_execute:
#endif /* !ONESHOT */
shell_initialized = 1;
if (pretty_print_mode && interactive_shell)
{
internal_warning (_("pretty-printing mode ignored in interactive shells"));
pretty_print_mode = 0;
}
if (pretty_print_mode)
exit_shell (pretty_print_loop ());
/* Read commands until exit condition. */
reader_loop ();
exit_shell (last_command_exit_value);
}
static int
parse_long_options (argv, arg_start, arg_end)
char **argv;
int arg_start, arg_end;
{
int arg_index, longarg, i;
char *arg_string;
arg_index = arg_start;
while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
(*arg_string == '-'))
{
longarg = 0;
/* Make --login equivalent to -login. */
if (arg_string[1] == '-' && arg_string[2])
{
longarg = 1;
arg_string++;
}
for (i = 0; long_args[i].name; i++)
{
if (STREQ (arg_string + 1, long_args[i].name))
{
if (long_args[i].type == Int)
*long_args[i].int_value = 1;
else if (argv[++arg_index] == 0)
{
report_error (_("%s: option requires an argument"), long_args[i].name);
exit (EX_BADUSAGE);
}
else
*long_args[i].char_value = argv[arg_index];
break;
}
}
if (long_args[i].name == 0)
{
if (longarg)
{
report_error (_("%s: invalid option"), argv[arg_index]);
show_shell_usage (stderr, 0);
exit (EX_BADUSAGE);
}
break; /* No such argument. Maybe flag arg. */
}
arg_index++;
}
return (arg_index);
}
static int
parse_shell_options (argv, arg_start, arg_end)
char **argv;
int arg_start, arg_end;
{
int arg_index;
int arg_character, on_or_off, next_arg, i;
char *o_option, *arg_string;
arg_index = arg_start;
while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
(*arg_string == '-' || *arg_string == '+'))
{
/* There are flag arguments, so parse them. */
next_arg = arg_index + 1;
/* A single `-' signals the end of options. From the 4.3 BSD sh.
An option `--' means the same thing; this is the standard
getopt(3) meaning. */
if (arg_string[0] == '-' &&
(arg_string[1] == '\0' ||
(arg_string[1] == '-' && arg_string[2] == '\0')))
return (next_arg);
i = 1;
on_or_off = arg_string[0];
while (arg_character = arg_string[i++])
{
switch (arg_character)
{
case 'c':
want_pending_command = 1;
break;
case 'l':
make_login_shell = 1;
break;
case 's':
read_from_stdin = 1;
break;
case 'o':
o_option = argv[next_arg];
if (o_option == 0)
{
list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
break;
}
if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
exit (EX_BADUSAGE);
next_arg++;
break;
case 'O':
/* Since some of these can be overridden by the normal
interactive/non-interactive shell initialization or
initializing posix mode, we save the options and process
them after initialization. */
o_option = argv[next_arg];
if (o_option == 0)
{
shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
break;
}
add_shopt_to_alist (o_option, on_or_off);
next_arg++;
break;
case 'D':
dump_translatable_strings = 1;
break;
default:
if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
{
report_error (_("%c%c: invalid option"), on_or_off, arg_character);
show_shell_usage (stderr, 0);
exit (EX_BADUSAGE);
}
}
}
/* Can't do just a simple increment anymore -- what about
"bash -abouo emacs ignoreeof -hP"? */
arg_index = next_arg;
}
return (arg_index);
}
/* Exit the shell with status S. */
void
exit_shell (s)
int s;
{
fflush (stdout); /* XXX */
fflush (stderr);
/* Clean up the terminal if we are in a state where it's been modified. */
#if defined (READLINE)
if (RL_ISSTATE (RL_STATE_TERMPREPPED) && rl_deprep_term_function)
(*rl_deprep_term_function) ();
#endif
if (read_tty_modified ())
read_tty_cleanup ();
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
#if defined (PROCESS_SUBSTITUTION)
unlink_fifo_list ();
#endif /* PROCESS_SUBSTITUTION */
#if defined (HISTORY)
if (remember_on_history)
maybe_save_shell_history ();
#endif /* HISTORY */
#if defined (COPROCESS_SUPPORT)
coproc_flush ();
#endif
#if defined (JOB_CONTROL)
/* If the user has run `shopt -s huponexit', hangup all jobs when we exit
an interactive login shell. ksh does this unconditionally. */
if (interactive_shell && login_shell && hup_on_exit)
hangup_all_jobs ();
/* If this shell is interactive, or job control is active, terminate all
stopped jobs and restore the original terminal process group. Don't do
this if we're in a subshell and calling exit_shell after, for example,
a failed word expansion. We want to do this even if the shell is not
interactive because we set the terminal's process group when job control
is enabled regardless of the interactive status. */
if (subshell_environment == 0)
end_job_control ();
#endif /* JOB_CONTROL */
/* Always return the exit status of the last command to our parent. */
sh_exit (s);
}
/* A wrapper for exit that (optionally) can do other things, like malloc
statistics tracing. */
void
sh_exit (s)
int s;
{
#if defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
if (malloc_trace_at_exit && (subshell_environment & (SUBSHELL_COMSUB|SUBSHELL_PROCSUB)) == 0)
trace_malloc_stats (get_name_for_error (), (char *)NULL);
/* mlocation_write_table (); */
#endif
exit (s);
}
/* Exit a subshell, which includes calling the exit trap. We don't want to
do any more cleanup, since a subshell is created as an exact copy of its
parent. */
void
subshell_exit (s)
int s;
{
fflush (stdout);
fflush (stderr);
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
sh_exit (s);
}
/* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
the Posix.2 startup file rules: $ENV is expanded, and if the file it
names exists, that file is sourced. The Posix.2 rules are in effect
for interactive shells only. (section 4.56.5.3) */
/* Execute ~/.bashrc for most shells. Never execute it if
ACT_LIKE_SH is set, or if NO_RC is set.
If the executable file "/usr/gnu/src/bash/foo" contains:
#!/usr/gnu/bin/bash
echo hello
then:
COMMAND EXECUTE BASHRC
--------------------------------
bash -c foo NO
bash foo NO
foo NO
rsh machine ls YES (for rsh, which calls `bash -c')
rsh machine foo YES (for shell started by rsh) NO (for foo!)
echo ls | bash NO
login NO
bash YES
*/
static void
execute_env_file (env_file)
char *env_file;
{
char *fn;
if (env_file && *env_file)
{
fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
if (fn && *fn)
maybe_execute_file (fn, 1);
FREE (fn);
}
}
static void
run_startup_files ()
{
#if defined (JOB_CONTROL)
int old_job_control;
#endif
int sourced_login, run_by_ssh;
/* get the rshd/sshd case out of the way first. */
if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
act_like_sh == 0 && command_execution_string)
{
#ifdef SSH_SOURCE_BASHRC
run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
(find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
#else
run_by_ssh = 0;
#endif
/* If we were run by sshd or we think we were run by rshd, execute
~/.bashrc if we are a top-level shell. */
if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
{
#ifdef SYS_BASHRC
# if defined (__OPENNT)
maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
# else
maybe_execute_file (SYS_BASHRC, 1);
# endif
#endif
maybe_execute_file (bashrc_file, 1);
return;
}
}
#if defined (JOB_CONTROL)
/* Startup files should be run without job control enabled. */
old_job_control = interactive_shell ? set_job_control (0) : 0;
#endif
sourced_login = 0;
/* A shell begun with the --login (or -l) flag that is not in posix mode
runs the login shell startup files, no matter whether or not it is
interactive. If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
startup files if argv[0][0] == '-' as well. */
#if defined (NON_INTERACTIVE_LOGIN_SHELLS)
if (login_shell && posixly_correct == 0)
#else
if (login_shell < 0 && posixly_correct == 0)
#endif
{
/* We don't execute .bashrc for login shells. */
no_rc++;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (no_profile == 0)
{
maybe_execute_file (SYS_PROFILE, 1);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", 1);
else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
(maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
maybe_execute_file ("~/.profile", 1);
}
sourced_login = 1;
}
/* A non-interactive shell not named `sh' and not in posix mode reads and
executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
and `-su' as the name of the shell, we want to read the startup files.
No other non-interactive shells read any startup files. */
if (interactive_shell == 0 && !(su_shell && login_shell))
{
if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
sourced_env++ == 0)
execute_env_file (get_string_value ("BASH_ENV"));
return;
}
/* Interactive shell or `-su' shell. */
if (posixly_correct == 0) /* bash, sh */
{
if (login_shell && sourced_login++ == 0)
{
/* We don't execute .bashrc for login shells. */
no_rc++;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (no_profile == 0)
{
maybe_execute_file (SYS_PROFILE, 1);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", 1);
else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
(maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
maybe_execute_file ("~/.profile", 1);
}
}
/* bash */
if (act_like_sh == 0 && no_rc == 0)
{
#ifdef SYS_BASHRC
# if defined (__OPENNT)
maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
# else
maybe_execute_file (SYS_BASHRC, 1);
# endif
#endif
maybe_execute_file (bashrc_file, 1);
}
/* sh */
else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
execute_env_file (get_string_value ("ENV"));
}
else /* bash --posix, sh --posix */
{
/* bash and sh */
if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
execute_env_file (get_string_value ("ENV"));
}
#if defined (JOB_CONTROL)
set_job_control (old_job_control);
#endif
}
#if defined (RESTRICTED_SHELL)
/* Return 1 if the shell should be a restricted one based on NAME or the
value of `restricted'. Don't actually do anything, just return a
boolean value. */
int
shell_is_restricted (name)
char *name;
{
char *temp;
if (restricted)
return 1;
temp = base_pathname (name);
if (*temp == '-')
temp++;
return (STREQ (temp, RESTRICTED_SHELL_NAME));
}
/* Perhaps make this shell a `restricted' one, based on NAME. If the
basename of NAME is "rbash", then this shell is restricted. The
name of the restricted shell is a configurable option, see config.h.
In a restricted shell, PATH, SHELL, ENV, and BASH_ENV are read-only
and non-unsettable.
Do this also if `restricted' is already set to 1; maybe the shell was
started with -r. */
int
maybe_make_restricted (name)
char *name;
{
char *temp;
temp = base_pathname (name);
if (*temp == '-')
temp++;
if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
{
#if defined (RBASH_STATIC_PATH_VALUE)
bind_variable ("PATH", RBASH_STATIC_PATH_VALUE, 0);
stupidly_hack_special_variables ("PATH"); /* clear hash table */
#endif
set_var_read_only ("PATH");
set_var_read_only ("SHELL");
set_var_read_only ("ENV");
set_var_read_only ("BASH_ENV");
restricted = 1;
}
return (restricted);
}
#endif /* RESTRICTED_SHELL */
/* Fetch the current set of uids and gids and return 1 if we're running
setuid or setgid. */
static int
uidget ()
{
uid_t u;
u = getuid ();
if (current_user.uid != u)
{
FREE (current_user.user_name);
FREE (current_user.shell);
FREE (current_user.home_dir);
current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
}
current_user.uid = u;
current_user.gid = getgid ();
current_user.euid = geteuid ();
current_user.egid = getegid ();
/* See whether or not we are running setuid or setgid. */
return (current_user.uid != current_user.euid) ||
(current_user.gid != current_user.egid);
}
void
disable_priv_mode ()
{
int e;
#if HAVE_DECL_SETRESUID
if (setresuid (current_user.uid, current_user.uid, current_user.uid) < 0)
#else
if (setuid (current_user.uid) < 0)
#endif
{
e = errno;
sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid);
#if defined (EXIT_ON_SETUID_FAILURE)
if (e == EAGAIN)
exit (e);
#endif
}
#if HAVE_DECL_SETRESGID
if (setresgid (current_user.gid, current_user.gid, current_user.gid) < 0)
#else
if (setgid (current_user.gid) < 0)
#endif
sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid);
current_user.euid = current_user.uid;
current_user.egid = current_user.gid;
}
#if defined (WORDEXP_OPTION)
static int
run_wordexp (words)
char *words;
{
int code, nw, nb;
WORD_LIST *wl, *tl, *result;
code = setjmp_nosigs (top_level);
if (code != NOT_JUMPED)
{
switch (code)
{
/* Some kind of throw to top_level has occurred. */
case FORCE_EOF:
return last_command_exit_value = 127;
case ERREXIT:
case EXITPROG:
return last_command_exit_value;
case DISCARD:
return last_command_exit_value = 1;
default:
command_error ("run_wordexp", CMDERR_BADJUMP, code, 0);
}
}
/* Run it through the parser to get a list of words and expand them */
if (words && *words)
{
with_input_from_string (words, "--wordexp");
if (parse_command () != 0)
return (126);
if (global_command == 0)
{
printf ("0\n0\n");
return (0);
}
if (global_command->type != cm_simple)
return (126);
wl = global_command->value.Simple->words;
if (protected_mode)
for (tl = wl; tl; tl = tl->next)
tl->word->flags |= W_NOCOMSUB|W_NOPROCSUB;
result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
}
else
result = (WORD_LIST *)0;
last_command_exit_value = 0;
if (result == 0)
{
printf ("0\n0\n");
return (0);
}
/* Count up the number of words and bytes, and print them. Don't count
the trailing NUL byte. */
for (nw = nb = 0, wl = result; wl; wl = wl->next)
{
nw++;
nb += strlen (wl->word->word);
}
printf ("%u\n%u\n", nw, nb);
/* Print each word on a separate line. This will have to be changed when
the interface to glibc is completed. */
for (wl = result; wl; wl = wl->next)
printf ("%s\n", wl->word->word);
return (0);
}
#endif
#if defined (ONESHOT)
/* Run one command, given as the argument to the -c option. Tell
parse_and_execute not to fork for a simple command. */
static int
run_one_command (command)
char *command;
{
int code;
code = setjmp_nosigs (top_level);
if (code != NOT_JUMPED)
{
#if defined (PROCESS_SUBSTITUTION)
unlink_fifo_list ();
#endif /* PROCESS_SUBSTITUTION */
switch (code)
{
/* Some kind of throw to top_level has occurred. */
case FORCE_EOF:
return last_command_exit_value = 127;
case ERREXIT:
case EXITPROG:
return last_command_exit_value;
case DISCARD:
return last_command_exit_value = 1;
default:
command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
}
}
return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
}
#endif /* ONESHOT */
static int
bind_args (argv, arg_start, arg_end, start_index)
char **argv;
int arg_start, arg_end, start_index;
{
register int i;
WORD_LIST *args, *tl;
for (i = arg_start, args = tl = (WORD_LIST *)NULL; i < arg_end; i++)
{
if (args == 0)
args = tl = make_word_list (make_word (argv[i]), args);
else
{
tl->next = make_word_list (make_word (argv[i]), (WORD_LIST *)NULL);
tl = tl->next;
}
}
if (args)
{
if (start_index == 0) /* bind to $0...$n for sh -c command */
{
/* Posix.2 4.56.3 says that the first argument after sh -c command
becomes $0, and the rest of the arguments become $1...$n */
shell_name = savestring (args->word->word);
FREE (dollar_vars[0]);
dollar_vars[0] = savestring (args->word->word);
remember_args (args->next, 1);
if (debugging_mode)
{
push_args (args->next); /* BASH_ARGV and BASH_ARGC */
bash_argv_initialized = 1;
}
}
else /* bind to $1...$n for shell script */
{
remember_args (args, 1);
/* We do this unconditionally so something like -O extdebug doesn't
do it first. We're setting the definitive positional params
here. */
if (debugging_mode)
{
push_args (args); /* BASH_ARGV and BASH_ARGC */
bash_argv_initialized = 1;
}
}
dispose_words (args);
}
return (i);
}
void
unbind_args ()
{
remember_args ((WORD_LIST *)NULL, 1);
pop_args (); /* Reset BASH_ARGV and BASH_ARGC */
}
static void
start_debugger ()
{
#if defined (DEBUGGER) && defined (DEBUGGER_START_FILE)
int old_errexit;
int r;
old_errexit = exit_immediately_on_error;
exit_immediately_on_error = 0;
r = force_execute_file (DEBUGGER_START_FILE, 1);
if (r < 0)
{
internal_warning (_("cannot start debugger; debugging mode disabled"));
debugging_mode = 0;
}
error_trace_mode = function_trace_mode = debugging_mode;
set_shellopts ();
set_bashopts ();
exit_immediately_on_error += old_errexit;
#endif
}
static int
open_shell_script (script_name)
char *script_name;
{
int fd, e, fd_is_tty;
char *filename, *path_filename, *t;
char sample[80];
int sample_len;
struct stat sb;
#if defined (ARRAY_VARS)
SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
#endif
filename = savestring (script_name);
fd = open (filename, O_RDONLY);
if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
{
e = errno;
/* If it's not in the current directory, try looking through PATH
for it. */
path_filename = find_path_file (script_name);
if (path_filename)
{
free (filename);
filename = path_filename;
fd = open (filename, O_RDONLY);
}
else
errno = e;
}
if (fd < 0)
{
e = errno;
file_error (filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
sh_exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
}
free (dollar_vars[0]);
dollar_vars[0] = exec_argv0 ? savestring (exec_argv0) : savestring (script_name);
if (exec_argv0)
{
free (exec_argv0);
exec_argv0 = (char *)NULL;
}
if (file_isdir (filename))
{
#if defined (EISDIR)
errno = EISDIR;
#else
errno = EINVAL;
#endif
file_error (filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
sh_exit (EX_NOINPUT);
}
#if defined (ARRAY_VARS)
GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
array_push (bash_source_a, filename);
if (bash_lineno_a)
{
t = itos (executing_line_number ());
array_push (bash_lineno_a, t);
free (t);
}
array_push (funcname_a, "main");
#endif
#ifdef HAVE_DEV_FD
fd_is_tty = isatty (fd);
#else
fd_is_tty = 0;
#endif
/* Only do this with non-tty file descriptors we can seek on. */
if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
{
/* Check to see if the `file' in `bash file' is a binary file
according to the same tests done by execute_simple_command (),
and report an error and exit if it is. */
sample_len = read (fd, sample, sizeof (sample));
if (sample_len < 0)
{
e = errno;
if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
{
#if defined (EISDIR)
errno = EISDIR;
file_error (filename);
#else
internal_error (_("%s: Is a directory"), filename);
#endif
}
else
{
errno = e;
file_error (filename);
}
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
exit (EX_NOEXEC);
}
else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
{
internal_error (_("%s: cannot execute binary file"), filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
exit (EX_BINARY_FILE);
}
/* Now rewind the file back to the beginning. */
lseek (fd, 0L, 0);
}
/* Open the script. But try to move the file descriptor to a randomly
large one, in the hopes that any descriptors used by the script will
not match with ours. */
fd = move_to_high_fd (fd, 1, -1);
#if defined (BUFFERED_INPUT)
default_buffered_input = fd;
SET_CLOSE_ON_EXEC (default_buffered_input);
#else /* !BUFFERED_INPUT */
default_input = fdopen (fd, "r");
if (default_input == 0)
{
file_error (filename);
exit (EX_NOTFOUND);
}
SET_CLOSE_ON_EXEC (fd);
if (fileno (default_input) != fd)
SET_CLOSE_ON_EXEC (fileno (default_input));
#endif /* !BUFFERED_INPUT */
/* Just about the only way for this code to be executed is if something
like `bash -i /dev/stdin' is executed. */
if (interactive_shell && fd_is_tty)
{
dup2 (fd, 0);
close (fd);
fd = 0;
#if defined (BUFFERED_INPUT)
default_buffered_input = 0;
#else
fclose (default_input);
default_input = stdin;
#endif
}
else if (forced_interactive && fd_is_tty == 0)
/* But if a script is called with something like `bash -i scriptname',
we need to do a non-interactive setup here, since we didn't do it
before. */
init_interactive_script ();
free (filename);
reading_shell_script = 1;
return (fd);
}
/* Initialize the input routines for the parser. */
static void
set_bash_input ()
{
/* Make sure the fd from which we are reading input is not in
no-delay mode. */
#if defined (BUFFERED_INPUT)
if (interactive == 0)
sh_unset_nodelay_mode (default_buffered_input);
else
#endif /* !BUFFERED_INPUT */
sh_unset_nodelay_mode (fileno (stdin));
/* with_input_from_stdin really means `with_input_from_readline' */
if (interactive && no_line_editing == 0)
with_input_from_stdin ();
#if defined (BUFFERED_INPUT)
else if (interactive == 0)
with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
#endif /* BUFFERED_INPUT */
else
with_input_from_stream (default_input, dollar_vars[0]);
}
/* Close the current shell script input source and forget about it. This is
extern so execute_cmd.c:initialize_subshell() can call it. If CHECK_ZERO
is non-zero, we close default_buffered_input even if it's the standard
input (fd 0). */
void
unset_bash_input (check_zero)
int check_zero;
{
#if defined (BUFFERED_INPUT)
if ((check_zero && default_buffered_input >= 0) ||
(check_zero == 0 && default_buffered_input > 0))
{
close_buffered_fd (default_buffered_input);
default_buffered_input = bash_input.location.buffered_fd = -1;
bash_input.type = st_none; /* XXX */
}
#else /* !BUFFERED_INPUT */
if (default_input)
{
fclose (default_input);
default_input = (FILE *)NULL;
}
#endif /* !BUFFERED_INPUT */
}
#if !defined (PROGRAM)
# define PROGRAM "bash"
#endif
static void
set_shell_name (argv0)
char *argv0;
{
/* Here's a hack. If the name of this shell is "sh", then don't do
any startup files; just try to be more like /bin/sh. */
shell_name = argv0 ? base_pathname (argv0) : PROGRAM;
if (argv0 && *argv0 == '-')
{
if (*shell_name == '-')
shell_name++;
login_shell = 1;
}
if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
act_like_sh++;
if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
su_shell++;
shell_name = argv0 ? argv0 : PROGRAM;
FREE (dollar_vars[0]);
dollar_vars[0] = savestring (shell_name);
/* A program may start an interactive shell with
"execl ("/bin/bash", "-", NULL)".
If so, default the name of this shell to our name. */
if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
shell_name = PROGRAM;
}
static void
init_interactive ()
{
expand_aliases = interactive_shell = startup_state = 1;
interactive = 1;
#if defined (HISTORY)
remember_on_history = enable_history_list = 1; /* XXX */
# if defined (BANG_HISTORY)
histexp_flag = history_expansion; /* XXX */
# endif
#endif
}
static void
init_noninteractive ()
{
#if defined (HISTORY)
bash_history_reinit (0);
#endif /* HISTORY */
interactive_shell = startup_state = interactive = 0;
expand_aliases = posixly_correct; /* XXX - was 0 not posixly_correct */
no_line_editing = 1;
#if defined (JOB_CONTROL)
/* Even if the shell is not interactive, enable job control if the -i or
-m option is supplied at startup. */
set_job_control (forced_interactive||jobs_m_flag);
#endif /* JOB_CONTROL */
}
static void
init_interactive_script ()
{
init_noninteractive ();
expand_aliases = interactive_shell = startup_state = 1;
#if defined (HISTORY)
remember_on_history = enable_history_list = 1; /* XXX */
#endif
}
void
get_current_user_info ()
{
struct passwd *entry;
/* Don't fetch this more than once. */
if (current_user.user_name == 0)
{
#if defined (__TANDEM)
entry = getpwnam (getlogin ());
#else
entry = getpwuid (current_user.uid);
#endif
if (entry)
{
current_user.user_name = savestring (entry->pw_name);
current_user.shell = (entry->pw_shell && entry->pw_shell[0])
? savestring (entry->pw_shell)
: savestring ("/bin/sh");
current_user.home_dir = savestring (entry->pw_dir);
}
else
{
current_user.user_name = _("I have no name!");
current_user.user_name = savestring (current_user.user_name);
current_user.shell = savestring ("/bin/sh");
current_user.home_dir = savestring ("/");
}
#if defined (HAVE_GETPWENT)
endpwent ();
#endif
}
}
/* Do whatever is necessary to initialize the shell.
Put new initializations in here. */
static void
shell_initialize ()
{
char hostname[256];
int should_be_restricted;
/* Line buffer output for stderr and stdout. */
if (shell_initialized == 0)
{
sh_setlinebuf (stderr);
sh_setlinebuf (stdout);
}
/* Sort the array of shell builtins so that the binary search in
find_shell_builtin () works correctly. */
initialize_shell_builtins ();
/* Initialize the trap signal handlers before installing our own
signal handlers. traps.c:restore_original_signals () is responsible
for restoring the original default signal handlers. That function
is called when we make a new child. */
initialize_traps ();
initialize_signals (0);
/* It's highly unlikely that this will change. */
if (current_host_name == 0)
{
/* Initialize current_host_name. */
if (gethostname (hostname, 255) < 0)
current_host_name = "??host??";
else
current_host_name = savestring (hostname);
}
/* Initialize the stuff in current_user that comes from the password
file. We don't need to do this right away if the shell is not
interactive. */
if (interactive_shell)
get_current_user_info ();
/* Initialize our interface to the tilde expander. */
tilde_initialize ();
#if defined (RESTRICTED_SHELL)
should_be_restricted = shell_is_restricted (shell_name);
#endif
/* Initialize internal and environment variables. Don't import shell
functions from the environment if we are running in privileged or
restricted mode or if the shell is running setuid. */
#if defined (RESTRICTED_SHELL)
initialize_shell_variables (shell_environment, privileged_mode||restricted||should_be_restricted||running_setuid);
#else
initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
#endif
/* Initialize the data structures for storing and running jobs. */
initialize_job_control (jobs_m_flag);
/* Initialize input streams to null. */
initialize_bash_input ();
initialize_flags ();
/* Initialize the shell options. Don't import the shell options
from the environment variables $SHELLOPTS or $BASHOPTS if we are
running in privileged or restricted mode or if the shell is running
setuid. */
#if defined (RESTRICTED_SHELL)
initialize_shell_options (privileged_mode||restricted||should_be_restricted||running_setuid);
initialize_bashopts (privileged_mode||restricted||should_be_restricted||running_setuid);
#else
initialize_shell_options (privileged_mode||running_setuid);
initialize_bashopts (privileged_mode||running_setuid);
#endif
}
/* Function called by main () when it appears that the shell has already
had some initialization performed. This is supposed to reset the world
back to a pristine state, as if we had been exec'ed. */
static void
shell_reinitialize ()
{
/* The default shell prompts. */
primary_prompt = PPROMPT;
secondary_prompt = SPROMPT;
/* Things that get 1. */
current_command_number = 1;
/* We have decided that the ~/.bashrc file should not be executed
for the invocation of each shell script. If the variable $ENV
(or $BASH_ENV) is set, its value is used as the name of a file
to source. */
no_rc = no_profile = 1;
/* Things that get 0. */
login_shell = make_login_shell = interactive = executing = 0;
debugging = do_version = line_number = last_command_exit_value = 0;
forced_interactive = interactive_shell = 0;
subshell_environment = running_in_background = 0;
expand_aliases = 0;
bash_argv_initialized = 0;
/* XXX - should we set jobs_m_flag to 0 here? */
#if defined (HISTORY)
bash_history_reinit (enable_history_list = 0);
#endif /* HISTORY */
#if defined (RESTRICTED_SHELL)
restricted = 0;
#endif /* RESTRICTED_SHELL */
/* Ensure that the default startup file is used. (Except that we don't
execute this file for reinitialized shells). */
bashrc_file = DEFAULT_BASHRC;
/* Delete all variables and functions. They will be reinitialized when
the environment is parsed. */
delete_all_contexts (shell_variables);
delete_all_variables (shell_functions);
reinit_special_variables ();
#if defined (READLINE)
bashline_reinitialize ();
#endif
shell_reinitialized = 1;
}
static void
show_shell_usage (fp, extra)
FILE *fp;
int extra;
{
int i;
char *set_opts, *s, *t;
if (extra)
fprintf (fp, _("GNU bash, version %s-(%s)\n"), shell_version_string (), MACHTYPE);
fprintf (fp, _("Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n"),
shell_name, shell_name);
fputs (_("GNU long options:\n"), fp);
for (i = 0; long_args[i].name; i++)
fprintf (fp, "\t--%s\n", long_args[i].name);
fputs (_("Shell options:\n"), fp);
fputs (_("\t-ilrsD or -c command or -O shopt_option\t\t(invocation only)\n"), fp);
for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
if (STREQ (shell_builtins[i].name, "set"))
{
set_opts = savestring (shell_builtins[i].short_doc);
break;
}
if (set_opts)
{
s = strchr (set_opts, '[');
if (s == 0)
s = set_opts;
while (*++s == '-')
;
t = strchr (s, ']');
if (t)
*t = '\0';
fprintf (fp, _("\t-%s or -o option\n"), s);
free (set_opts);
}
if (extra)
{
fprintf (fp, _("Type `%s -c \"help set\"' for more information about shell options.\n"), shell_name);
fprintf (fp, _("Type `%s -c help' for more information about shell builtin commands.\n"), shell_name);
fprintf (fp, _("Use the `bashbug' command to report bugs.\n"));
fprintf (fp, "\n");
fprintf (fp, _("bash home page: <http://www.gnu.org/software/bash>\n"));
fprintf (fp, _("General help using GNU software: <http://www.gnu.org/gethelp/>\n"));
}
}
static void
add_shopt_to_alist (opt, on_or_off)
char *opt;
int on_or_off;
{
if (shopt_ind >= shopt_len)
{
shopt_len += 8;
shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
}
shopt_alist[shopt_ind].word = opt;
shopt_alist[shopt_ind].token = on_or_off;
shopt_ind++;
}
static void
run_shopt_alist ()
{
register int i;
for (i = 0; i < shopt_ind; i++)
if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
exit (EX_BADUSAGE);
free (shopt_alist);
shopt_alist = 0;
shopt_ind = shopt_len = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-273/c/good_1198_11 |
crossvul-cpp_data_bad_1198_10 | /* pathexp.c -- The shell interface to the globbing library. */
/* Copyright (C) 1995-2014 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "bashtypes.h"
#include <stdio.h>
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashansi.h"
#include "shell.h"
#include "pathexp.h"
#include "flags.h"
#include "shmbutil.h"
#include "bashintl.h"
#include <glob/strmatch.h>
static int glob_name_is_acceptable __P((const char *));
static void ignore_globbed_names __P((char **, sh_ignore_func_t *));
static char *split_ignorespec __P((char *, int *));
#if defined (USE_POSIX_GLOB_LIBRARY)
# include <glob.h>
typedef int posix_glob_errfunc_t __P((const char *, int));
#else
# include <glob/glob.h>
#endif
/* Control whether * matches .files in globbing. */
int glob_dot_filenames;
/* Control whether the extended globbing features are enabled. */
int extended_glob = EXTGLOB_DEFAULT;
/* Control enabling special handling of `**' */
int glob_star = 0;
/* Do we handle backslashes in patterns the way Posix specifies? */
int posix_glob_backslash = 1;
/* Return nonzero if STRING has any unquoted special globbing chars in it. */
int
unquoted_glob_pattern_p (string)
register char *string;
{
register int c;
char *send;
int open, bsquote;
DECLARE_MBSTATE;
open = bsquote = 0;
send = string + strlen (string);
while (c = *string++)
{
switch (c)
{
case '?':
case '*':
return (1);
case '[':
open++;
continue;
case ']':
if (open)
return (1);
continue;
case '+':
case '@':
case '!':
if (*string == '(') /*)*/
return (1);
continue;
/* A pattern can't end with a backslash, but a backslash in the pattern
can be removed by the matching engine, so we have to run it through
globbing. */
case '\\':
if (*string != '\0' && *string != '/')
{
bsquote = 1;
string++;
continue;
}
else if (*string == 0)
return (0);
case CTLESC:
if (*string++ == '\0')
return (0);
}
/* Advance one fewer byte than an entire multibyte character to
account for the auto-increment in the loop above. */
#ifdef HANDLE_MULTIBYTE
string--;
ADVANCE_CHAR_P (string, send - string);
string++;
#else
ADVANCE_CHAR_P (string, send - string);
#endif
}
return ((bsquote && posix_glob_backslash) ? 2 : 0);
}
/* Return 1 if C is a character that is `special' in a POSIX ERE and needs to
be quoted to match itself. */
static inline int
ere_char (c)
int c;
{
switch (c)
{
case '.':
case '[':
case '\\':
case '(':
case ')':
case '*':
case '+':
case '?':
case '{':
case '|':
case '^':
case '$':
return 1;
default:
return 0;
}
return (0);
}
int
glob_char_p (s)
const char *s;
{
switch (*s)
{
case '*':
case '[':
case ']':
case '?':
case '\\':
return 1;
case '+':
case '@':
case '!':
if (s[1] == '(') /*(*/
return 1;
break;
}
return 0;
}
/* PATHNAME can contain characters prefixed by CTLESC; this indicates
that the character is to be quoted. We quote it here in the style
that the glob library recognizes. If flags includes QGLOB_CVTNULL,
we change quoted null strings (pathname[0] == CTLNUL) into empty
strings (pathname[0] == 0). If this is called after quote removal
is performed, (flags & QGLOB_CVTNULL) should be 0; if called when quote
removal has not been done (for example, before attempting to match a
pattern while executing a case statement), flags should include
QGLOB_CVTNULL. If flags includes QGLOB_CTLESC, we need to remove CTLESC
quoting CTLESC or CTLNUL (as if dequote_string were called). If flags
includes QGLOB_FILENAME, appropriate quoting to match a filename should be
performed. QGLOB_REGEXP means we're quoting for a Posix ERE (for
[[ string =~ pat ]]) and that requires some special handling. */
char *
quote_string_for_globbing (pathname, qflags)
const char *pathname;
int qflags;
{
char *temp;
register int i, j;
int cclass, collsym, equiv, c, last_was_backslash;
int savei, savej;
temp = (char *)xmalloc (2 * strlen (pathname) + 1);
if ((qflags & QGLOB_CVTNULL) && QUOTED_NULL (pathname))
{
temp[0] = '\0';
return temp;
}
cclass = collsym = equiv = last_was_backslash = 0;
for (i = j = 0; pathname[i]; i++)
{
/* Fix for CTLESC at the end of the string? */
if (pathname[i] == CTLESC && pathname[i+1] == '\0')
{
temp[j++] = pathname[i++];
break;
}
/* If we are parsing regexp, turn CTLESC CTLESC into CTLESC. It's not an
ERE special character, so we should just be able to pass it through. */
else if ((qflags & (QGLOB_REGEXP|QGLOB_CTLESC)) && pathname[i] == CTLESC && (pathname[i+1] == CTLESC || pathname[i+1] == CTLNUL))
{
i++;
temp[j++] = pathname[i];
continue;
}
else if (pathname[i] == CTLESC)
{
if ((qflags & QGLOB_FILENAME) && pathname[i+1] == '/')
continue;
/* What to do if preceding char is backslash? */
if (pathname[i+1] != CTLESC && (qflags & QGLOB_REGEXP) && ere_char (pathname[i+1]) == 0)
continue;
temp[j++] = '\\';
i++;
if (pathname[i] == '\0')
break;
}
else if ((qflags & QGLOB_REGEXP) && (i == 0 || pathname[i-1] != CTLESC) && pathname[i] == '[') /*]*/
{
temp[j++] = pathname[i++]; /* open bracket */
savej = j;
savei = i;
c = pathname[i++]; /* c == char after open bracket */
if (c == '^') /* ignore pattern negation */
{
temp[j++] = c;
c = pathname[i++];
}
if (c == ']') /* ignore right bracket if first char */
{
temp[j++] = c;
c = pathname[i++];
}
do
{
if (c == 0)
goto endpat;
else if (c == CTLESC)
{
/* skip c, check for EOS, let assignment at end of loop */
/* pathname[i] == backslash-escaped character */
if (pathname[i] == 0)
goto endpat;
temp[j++] = pathname[i++];
}
else if (c == '[' && pathname[i] == ':')
{
temp[j++] = c;
temp[j++] = pathname[i++];
cclass = 1;
}
else if (cclass && c == ':' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
cclass = 0;
}
else if (c == '[' && pathname[i] == '=')
{
temp[j++] = c;
temp[j++] = pathname[i++];
if (pathname[i] == ']')
temp[j++] = pathname[i++]; /* right brack can be in equiv */
equiv = 1;
}
else if (equiv && c == '=' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
equiv = 0;
}
else if (c == '[' && pathname[i] == '.')
{
temp[j++] = c;
temp[j++] = pathname[i++];
if (pathname[i] == ']')
temp[j++] = pathname[i++]; /* right brack can be in collsym */
collsym = 1;
}
else if (collsym && c == '.' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
collsym = 0;
}
else
temp[j++] = c;
}
while (((c = pathname[i++]) != ']') && c != 0);
/* If we don't find the closing bracket before we hit the end of
the string, rescan string without treating it as a bracket
expression (has implications for backslash and special ERE
chars) */
if (c == 0)
{
i = savei - 1; /* -1 for autoincrement above */
j = savej;
continue;
}
temp[j++] = c; /* closing right bracket */
i--; /* increment will happen above in loop */
continue; /* skip double assignment below */
}
else if (pathname[i] == '\\' && (qflags & QGLOB_REGEXP) == 0)
{
/* XXX - if not quoting regexp, use backslash as quote char. Should
we just pass it through without treating it as special? That is
what ksh93 seems to do. */
/* If we want to pass through backslash unaltered, comment out these
lines. */
temp[j++] = '\\';
i++;
if (pathname[i] == '\0')
break;
/* If we are turning CTLESC CTLESC into CTLESC, we need to do that
even when the first CTLESC is preceded by a backslash. */
if ((qflags & QGLOB_CTLESC) && pathname[i] == CTLESC && (pathname[i+1] == CTLESC || pathname[i+1] == CTLNUL))
i++; /* skip over the CTLESC */
}
else if (pathname[i] == '\\' && (qflags & QGLOB_REGEXP))
last_was_backslash = 1;
temp[j++] = pathname[i];
}
endpat:
temp[j] = '\0';
return (temp);
}
char *
quote_globbing_chars (string)
const char *string;
{
size_t slen;
char *temp, *t;
const char *s, *send;
DECLARE_MBSTATE;
slen = strlen (string);
send = string + slen;
temp = (char *)xmalloc (slen * 2 + 1);
for (t = temp, s = string; *s; )
{
if (glob_char_p (s))
*t++ = '\\';
/* Copy a single (possibly multibyte) character from s to t,
incrementing both. */
COPY_CHAR_P (t, s, send);
}
*t = '\0';
return temp;
}
/* Call the glob library to do globbing on PATHNAME. */
char **
shell_glob_filename (pathname)
const char *pathname;
{
#if defined (USE_POSIX_GLOB_LIBRARY)
register int i;
char *temp, **results;
glob_t filenames;
int glob_flags;
temp = quote_string_for_globbing (pathname, QGLOB_FILENAME);
filenames.gl_offs = 0;
# if defined (GLOB_PERIOD)
glob_flags = glob_dot_filenames ? GLOB_PERIOD : 0;
# else
glob_flags = 0;
# endif /* !GLOB_PERIOD */
glob_flags |= (GLOB_ERR | GLOB_DOOFFS);
i = glob (temp, glob_flags, (posix_glob_errfunc_t *)NULL, &filenames);
free (temp);
if (i == GLOB_NOSPACE || i == GLOB_ABORTED)
return ((char **)NULL);
else if (i == GLOB_NOMATCH)
filenames.gl_pathv = (char **)NULL;
else if (i != 0) /* other error codes not in POSIX.2 */
filenames.gl_pathv = (char **)NULL;
results = filenames.gl_pathv;
if (results && ((GLOB_FAILED (results)) == 0))
{
if (should_ignore_glob_matches ())
ignore_glob_matches (results);
if (results && results[0])
strvec_sort (results);
else
{
FREE (results);
results = (char **)NULL;
}
}
return (results);
#else /* !USE_POSIX_GLOB_LIBRARY */
char *temp, **results;
int gflags, quoted_pattern;
noglob_dot_filenames = glob_dot_filenames == 0;
temp = quote_string_for_globbing (pathname, QGLOB_FILENAME);
quoted_pattern = STREQ (pathname, temp) == 0;
gflags = glob_star ? GX_GLOBSTAR : 0;
results = glob_filename (temp, gflags);
free (temp);
if (results && ((GLOB_FAILED (results)) == 0))
{
if (should_ignore_glob_matches ())
ignore_glob_matches (results);
if (results && results[0])
strvec_sort (results);
else
{
FREE (results);
results = (char **)&glob_error_return;
}
}
return (results);
#endif /* !USE_POSIX_GLOB_LIBRARY */
}
/* Stuff for GLOBIGNORE. */
static struct ignorevar globignore =
{
"GLOBIGNORE",
(struct ign *)0,
0,
(char *)0,
(sh_iv_item_func_t *)0,
};
/* Set up to ignore some glob matches because the value of GLOBIGNORE
has changed. If GLOBIGNORE is being unset, we also need to disable
the globbing of filenames beginning with a `.'. */
void
setup_glob_ignore (name)
char *name;
{
char *v;
v = get_string_value (name);
setup_ignore_patterns (&globignore);
if (globignore.num_ignores)
glob_dot_filenames = 1;
else if (v == 0)
glob_dot_filenames = 0;
}
int
should_ignore_glob_matches ()
{
return globignore.num_ignores;
}
/* Return 0 if NAME matches a pattern in the globignore.ignores list. */
static int
glob_name_is_acceptable (name)
const char *name;
{
struct ign *p;
int flags;
/* . and .. are never matched */
if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
return (0);
flags = FNM_PATHNAME | FNMATCH_EXTFLAG | FNMATCH_NOCASEGLOB;
for (p = globignore.ignores; p->val; p++)
{
if (strmatch (p->val, (char *)name, flags) != FNM_NOMATCH)
return (0);
}
return (1);
}
/* Internal function to test whether filenames in NAMES should be
ignored. NAME_FUNC is a pointer to a function to call with each
name. It returns non-zero if the name is acceptable to the particular
ignore function which called _ignore_names; zero if the name should
be removed from NAMES. */
static void
ignore_globbed_names (names, name_func)
char **names;
sh_ignore_func_t *name_func;
{
char **newnames;
int n, i;
for (i = 0; names[i]; i++)
;
newnames = strvec_create (i + 1);
for (n = i = 0; names[i]; i++)
{
if ((*name_func) (names[i]))
newnames[n++] = names[i];
else
free (names[i]);
}
newnames[n] = (char *)NULL;
if (n == 0)
{
names[0] = (char *)NULL;
free (newnames);
return;
}
/* Copy the acceptable names from NEWNAMES back to NAMES and set the
new array end. */
for (n = 0; newnames[n]; n++)
names[n] = newnames[n];
names[n] = (char *)NULL;
free (newnames);
}
void
ignore_glob_matches (names)
char **names;
{
if (globignore.num_ignores == 0)
return;
ignore_globbed_names (names, glob_name_is_acceptable);
}
static char *
split_ignorespec (s, ip)
char *s;
int *ip;
{
char *t;
int n, i;
if (s == 0)
return 0;
i = *ip;
if (s[i] == 0)
return 0;
n = skip_to_delim (s, i, ":", SD_NOJMP|SD_EXTGLOB|SD_GLOB);
t = substring (s, i, n);
if (s[n] == ':')
n++;
*ip = n;
return t;
}
void
setup_ignore_patterns (ivp)
struct ignorevar *ivp;
{
int numitems, maxitems, ptr;
char *colon_bit, *this_ignoreval;
struct ign *p;
this_ignoreval = get_string_value (ivp->varname);
/* If nothing has changed then just exit now. */
if ((this_ignoreval && ivp->last_ignoreval && STREQ (this_ignoreval, ivp->last_ignoreval)) ||
(!this_ignoreval && !ivp->last_ignoreval))
return;
/* Oops. The ignore variable has changed. Re-parse it. */
ivp->num_ignores = 0;
if (ivp->ignores)
{
for (p = ivp->ignores; p->val; p++)
free(p->val);
free (ivp->ignores);
ivp->ignores = (struct ign *)NULL;
}
if (ivp->last_ignoreval)
{
free (ivp->last_ignoreval);
ivp->last_ignoreval = (char *)NULL;
}
if (this_ignoreval == 0 || *this_ignoreval == '\0')
return;
ivp->last_ignoreval = savestring (this_ignoreval);
numitems = maxitems = ptr = 0;
#if 0
while (colon_bit = extract_colon_unit (this_ignoreval, &ptr))
#else
while (colon_bit = split_ignorespec (this_ignoreval, &ptr))
#endif
{
if (numitems + 1 >= maxitems)
{
maxitems += 10;
ivp->ignores = (struct ign *)xrealloc (ivp->ignores, maxitems * sizeof (struct ign));
}
ivp->ignores[numitems].val = colon_bit;
ivp->ignores[numitems].len = strlen (colon_bit);
ivp->ignores[numitems].flags = 0;
if (ivp->item_func)
(*ivp->item_func) (&ivp->ignores[numitems]);
numitems++;
}
ivp->ignores[numitems].val = (char *)NULL;
ivp->num_ignores = numitems;
}
| ./CrossVul/dataset_final_sorted/CWE-273/c/bad_1198_10 |
crossvul-cpp_data_good_1198_10 | /* pathexp.c -- The shell interface to the globbing library. */
/* Copyright (C) 1995-2014 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "bashtypes.h"
#include <stdio.h>
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashansi.h"
#include "shell.h"
#include "pathexp.h"
#include "flags.h"
#include "shmbutil.h"
#include "bashintl.h"
#include <glob/strmatch.h>
static int glob_name_is_acceptable __P((const char *));
static void ignore_globbed_names __P((char **, sh_ignore_func_t *));
static char *split_ignorespec __P((char *, int *));
#if defined (USE_POSIX_GLOB_LIBRARY)
# include <glob.h>
typedef int posix_glob_errfunc_t __P((const char *, int));
#else
# include <glob/glob.h>
#endif
/* Control whether * matches .files in globbing. */
int glob_dot_filenames;
/* Control whether the extended globbing features are enabled. */
int extended_glob = EXTGLOB_DEFAULT;
/* Control enabling special handling of `**' */
int glob_star = 0;
/* Do we handle backslashes in patterns the way Posix specifies? */
int posix_glob_backslash = 1;
/* Return nonzero if STRING has any unquoted special globbing chars in it.
This is supposed to be called when pathname expansion is performed, so
it implements the rules in Posix 2.13.3, specifically that an unquoted
slash cannot appear in a bracket expression. */
int
unquoted_glob_pattern_p (string)
register char *string;
{
register int c;
char *send;
int open, bsquote;
DECLARE_MBSTATE;
open = bsquote = 0;
send = string + strlen (string);
while (c = *string++)
{
switch (c)
{
case '?':
case '*':
return (1);
case '[':
open++;
continue;
case ']':
if (open) /* XXX - if --open == 0? */
return (1);
continue;
case '/':
if (open)
open = 0;
case '+':
case '@':
case '!':
if (*string == '(') /*)*/
return (1);
continue;
/* A pattern can't end with a backslash, but a backslash in the pattern
can be removed by the matching engine, so we have to run it through
globbing. */
case '\\':
if (*string != '\0' && *string != '/')
{
bsquote = 1;
string++;
continue;
}
else if (open && *string == '/')
{
string++; /* quoted slashes in bracket expressions are ok */
continue;
}
else if (*string == 0)
return (0);
case CTLESC:
if (*string++ == '\0')
return (0);
}
/* Advance one fewer byte than an entire multibyte character to
account for the auto-increment in the loop above. */
#ifdef HANDLE_MULTIBYTE
string--;
ADVANCE_CHAR_P (string, send - string);
string++;
#else
ADVANCE_CHAR_P (string, send - string);
#endif
}
return ((bsquote && posix_glob_backslash) ? 2 : 0);
}
/* Return 1 if C is a character that is `special' in a POSIX ERE and needs to
be quoted to match itself. */
static inline int
ere_char (c)
int c;
{
switch (c)
{
case '.':
case '[':
case '\\':
case '(':
case ')':
case '*':
case '+':
case '?':
case '{':
case '|':
case '^':
case '$':
return 1;
default:
return 0;
}
return (0);
}
int
glob_char_p (s)
const char *s;
{
switch (*s)
{
case '*':
case '[':
case ']':
case '?':
case '\\':
return 1;
case '+':
case '@':
case '!':
if (s[1] == '(') /*(*/
return 1;
break;
}
return 0;
}
/* PATHNAME can contain characters prefixed by CTLESC; this indicates
that the character is to be quoted. We quote it here in the style
that the glob library recognizes. If flags includes QGLOB_CVTNULL,
we change quoted null strings (pathname[0] == CTLNUL) into empty
strings (pathname[0] == 0). If this is called after quote removal
is performed, (flags & QGLOB_CVTNULL) should be 0; if called when quote
removal has not been done (for example, before attempting to match a
pattern while executing a case statement), flags should include
QGLOB_CVTNULL. If flags includes QGLOB_CTLESC, we need to remove CTLESC
quoting CTLESC or CTLNUL (as if dequote_string were called). If flags
includes QGLOB_FILENAME, appropriate quoting to match a filename should be
performed. QGLOB_REGEXP means we're quoting for a Posix ERE (for
[[ string =~ pat ]]) and that requires some special handling. */
char *
quote_string_for_globbing (pathname, qflags)
const char *pathname;
int qflags;
{
char *temp;
register int i, j;
int cclass, collsym, equiv, c, last_was_backslash;
int savei, savej;
temp = (char *)xmalloc (2 * strlen (pathname) + 1);
if ((qflags & QGLOB_CVTNULL) && QUOTED_NULL (pathname))
{
temp[0] = '\0';
return temp;
}
cclass = collsym = equiv = last_was_backslash = 0;
for (i = j = 0; pathname[i]; i++)
{
/* Fix for CTLESC at the end of the string? */
if (pathname[i] == CTLESC && pathname[i+1] == '\0')
{
temp[j++] = pathname[i++];
break;
}
/* If we are parsing regexp, turn CTLESC CTLESC into CTLESC. It's not an
ERE special character, so we should just be able to pass it through. */
else if ((qflags & (QGLOB_REGEXP|QGLOB_CTLESC)) && pathname[i] == CTLESC && (pathname[i+1] == CTLESC || pathname[i+1] == CTLNUL))
{
i++;
temp[j++] = pathname[i];
continue;
}
else if (pathname[i] == CTLESC)
{
if ((qflags & QGLOB_FILENAME) && pathname[i+1] == '/')
continue;
/* What to do if preceding char is backslash? */
if (pathname[i+1] != CTLESC && (qflags & QGLOB_REGEXP) && ere_char (pathname[i+1]) == 0)
continue;
temp[j++] = '\\';
i++;
if (pathname[i] == '\0')
break;
}
else if ((qflags & QGLOB_REGEXP) && (i == 0 || pathname[i-1] != CTLESC) && pathname[i] == '[') /*]*/
{
temp[j++] = pathname[i++]; /* open bracket */
savej = j;
savei = i;
c = pathname[i++]; /* c == char after open bracket */
if (c == '^') /* ignore pattern negation */
{
temp[j++] = c;
c = pathname[i++];
}
if (c == ']') /* ignore right bracket if first char */
{
temp[j++] = c;
c = pathname[i++];
}
do
{
if (c == 0)
goto endpat;
else if (c == CTLESC)
{
/* skip c, check for EOS, let assignment at end of loop */
/* pathname[i] == backslash-escaped character */
if (pathname[i] == 0)
goto endpat;
temp[j++] = pathname[i++];
}
else if (c == '[' && pathname[i] == ':')
{
temp[j++] = c;
temp[j++] = pathname[i++];
cclass = 1;
}
else if (cclass && c == ':' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
cclass = 0;
}
else if (c == '[' && pathname[i] == '=')
{
temp[j++] = c;
temp[j++] = pathname[i++];
if (pathname[i] == ']')
temp[j++] = pathname[i++]; /* right brack can be in equiv */
equiv = 1;
}
else if (equiv && c == '=' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
equiv = 0;
}
else if (c == '[' && pathname[i] == '.')
{
temp[j++] = c;
temp[j++] = pathname[i++];
if (pathname[i] == ']')
temp[j++] = pathname[i++]; /* right brack can be in collsym */
collsym = 1;
}
else if (collsym && c == '.' && pathname[i] == ']')
{
temp[j++] = c;
temp[j++] = pathname[i++];
collsym = 0;
}
else
temp[j++] = c;
}
while (((c = pathname[i++]) != ']') && c != 0);
/* If we don't find the closing bracket before we hit the end of
the string, rescan string without treating it as a bracket
expression (has implications for backslash and special ERE
chars) */
if (c == 0)
{
i = savei - 1; /* -1 for autoincrement above */
j = savej;
continue;
}
temp[j++] = c; /* closing right bracket */
i--; /* increment will happen above in loop */
continue; /* skip double assignment below */
}
else if (pathname[i] == '\\' && (qflags & QGLOB_REGEXP) == 0)
{
/* XXX - if not quoting regexp, use backslash as quote char. Should
we just pass it through without treating it as special? That is
what ksh93 seems to do. */
/* If we want to pass through backslash unaltered, comment out these
lines. */
temp[j++] = '\\';
i++;
if (pathname[i] == '\0')
break;
/* If we are turning CTLESC CTLESC into CTLESC, we need to do that
even when the first CTLESC is preceded by a backslash. */
if ((qflags & QGLOB_CTLESC) && pathname[i] == CTLESC && (pathname[i+1] == CTLESC || pathname[i+1] == CTLNUL))
i++; /* skip over the CTLESC */
}
else if (pathname[i] == '\\' && (qflags & QGLOB_REGEXP))
last_was_backslash = 1;
temp[j++] = pathname[i];
}
endpat:
temp[j] = '\0';
return (temp);
}
char *
quote_globbing_chars (string)
const char *string;
{
size_t slen;
char *temp, *t;
const char *s, *send;
DECLARE_MBSTATE;
slen = strlen (string);
send = string + slen;
temp = (char *)xmalloc (slen * 2 + 1);
for (t = temp, s = string; *s; )
{
if (glob_char_p (s))
*t++ = '\\';
/* Copy a single (possibly multibyte) character from s to t,
incrementing both. */
COPY_CHAR_P (t, s, send);
}
*t = '\0';
return temp;
}
/* Call the glob library to do globbing on PATHNAME. */
char **
shell_glob_filename (pathname)
const char *pathname;
{
#if defined (USE_POSIX_GLOB_LIBRARY)
register int i;
char *temp, **results;
glob_t filenames;
int glob_flags;
temp = quote_string_for_globbing (pathname, QGLOB_FILENAME);
filenames.gl_offs = 0;
# if defined (GLOB_PERIOD)
glob_flags = glob_dot_filenames ? GLOB_PERIOD : 0;
# else
glob_flags = 0;
# endif /* !GLOB_PERIOD */
glob_flags |= (GLOB_ERR | GLOB_DOOFFS);
i = glob (temp, glob_flags, (posix_glob_errfunc_t *)NULL, &filenames);
free (temp);
if (i == GLOB_NOSPACE || i == GLOB_ABORTED)
return ((char **)NULL);
else if (i == GLOB_NOMATCH)
filenames.gl_pathv = (char **)NULL;
else if (i != 0) /* other error codes not in POSIX.2 */
filenames.gl_pathv = (char **)NULL;
results = filenames.gl_pathv;
if (results && ((GLOB_FAILED (results)) == 0))
{
if (should_ignore_glob_matches ())
ignore_glob_matches (results);
if (results && results[0])
strvec_sort (results);
else
{
FREE (results);
results = (char **)NULL;
}
}
return (results);
#else /* !USE_POSIX_GLOB_LIBRARY */
char *temp, **results;
int gflags, quoted_pattern;
noglob_dot_filenames = glob_dot_filenames == 0;
temp = quote_string_for_globbing (pathname, QGLOB_FILENAME);
quoted_pattern = STREQ (pathname, temp) == 0;
gflags = glob_star ? GX_GLOBSTAR : 0;
results = glob_filename (temp, gflags);
free (temp);
if (results && ((GLOB_FAILED (results)) == 0))
{
if (should_ignore_glob_matches ())
ignore_glob_matches (results);
if (results && results[0])
strvec_sort (results);
else
{
FREE (results);
results = (char **)&glob_error_return;
}
}
return (results);
#endif /* !USE_POSIX_GLOB_LIBRARY */
}
/* Stuff for GLOBIGNORE. */
static struct ignorevar globignore =
{
"GLOBIGNORE",
(struct ign *)0,
0,
(char *)0,
(sh_iv_item_func_t *)0,
};
/* Set up to ignore some glob matches because the value of GLOBIGNORE
has changed. If GLOBIGNORE is being unset, we also need to disable
the globbing of filenames beginning with a `.'. */
void
setup_glob_ignore (name)
char *name;
{
char *v;
v = get_string_value (name);
setup_ignore_patterns (&globignore);
if (globignore.num_ignores)
glob_dot_filenames = 1;
else if (v == 0)
glob_dot_filenames = 0;
}
int
should_ignore_glob_matches ()
{
return globignore.num_ignores;
}
/* Return 0 if NAME matches a pattern in the globignore.ignores list. */
static int
glob_name_is_acceptable (name)
const char *name;
{
struct ign *p;
int flags;
/* . and .. are never matched */
if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
return (0);
flags = FNM_PATHNAME | FNMATCH_EXTFLAG | FNMATCH_NOCASEGLOB;
for (p = globignore.ignores; p->val; p++)
{
if (strmatch (p->val, (char *)name, flags) != FNM_NOMATCH)
return (0);
}
return (1);
}
/* Internal function to test whether filenames in NAMES should be
ignored. NAME_FUNC is a pointer to a function to call with each
name. It returns non-zero if the name is acceptable to the particular
ignore function which called _ignore_names; zero if the name should
be removed from NAMES. */
static void
ignore_globbed_names (names, name_func)
char **names;
sh_ignore_func_t *name_func;
{
char **newnames;
int n, i;
for (i = 0; names[i]; i++)
;
newnames = strvec_create (i + 1);
for (n = i = 0; names[i]; i++)
{
if ((*name_func) (names[i]))
newnames[n++] = names[i];
else
free (names[i]);
}
newnames[n] = (char *)NULL;
if (n == 0)
{
names[0] = (char *)NULL;
free (newnames);
return;
}
/* Copy the acceptable names from NEWNAMES back to NAMES and set the
new array end. */
for (n = 0; newnames[n]; n++)
names[n] = newnames[n];
names[n] = (char *)NULL;
free (newnames);
}
void
ignore_glob_matches (names)
char **names;
{
if (globignore.num_ignores == 0)
return;
ignore_globbed_names (names, glob_name_is_acceptable);
}
static char *
split_ignorespec (s, ip)
char *s;
int *ip;
{
char *t;
int n, i;
if (s == 0)
return 0;
i = *ip;
if (s[i] == 0)
return 0;
n = skip_to_delim (s, i, ":", SD_NOJMP|SD_EXTGLOB|SD_GLOB);
t = substring (s, i, n);
if (s[n] == ':')
n++;
*ip = n;
return t;
}
void
setup_ignore_patterns (ivp)
struct ignorevar *ivp;
{
int numitems, maxitems, ptr;
char *colon_bit, *this_ignoreval;
struct ign *p;
this_ignoreval = get_string_value (ivp->varname);
/* If nothing has changed then just exit now. */
if ((this_ignoreval && ivp->last_ignoreval && STREQ (this_ignoreval, ivp->last_ignoreval)) ||
(!this_ignoreval && !ivp->last_ignoreval))
return;
/* Oops. The ignore variable has changed. Re-parse it. */
ivp->num_ignores = 0;
if (ivp->ignores)
{
for (p = ivp->ignores; p->val; p++)
free(p->val);
free (ivp->ignores);
ivp->ignores = (struct ign *)NULL;
}
if (ivp->last_ignoreval)
{
free (ivp->last_ignoreval);
ivp->last_ignoreval = (char *)NULL;
}
if (this_ignoreval == 0 || *this_ignoreval == '\0')
return;
ivp->last_ignoreval = savestring (this_ignoreval);
numitems = maxitems = ptr = 0;
#if 0
while (colon_bit = extract_colon_unit (this_ignoreval, &ptr))
#else
while (colon_bit = split_ignorespec (this_ignoreval, &ptr))
#endif
{
if (numitems + 1 >= maxitems)
{
maxitems += 10;
ivp->ignores = (struct ign *)xrealloc (ivp->ignores, maxitems * sizeof (struct ign));
}
ivp->ignores[numitems].val = colon_bit;
ivp->ignores[numitems].len = strlen (colon_bit);
ivp->ignores[numitems].flags = 0;
if (ivp->item_func)
(*ivp->item_func) (&ivp->ignores[numitems]);
numitems++;
}
ivp->ignores[numitems].val = (char *)NULL;
ivp->num_ignores = numitems;
}
| ./CrossVul/dataset_final_sorted/CWE-273/c/good_1198_10 |
crossvul-cpp_data_good_1198_9 | /* glob.c -- file-name wildcard pattern matching for Bash.
Copyright (C) 1985-2019 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne-Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
/* To whomever it may concern: I have never seen the code which most
Unix programs use to perform this function. I wrote this from scratch
based on specifications for the pattern matching. --RMS. */
#include <config.h>
#if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
#pragma alloca
#endif /* _AIX && RISC6000 && !__GNUC__ */
#include "bashtypes.h"
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashansi.h"
#include "posixdir.h"
#include "posixstat.h"
#include "shmbutil.h"
#include "xmalloc.h"
#include "filecntl.h"
#if !defined (F_OK)
# define F_OK 0
#endif
#include "stdc.h"
#include "memalloc.h"
#include <signal.h>
#include "shell.h"
#include "general.h"
#include "glob.h"
#include "strmatch.h"
#if !defined (HAVE_BCOPY) && !defined (bcopy)
# define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
#endif /* !HAVE_BCOPY && !bcopy */
#if !defined (NULL)
# if defined (__STDC__)
# define NULL ((void *) 0)
# else
# define NULL 0x0
# endif /* __STDC__ */
#endif /* !NULL */
#if !defined (FREE)
# define FREE(x) if (x) free (x)
#endif
/* Don't try to alloca() more than this much memory for `struct globval'
in glob_vector() */
#ifndef ALLOCA_MAX
# define ALLOCA_MAX 100000
#endif
struct globval
{
struct globval *next;
char *name;
};
extern void throw_to_top_level __P((void));
extern int sh_eaccess __P((const char *, int));
extern char *sh_makepath __P((const char *, const char *, int));
extern int signal_is_pending __P((int));
extern void run_pending_traps __P((void));
extern int extended_glob;
extern int posix_glob_backslash;
/* Global variable which controls whether or not * matches .*.
Non-zero means don't match .*. */
int noglob_dot_filenames = 1;
/* Global variable which controls whether or not filename globbing
is done without regard to case. */
int glob_ignore_case = 0;
/* Global variable controlling whether globbing ever returns . or ..
regardless of the pattern. If set to 1, no glob pattern will ever
match `.' or `..'. Disabled by default. */
int glob_always_skip_dot_and_dotdot = 0;
/* Global variable to return to signify an error in globbing. */
char *glob_error_return;
static struct globval finddirs_error_return;
/* Some forward declarations. */
static int skipname __P((char *, char *, int));
#if HANDLE_MULTIBYTE
static int mbskipname __P((char *, char *, int));
#endif
#if HANDLE_MULTIBYTE
static void udequote_pathname __P((char *));
static void wdequote_pathname __P((char *));
#else
# define dequote_pathname udequote_pathname
#endif
static void dequote_pathname __P((char *));
static int glob_testdir __P((char *, int));
static char **glob_dir_to_array __P((char *, char **, int));
/* Make sure these names continue to agree with what's in smatch.c */
extern char *glob_patscan __P((char *, char *, int));
extern wchar_t *glob_patscan_wc __P((wchar_t *, wchar_t *, int));
/* And this from gmisc.c/gm_loop.c */
extern int wextglob_pattern_p __P((wchar_t *));
extern char *glob_dirscan __P((char *, int));
/* Compile `glob_loop.c' for single-byte characters. */
#define GCHAR unsigned char
#define CHAR char
#define INT int
#define L(CS) CS
#define INTERNAL_GLOB_PATTERN_P internal_glob_pattern_p
#include "glob_loop.c"
/* Compile `glob_loop.c' again for multibyte characters. */
#if HANDLE_MULTIBYTE
#define GCHAR wchar_t
#define CHAR wchar_t
#define INT wint_t
#define L(CS) L##CS
#define INTERNAL_GLOB_PATTERN_P internal_glob_wpattern_p
#include "glob_loop.c"
#endif /* HANDLE_MULTIBYTE */
/* And now a function that calls either the single-byte or multibyte version
of internal_glob_pattern_p. */
int
glob_pattern_p (pattern)
const char *pattern;
{
#if HANDLE_MULTIBYTE
size_t n;
wchar_t *wpattern;
int r;
if (MB_CUR_MAX == 1 || mbsmbchar (pattern) == 0)
return (internal_glob_pattern_p ((unsigned char *)pattern));
/* Convert strings to wide chars, and call the multibyte version. */
n = xdupmbstowcs (&wpattern, NULL, pattern);
if (n == (size_t)-1)
/* Oops. Invalid multibyte sequence. Try it as single-byte sequence. */
return (internal_glob_pattern_p ((unsigned char *)pattern));
r = internal_glob_wpattern_p (wpattern);
free (wpattern);
return r;
#else
return (internal_glob_pattern_p ((unsigned char *)pattern));
#endif
}
#if EXTENDED_GLOB
/* Return 1 if all subpatterns in the extended globbing pattern PAT indicate
that the name should be skipped. XXX - doesn't handle pattern negation,
not sure if it should */
static int
extglob_skipname (pat, dname, flags)
char *pat, *dname;
int flags;
{
char *pp, *pe, *t, *se;
int n, r, negate, wild, nullpat;
negate = *pat == '!';
wild = *pat == '*' || *pat == '?';
pp = pat + 2;
se = pp + strlen (pp) - 1; /* end of string */
pe = glob_patscan (pp, se, 0); /* end of extglob pattern (( */
/* we should check for invalid extglob pattern here */
if (pe == 0)
return 0;
/* if pe != se we have more of the pattern at the end of the extglob
pattern. Check the easy case first ( */
if (pe == se && *pe == ')' && (t = strchr (pp, '|')) == 0)
{
*pe = '\0';
#if defined (HANDLE_MULTIBYTE)
r = mbskipname (pp, dname, flags);
#else
r = skipname (pp, dname, flags); /*(*/
#endif
*pe = ')';
if (wild && pe[1]) /* if we can match zero instances, check further */
return (skipname (pe+1, dname, flags));
return r;
}
/* Is the extglob pattern between the parens the null pattern? The null
pattern can match nothing, so should we check any remaining portion of
the pattern? */
nullpat = pe >= (pat + 2) && pe[-2] == '(' && pe[-1] == ')';
/* check every subpattern */
while (t = glob_patscan (pp, pe, '|'))
{
n = t[-1]; /* ( */
if (extglob_pattern_p (pp) && n == ')')
t[-1] = n; /* no-op for now */
else
t[-1] = '\0';
#if defined (HANDLE_MULTIBYTE)
r = mbskipname (pp, dname, flags);
#else
r = skipname (pp, dname, flags);
#endif
t[-1] = n;
if (r == 0) /* if any pattern says not skip, we don't skip */
return r;
pp = t;
} /*(*/
/* glob_patscan might find end of string */
if (pp == se)
return r;
/* but if it doesn't then we didn't match a leading dot */
if (wild && *pe) /* if we can match zero instances, check further */
return (skipname (pe, dname, flags));
return 1;
}
#endif
/* Return 1 if DNAME should be skipped according to PAT. Mostly concerned
with matching leading `.'. */
static int
skipname (pat, dname, flags)
char *pat;
char *dname;
int flags;
{
#if EXTENDED_GLOB
if (extglob_pattern_p (pat)) /* XXX */
return (extglob_skipname (pat, dname, flags));
#endif
if (glob_always_skip_dot_and_dotdot && DOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot need not be explicitly matched, and the pattern
doesn't start with a `.', don't match `.' or `..' */
if (noglob_dot_filenames == 0 && pat[0] != '.' &&
(pat[0] != '\\' || pat[1] != '.') &&
DOT_OR_DOTDOT (dname))
return 1;
/* If a dot must be explicitly matched, check to see if they do. */
else if (noglob_dot_filenames && dname[0] == '.' && pat[0] != '.' &&
(pat[0] != '\\' || pat[1] != '.'))
return 1;
return 0;
}
#if HANDLE_MULTIBYTE
static int
wskipname (pat, dname, flags)
wchar_t *pat, *dname;
int flags;
{
if (glob_always_skip_dot_and_dotdot && WDOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot need not be explicitly matched, and the
pattern doesn't start with a `.', don't match `.' or `..' */
if (noglob_dot_filenames == 0 && pat[0] != L'.' &&
(pat[0] != L'\\' || pat[1] != L'.') &&
WDOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot must be explicitly matched, check to see if the
pattern and dirname both have one. */
else if (noglob_dot_filenames && dname[0] == L'.' &&
pat[0] != L'.' &&
(pat[0] != L'\\' || pat[1] != L'.'))
return 1;
return 0;
}
static int
wextglob_skipname (pat, dname, flags)
wchar_t *pat, *dname;
int flags;
{
#if EXTENDED_GLOB
wchar_t *pp, *pe, *t, n, *se;
int r, negate, wild, nullpat;
negate = *pat == L'!';
wild = *pat == L'*' || *pat == L'?';
pp = pat + 2;
se = pp + wcslen (pp) - 1; /*(*/
pe = glob_patscan_wc (pp, se, 0);
if (pe == se && *pe == ')' && (t = wcschr (pp, L'|')) == 0)
{
*pe = L'\0';
r = wskipname (pp, dname, flags); /*(*/
*pe = L')';
if (wild && pe[1] != L'\0')
return (wskipname (pe+1, dname, flags));
return r;
}
/* Is the extglob pattern between the parens the null pattern? The null
pattern can match nothing, so should we check any remaining portion of
the pattern? */
nullpat = pe >= (pat + 2) && pe[-2] == L'(' && pe[-1] == L')';
/* check every subpattern */
while (t = glob_patscan_wc (pp, pe, '|'))
{
n = t[-1]; /* ( */
if (wextglob_pattern_p (pp) && n == L')')
t[-1] = n; /* no-op for now */
else
t[-1] = L'\0';
r = wskipname (pp, dname, flags);
t[-1] = n;
if (r == 0)
return 0;
pp = t;
}
if (pp == pe) /* glob_patscan_wc might find end of pattern */
return r;
/* but if it doesn't then we didn't match a leading dot */
if (wild && *pe != L'\0')
return (wskipname (pe, dname, flags));
return 1;
#else
return (wskipname (pat, dname, flags));
#endif
}
/* Return 1 if DNAME should be skipped according to PAT. Handles multibyte
characters in PAT and DNAME. Mostly concerned with matching leading `.'. */
static int
mbskipname (pat, dname, flags)
char *pat, *dname;
int flags;
{
int ret, ext;
wchar_t *pat_wc, *dn_wc;
size_t pat_n, dn_n;
if (mbsmbchar (dname) == 0 && mbsmbchar (pat) == 0)
return (skipname (pat, dname, flags));
ext = 0;
#if EXTENDED_GLOB
ext = extglob_pattern_p (pat);
#endif
pat_wc = dn_wc = (wchar_t *)NULL;
pat_n = xdupmbstowcs (&pat_wc, NULL, pat);
if (pat_n != (size_t)-1)
dn_n = xdupmbstowcs (&dn_wc, NULL, dname);
ret = 0;
if (pat_n != (size_t)-1 && dn_n !=(size_t)-1)
ret = ext ? wextglob_skipname (pat_wc, dn_wc, flags) : wskipname (pat_wc, dn_wc, flags);
else
ret = skipname (pat, dname, flags);
FREE (pat_wc);
FREE (dn_wc);
return ret;
}
#endif /* HANDLE_MULTIBYTE */
/* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */
static void
udequote_pathname (pathname)
char *pathname;
{
register int i, j;
for (i = j = 0; pathname && pathname[i]; )
{
if (pathname[i] == '\\')
i++;
pathname[j++] = pathname[i++];
if (pathname[i - 1] == 0)
break;
}
if (pathname)
pathname[j] = '\0';
}
#if HANDLE_MULTIBYTE
/* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */
static void
wdequote_pathname (pathname)
char *pathname;
{
mbstate_t ps;
size_t len, n;
wchar_t *wpathname;
int i, j;
wchar_t *orig_wpathname;
if (mbsmbchar (pathname) == 0)
{
udequote_pathname (pathname);
return;
}
len = strlen (pathname);
/* Convert the strings into wide characters. */
n = xdupmbstowcs (&wpathname, NULL, pathname);
if (n == (size_t) -1)
{
/* Something wrong. Fall back to single-byte */
udequote_pathname (pathname);
return;
}
orig_wpathname = wpathname;
for (i = j = 0; wpathname && wpathname[i]; )
{
if (wpathname[i] == L'\\')
i++;
wpathname[j++] = wpathname[i++];
if (wpathname[i - 1] == L'\0')
break;
}
if (wpathname)
wpathname[j] = L'\0';
/* Convert the wide character string into unibyte character set. */
memset (&ps, '\0', sizeof(mbstate_t));
n = wcsrtombs(pathname, (const wchar_t **)&wpathname, len, &ps);
pathname[len] = '\0';
/* Can't just free wpathname here; wcsrtombs changes it in many cases. */
free (orig_wpathname);
}
static void
dequote_pathname (pathname)
char *pathname;
{
if (MB_CUR_MAX > 1)
wdequote_pathname (pathname);
else
udequote_pathname (pathname);
}
#endif /* HANDLE_MULTIBYTE */
/* Test whether NAME exists. */
#if defined (HAVE_LSTAT)
# define GLOB_TESTNAME(name) (lstat (name, &finfo))
#else /* !HAVE_LSTAT */
# if !defined (AFS)
# define GLOB_TESTNAME(name) (sh_eaccess (name, F_OK))
# else /* AFS */
# define GLOB_TESTNAME(name) (access (name, F_OK))
# endif /* AFS */
#endif /* !HAVE_LSTAT */
/* Return 0 if DIR is a directory, -2 if DIR is a symlink, -1 otherwise. */
static int
glob_testdir (dir, flags)
char *dir;
int flags;
{
struct stat finfo;
int r;
/*itrace("glob_testdir: testing %s" flags = %d, dir, flags);*/
#if defined (HAVE_LSTAT)
r = (flags & GX_ALLDIRS) ? lstat (dir, &finfo) : stat (dir, &finfo);
#else
r = stat (dir, &finfo);
#endif
if (r < 0)
return (-1);
#if defined (S_ISLNK)
if (S_ISLNK (finfo.st_mode))
return (-2);
#endif
if (S_ISDIR (finfo.st_mode) == 0)
return (-1);
return (0);
}
/* Recursively scan SDIR for directories matching PAT (PAT is always `**').
FLAGS is simply passed down to the recursive call to glob_vector. Returns
a list of matching directory names. EP, if non-null, is set to the last
element of the returned list. NP, if non-null, is set to the number of
directories in the returned list. These two variables exist for the
convenience of the caller (always glob_vector). */
static struct globval *
finddirs (pat, sdir, flags, ep, np)
char *pat;
char *sdir;
int flags;
struct globval **ep;
int *np;
{
char **r, *n;
int ndirs;
struct globval *ret, *e, *g;
/*itrace("finddirs: pat = `%s' sdir = `%s' flags = 0x%x", pat, sdir, flags);*/
e = ret = 0;
r = glob_vector (pat, sdir, flags);
if (r == 0 || r[0] == 0)
{
if (np)
*np = 0;
if (ep)
*ep = 0;
if (r && r != &glob_error_return)
free (r);
return (struct globval *)0;
}
for (ndirs = 0; r[ndirs] != 0; ndirs++)
{
g = (struct globval *) malloc (sizeof (struct globval));
if (g == 0)
{
while (ret) /* free list built so far */
{
g = ret->next;
free (ret);
ret = g;
}
free (r);
if (np)
*np = 0;
if (ep)
*ep = 0;
return (&finddirs_error_return);
}
if (e == 0)
e = g;
g->next = ret;
ret = g;
g->name = r[ndirs];
}
free (r);
if (ep)
*ep = e;
if (np)
*np = ndirs;
return ret;
}
/* Return a vector of names of files in directory DIR
whose names match glob pattern PAT.
The names are not in any particular order.
Wildcards at the beginning of PAT do not match an initial period.
The vector is terminated by an element that is a null pointer.
To free the space allocated, first free the vector's elements,
then free the vector.
Return 0 if cannot get enough memory to hold the pointer
and the names.
Return -1 if cannot access directory DIR.
Look in errno for more information. */
char **
glob_vector (pat, dir, flags)
char *pat;
char *dir;
int flags;
{
DIR *d;
register struct dirent *dp;
struct globval *lastlink, *e, *dirlist;
register struct globval *nextlink;
register char *nextname, *npat, *subdir;
unsigned int count;
int lose, skip, ndirs, isdir, sdlen, add_current, patlen;
register char **name_vector;
register unsigned int i;
int mflags; /* Flags passed to strmatch (). */
int pflags; /* flags passed to sh_makepath () */
int hasglob; /* return value from glob_pattern_p */
int nalloca;
struct globval *firstmalloc, *tmplink;
char *convfn;
lastlink = 0;
count = lose = skip = add_current = 0;
firstmalloc = 0;
nalloca = 0;
name_vector = NULL;
/*itrace("glob_vector: pat = `%s' dir = `%s' flags = 0x%x", pat, dir, flags);*/
/* If PAT is empty, skip the loop, but return one (empty) filename. */
if (pat == 0 || *pat == '\0')
{
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
nextlink = (struct globval *)alloca (sizeof (struct globval));
if (nextlink == NULL)
return ((char **) NULL);
nextlink->next = (struct globval *)0;
nextname = (char *) malloc (1);
if (nextname == 0)
lose = 1;
else
{
lastlink = nextlink;
nextlink->name = nextname;
nextname[0] = '\0';
count = 1;
}
skip = 1;
}
patlen = (pat && *pat) ? strlen (pat) : 0;
/* If the filename pattern (PAT) does not contain any globbing characters,
or contains a pattern with only backslash escapes (hasglob == 2),
we can dispense with reading the directory, and just see if there is
a filename `DIR/PAT'. If there is, and we can access it, just make the
vector to return and bail immediately. */
hasglob = 0;
if (skip == 0 && (hasglob = glob_pattern_p (pat)) == 0 || hasglob == 2)
{
int dirlen;
struct stat finfo;
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
dirlen = strlen (dir);
nextname = (char *)malloc (dirlen + patlen + 2);
npat = (char *)malloc (patlen + 1);
if (nextname == 0 || npat == 0)
{
FREE (nextname);
FREE (npat);
lose = 1;
}
else
{
strcpy (npat, pat);
dequote_pathname (npat);
strcpy (nextname, dir);
nextname[dirlen++] = '/';
strcpy (nextname + dirlen, npat);
if (GLOB_TESTNAME (nextname) >= 0)
{
free (nextname);
nextlink = (struct globval *)alloca (sizeof (struct globval));
if (nextlink)
{
nextlink->next = (struct globval *)0;
lastlink = nextlink;
nextlink->name = npat;
count = 1;
}
else
{
free (npat);
lose = 1;
}
}
else
{
free (nextname);
free (npat);
}
}
skip = 1;
}
if (skip == 0)
{
/* Open the directory, punting immediately if we cannot. If opendir
is not robust (i.e., it opens non-directories successfully), test
that DIR is a directory and punt if it's not. */
#if defined (OPENDIR_NOT_ROBUST)
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
#endif
d = opendir (dir);
if (d == NULL)
return ((char **) &glob_error_return);
/* Compute the flags that will be passed to strmatch(). We don't
need to do this every time through the loop. */
mflags = (noglob_dot_filenames ? FNM_PERIOD : 0) | FNM_PATHNAME;
#ifdef FNM_CASEFOLD
if (glob_ignore_case)
mflags |= FNM_CASEFOLD;
#endif
if (extended_glob)
mflags |= FNM_EXTMATCH;
add_current = ((flags & (GX_ALLDIRS|GX_ADDCURDIR)) == (GX_ALLDIRS|GX_ADDCURDIR));
/* Scan the directory, finding all names that match.
For each name that matches, allocate a struct globval
on the stack and store the name in it.
Chain those structs together; lastlink is the front of the chain. */
while (1)
{
/* Make globbing interruptible in the shell. */
if (interrupt_state || terminating_signal)
{
lose = 1;
break;
}
else if (signal_is_pending (SIGINT)) /* XXX - make SIGINT traps responsive */
{
lose = 1;
break;
}
dp = readdir (d);
if (dp == NULL)
break;
/* If this directory entry is not to be used, try again. */
if (REAL_DIR_ENTRY (dp) == 0)
continue;
#if 0
if (dp->d_name == 0 || *dp->d_name == 0)
continue;
#endif
#if HANDLE_MULTIBYTE
if (MB_CUR_MAX > 1 && mbskipname (pat, dp->d_name, flags))
continue;
else
#endif
if (skipname (pat, dp->d_name, flags))
continue;
/* If we're only interested in directories, don't bother with files */
if (flags & (GX_MATCHDIRS|GX_ALLDIRS))
{
pflags = (flags & GX_ALLDIRS) ? MP_RMDOT : 0;
if (flags & GX_NULLDIR)
pflags |= MP_IGNDOT;
subdir = sh_makepath (dir, dp->d_name, pflags);
isdir = glob_testdir (subdir, flags);
if (isdir < 0 && (flags & GX_MATCHDIRS))
{
free (subdir);
continue;
}
}
if (flags & GX_ALLDIRS)
{
if (isdir == 0)
{
dirlist = finddirs (pat, subdir, (flags & ~GX_ADDCURDIR), &e, &ndirs);
if (dirlist == &finddirs_error_return)
{
free (subdir);
lose = 1;
break;
}
if (ndirs) /* add recursive directories to list */
{
if (firstmalloc == 0)
firstmalloc = e;
e->next = lastlink;
lastlink = dirlist;
count += ndirs;
}
}
/* XXX - should we even add this if it's not a directory? */
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (firstmalloc == 0)
firstmalloc = nextlink;
sdlen = strlen (subdir);
nextname = (char *) malloc (sdlen + 1);
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
free (subdir);
lose = 1;
break;
}
nextlink->next = lastlink;
lastlink = nextlink;
nextlink->name = nextname;
bcopy (subdir, nextname, sdlen + 1);
free (subdir);
++count;
continue;
}
else if (flags & GX_MATCHDIRS)
free (subdir);
convfn = fnx_fromfs (dp->d_name, D_NAMLEN (dp));
if (strmatch (pat, convfn, mflags) != FNM_NOMATCH)
{
if (nalloca < ALLOCA_MAX)
{
nextlink = (struct globval *) alloca (sizeof (struct globval));
nalloca += sizeof (struct globval);
}
else
{
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (firstmalloc == 0)
firstmalloc = nextlink;
}
nextname = (char *) malloc (D_NAMLEN (dp) + 1);
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
lose = 1;
break;
}
nextlink->next = lastlink;
lastlink = nextlink;
nextlink->name = nextname;
bcopy (dp->d_name, nextname, D_NAMLEN (dp) + 1);
++count;
}
}
(void) closedir (d);
}
/* compat: if GX_ADDCURDIR, add the passed directory also. Add an empty
directory name as a placeholder if GX_NULLDIR (in which case the passed
directory name is "."). */
if (add_current)
{
sdlen = strlen (dir);
nextname = (char *)malloc (sdlen + 1);
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
lose = 1;
}
else
{
nextlink->name = nextname;
nextlink->next = lastlink;
lastlink = nextlink;
if (flags & GX_NULLDIR)
nextname[0] = '\0';
else
bcopy (dir, nextname, sdlen + 1);
++count;
}
}
if (lose == 0)
{
name_vector = (char **) malloc ((count + 1) * sizeof (char *));
lose |= name_vector == NULL;
}
/* Have we run out of memory? */
if (lose)
{
tmplink = 0;
/* Here free the strings we have got. */
while (lastlink)
{
/* Since we build the list in reverse order, the first N entries
will be allocated with malloc, if firstmalloc is set, from
lastlink to firstmalloc. */
if (firstmalloc)
{
if (lastlink == firstmalloc)
firstmalloc = 0;
tmplink = lastlink;
}
else
tmplink = 0;
free (lastlink->name);
lastlink = lastlink->next;
FREE (tmplink);
}
/* Don't call QUIT; here; let higher layers deal with it. */
return ((char **)NULL);
}
/* Copy the name pointers from the linked list into the vector. */
for (tmplink = lastlink, i = 0; i < count; ++i)
{
name_vector[i] = tmplink->name;
tmplink = tmplink->next;
}
name_vector[count] = NULL;
/* If we allocated some of the struct globvals, free them now. */
if (firstmalloc)
{
tmplink = 0;
while (lastlink)
{
tmplink = lastlink;
if (lastlink == firstmalloc)
lastlink = firstmalloc = 0;
else
lastlink = lastlink->next;
free (tmplink);
}
}
return (name_vector);
}
/* Return a new array which is the concatenation of each string in ARRAY
to DIR. This function expects you to pass in an allocated ARRAY, and
it takes care of free()ing that array. Thus, you might think of this
function as side-effecting ARRAY. This should handle GX_MARKDIRS. */
static char **
glob_dir_to_array (dir, array, flags)
char *dir, **array;
int flags;
{
register unsigned int i, l;
int add_slash;
char **result, *new;
struct stat sb;
l = strlen (dir);
if (l == 0)
{
if (flags & GX_MARKDIRS)
for (i = 0; array[i]; i++)
{
if ((stat (array[i], &sb) == 0) && S_ISDIR (sb.st_mode))
{
l = strlen (array[i]);
new = (char *)realloc (array[i], l + 2);
if (new == 0)
return NULL;
new[l] = '/';
new[l+1] = '\0';
array[i] = new;
}
}
return (array);
}
add_slash = dir[l - 1] != '/';
i = 0;
while (array[i] != NULL)
++i;
result = (char **) malloc ((i + 1) * sizeof (char *));
if (result == NULL)
return (NULL);
for (i = 0; array[i] != NULL; i++)
{
/* 3 == 1 for NUL, 1 for slash at end of DIR, 1 for GX_MARKDIRS */
result[i] = (char *) malloc (l + strlen (array[i]) + 3);
if (result[i] == NULL)
{
int ind;
for (ind = 0; ind < i; ind++)
free (result[ind]);
free (result);
return (NULL);
}
strcpy (result[i], dir);
if (add_slash)
result[i][l] = '/';
if (array[i][0])
{
strcpy (result[i] + l + add_slash, array[i]);
if (flags & GX_MARKDIRS)
{
if ((stat (result[i], &sb) == 0) && S_ISDIR (sb.st_mode))
{
size_t rlen;
rlen = strlen (result[i]);
result[i][rlen] = '/';
result[i][rlen+1] = '\0';
}
}
}
else
result[i][l+add_slash] = '\0';
}
result[i] = NULL;
/* Free the input array. */
for (i = 0; array[i] != NULL; i++)
free (array[i]);
free ((char *) array);
return (result);
}
/* Do globbing on PATHNAME. Return an array of pathnames that match,
marking the end of the array with a null-pointer as an element.
If no pathnames match, then the array is empty (first element is null).
If there isn't enough memory, then return NULL.
If a file system error occurs, return -1; `errno' has the error code. */
char **
glob_filename (pathname, flags)
char *pathname;
int flags;
{
char **result, **new_result;
unsigned int result_size;
char *directory_name, *filename, *dname, *fn;
unsigned int directory_len;
int free_dirname; /* flag */
int dflags, hasglob;
result = (char **) malloc (sizeof (char *));
result_size = 1;
if (result == NULL)
return (NULL);
result[0] = NULL;
directory_name = NULL;
/* Find the filename. */
filename = strrchr (pathname, '/');
#if defined (EXTENDED_GLOB)
if (filename && extended_glob)
{
fn = glob_dirscan (pathname, '/');
#if DEBUG_MATCHING
if (fn != filename)
fprintf (stderr, "glob_filename: glob_dirscan: fn (%s) != filename (%s)\n", fn ? fn : "(null)", filename);
#endif
filename = fn;
}
#endif
if (filename == NULL)
{
filename = pathname;
directory_name = "";
directory_len = 0;
free_dirname = 0;
}
else
{
directory_len = (filename - pathname) + 1;
directory_name = (char *) malloc (directory_len + 1);
if (directory_name == 0) /* allocation failed? */
{
free (result);
return (NULL);
}
bcopy (pathname, directory_name, directory_len);
directory_name[directory_len] = '\0';
++filename;
free_dirname = 1;
}
hasglob = 0;
/* If directory_name contains globbing characters, then we
have to expand the previous levels. Just recurse.
If glob_pattern_p returns != [0,1] we have a pattern that has backslash
quotes but no unquoted glob pattern characters. We dequote it below. */
if (directory_len > 0 && (hasglob = glob_pattern_p (directory_name)) == 1)
{
char **directories, *d, *p;
register unsigned int i;
int all_starstar, last_starstar;
all_starstar = last_starstar = 0;
d = directory_name;
dflags = flags & ~GX_MARKDIRS;
/* Collapse a sequence of ** patterns separated by one or more slashes
to a single ** terminated by a slash or NUL */
if ((flags & GX_GLOBSTAR) && d[0] == '*' && d[1] == '*' && (d[2] == '/' || d[2] == '\0'))
{
p = d;
while (d[0] == '*' && d[1] == '*' && (d[2] == '/' || d[2] == '\0'))
{
p = d;
if (d[2])
{
d += 3;
while (*d == '/')
d++;
if (*d == 0)
break;
}
}
if (*d == 0)
all_starstar = 1;
d = p;
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
directory_len = strlen (d);
}
/* If there is a non [star][star]/ component in directory_name, we
still need to collapse trailing sequences of [star][star]/ into
a single one and note that the directory name ends with [star][star],
so we can compensate if filename is [star][star] */
if ((flags & GX_GLOBSTAR) && all_starstar == 0)
{
int dl, prev;
prev = dl = directory_len;
while (dl >= 4 && d[dl - 1] == '/' &&
d[dl - 2] == '*' &&
d[dl - 3] == '*' &&
d[dl - 4] == '/')
prev = dl, dl -= 3;
if (dl != directory_len)
last_starstar = 1;
directory_len = prev;
}
/* If the directory name ends in [star][star]/ but the filename is
[star][star], just remove the final [star][star] from the directory
so we don't have to scan everything twice. */
if (last_starstar && directory_len > 4 &&
filename[0] == '*' && filename[1] == '*' && filename[2] == 0)
{
directory_len -= 3;
}
if (d[directory_len - 1] == '/')
d[directory_len - 1] = '\0';
directories = glob_filename (d, dflags|GX_RECURSE);
if (free_dirname)
{
free (directory_name);
directory_name = NULL;
}
if (directories == NULL)
goto memory_error;
else if (directories == (char **)&glob_error_return)
{
free ((char *) result);
return ((char **) &glob_error_return);
}
else if (*directories == NULL)
{
free ((char *) directories);
free ((char *) result);
return ((char **) &glob_error_return);
}
/* If we have something like [star][star]/[star][star], it's no use to
glob **, then do it again, and throw half the results away. */
if (all_starstar && filename[0] == '*' && filename[1] == '*' && filename[2] == 0)
{
free ((char *) directories);
free (directory_name);
directory_name = NULL;
directory_len = 0;
goto only_filename;
}
/* We have successfully globbed the preceding directory name.
For each name in DIRECTORIES, call glob_vector on it and
FILENAME. Concatenate the results together. */
for (i = 0; directories[i] != NULL; ++i)
{
char **temp_results;
int shouldbreak;
shouldbreak = 0;
/* XXX -- we've recursively scanned any directories resulting from
a `**', so turn off the flag. We turn it on again below if
filename is `**' */
/* Scan directory even on a NULL filename. That way, `*h/'
returns only directories ending in `h', instead of all
files ending in `h' with a `/' appended. */
dname = directories[i];
dflags = flags & ~(GX_MARKDIRS|GX_ALLDIRS|GX_ADDCURDIR);
/* last_starstar? */
if ((flags & GX_GLOBSTAR) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
if (dname[0] == '\0' && filename[0])
{
dflags |= GX_NULLDIR;
dname = "."; /* treat null directory name and non-null filename as current directory */
}
/* Special handling for symlinks to directories with globstar on */
if (all_starstar && (dflags & GX_NULLDIR) == 0)
{
int dlen;
/* If we have a directory name that is not null (GX_NULLDIR above)
and is a symlink to a directory, we return the symlink if
we're not `descending' into it (filename[0] == 0) and return
glob_error_return (which causes the code below to skip the
name) otherwise. I should fold this into a test that does both
checks instead of calling stat twice. */
if (glob_testdir (dname, flags|GX_ALLDIRS) == -2 && glob_testdir (dname, 0) == 0)
{
if (filename[0] != 0)
temp_results = (char **)&glob_error_return; /* skip */
else
{
/* Construct array to pass to glob_dir_to_array */
temp_results = (char **)malloc (2 * sizeof (char *));
if (temp_results == NULL)
goto memory_error;
temp_results[0] = (char *)malloc (1);
if (temp_results[0] == 0)
{
free (temp_results);
goto memory_error;
}
**temp_results = '\0';
temp_results[1] = NULL;
dflags |= GX_SYMLINK; /* mostly for debugging */
}
}
else
temp_results = glob_vector (filename, dname, dflags);
}
else
temp_results = glob_vector (filename, dname, dflags);
/* Handle error cases. */
if (temp_results == NULL)
goto memory_error;
else if (temp_results == (char **)&glob_error_return)
/* This filename is probably not a directory. Ignore it. */
;
else
{
char **array;
register unsigned int l;
/* If we're expanding **, we don't need to glue the directory
name to the results; we've already done it in glob_vector */
if ((dflags & GX_ALLDIRS) && filename[0] == '*' && filename[1] == '*' && (filename[2] == '\0' || filename[2] == '/'))
{
/* When do we remove null elements from temp_results? And
how to avoid duplicate elements in the final result? */
/* If (dflags & GX_NULLDIR) glob_filename potentially left a
NULL placeholder in the temp results just in case
glob_vector/glob_dir_to_array did something with it, but
if it didn't, and we're not supposed to be passing them
through for some reason ((flags & GX_NULLDIR) == 0) we
need to remove all the NULL elements from the beginning
of TEMP_RESULTS. */
/* If we have a null directory name and ** as the filename,
we have just searched for everything from the current
directory on down. Break now (shouldbreak = 1) to avoid
duplicate entries in the final result. */
#define NULL_PLACEHOLDER(x) ((x) && *(x) && **(x) == 0)
if ((dflags & GX_NULLDIR) && (flags & GX_NULLDIR) == 0 &&
NULL_PLACEHOLDER (temp_results))
#undef NULL_PLACEHOLDER
{
register int i, n;
for (n = 0; temp_results[n] && *temp_results[n] == 0; n++)
;
i = n;
do
temp_results[i - n] = temp_results[i];
while (temp_results[i++] != 0);
array = temp_results;
shouldbreak = 1;
}
else
array = temp_results;
}
else if (dflags & GX_SYMLINK)
array = glob_dir_to_array (directories[i], temp_results, flags);
else
array = glob_dir_to_array (directories[i], temp_results, flags);
l = 0;
while (array[l] != NULL)
++l;
new_result = (char **)realloc (result, (result_size + l) * sizeof (char *));
if (new_result == NULL)
{
for (l = 0; array[l]; ++l)
free (array[l]);
free ((char *)array);
goto memory_error;
}
result = new_result;
for (l = 0; array[l] != NULL; ++l)
result[result_size++ - 1] = array[l];
result[result_size - 1] = NULL;
/* Note that the elements of ARRAY are not freed. */
if (array != temp_results)
free ((char *) array);
else if ((dflags & GX_ALLDIRS) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
free (temp_results); /* expanding ** case above */
if (shouldbreak)
break;
}
}
/* Free the directories. */
for (i = 0; directories[i]; i++)
free (directories[i]);
free ((char *) directories);
return (result);
}
only_filename:
/* If there is only a directory name, return it. */
if (*filename == '\0')
{
result = (char **) realloc ((char *) result, 2 * sizeof (char *));
if (result == NULL)
{
if (free_dirname)
free (directory_name);
return (NULL);
}
/* If we have a directory name with quoted characters, and we are
being called recursively to glob the directory portion of a pathname,
we need to dequote the directory name before returning it so the
caller can read the directory */
if (directory_len > 0 && hasglob == 2 && (flags & GX_RECURSE) != 0)
{
dequote_pathname (directory_name);
directory_len = strlen (directory_name);
}
/* We could check whether or not the dequoted directory_name is a
directory and return it here, returning the original directory_name
if not, but we don't do that. We do return the dequoted directory
name if we're not being called recursively and the dequoted name
corresponds to an actual directory. For better backwards compatibility,
we can return &glob_error_return unconditionally in this case. */
if (directory_len > 0 && hasglob == 2 && (flags & GX_RECURSE) == 0)
{
#if 1
dequote_pathname (directory_name);
if (glob_testdir (directory_name, 0) < 0)
{
if (free_dirname)
free (directory_name);
return ((char **)&glob_error_return);
}
#else
return ((char **)&glob_error_return);
#endif
}
/* Handle GX_MARKDIRS here. */
result[0] = (char *) malloc (directory_len + 1);
if (result[0] == NULL)
goto memory_error;
bcopy (directory_name, result[0], directory_len + 1);
if (free_dirname)
free (directory_name);
result[1] = NULL;
return (result);
}
else
{
char **temp_results;
/* There are no unquoted globbing characters in DIRECTORY_NAME.
Dequote it before we try to open the directory since there may
be quoted globbing characters which should be treated verbatim. */
if (directory_len > 0)
dequote_pathname (directory_name);
/* We allocated a small array called RESULT, which we won't be using.
Free that memory now. */
free (result);
/* Just return what glob_vector () returns appended to the
directory name. */
/* If flags & GX_ALLDIRS, we're called recursively */
dflags = flags & ~GX_MARKDIRS;
if (directory_len == 0)
dflags |= GX_NULLDIR;
if ((flags & GX_GLOBSTAR) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
{
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
#if 0
/* If we want all directories (dflags & GX_ALLDIRS) and we're not
being called recursively as something like `echo [star][star]/[star].o'
((flags & GX_ALLDIRS) == 0), we want to prevent glob_vector from
adding a null directory name to the front of the temp_results
array. We turn off ADDCURDIR if not called recursively and
dlen == 0 */
#endif
if (directory_len == 0 && (flags & GX_ALLDIRS) == 0)
dflags &= ~GX_ADDCURDIR;
}
temp_results = glob_vector (filename,
(directory_len == 0 ? "." : directory_name),
dflags);
if (temp_results == NULL || temp_results == (char **)&glob_error_return)
{
if (free_dirname)
free (directory_name);
QUIT; /* XXX - shell */
run_pending_traps ();
return (temp_results);
}
result = glob_dir_to_array ((dflags & GX_ALLDIRS) ? "" : directory_name, temp_results, flags);
if (free_dirname)
free (directory_name);
return (result);
}
/* We get to memory_error if the program has run out of memory, or
if this is the shell, and we have been interrupted. */
memory_error:
if (result != NULL)
{
register unsigned int i;
for (i = 0; result[i] != NULL; ++i)
free (result[i]);
free ((char *) result);
}
if (free_dirname && directory_name)
free (directory_name);
QUIT;
run_pending_traps ();
return (NULL);
}
#if defined (TEST)
main (argc, argv)
int argc;
char **argv;
{
unsigned int i;
for (i = 1; i < argc; ++i)
{
char **value = glob_filename (argv[i], 0);
if (value == NULL)
puts ("Out of memory.");
else if (value == &glob_error_return)
perror (argv[i]);
else
for (i = 0; value[i] != NULL; i++)
puts (value[i]);
}
exit (0);
}
#endif /* TEST. */
| ./CrossVul/dataset_final_sorted/CWE-273/c/good_1198_9 |
crossvul-cpp_data_good_1198_2 | /* bashline.c -- Bash's interface to the readline library. */
/* Copyright (C) 1987-2019 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#if defined (READLINE)
#include "bashtypes.h"
#include "posixstat.h"
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined (HAVE_GRP_H)
# include <grp.h>
#endif
#if defined (HAVE_NETDB_H)
# include <netdb.h>
#endif
#include <signal.h>
#include <stdio.h>
#include "chartypes.h"
#include "bashansi.h"
#include "bashintl.h"
#include "shell.h"
#include "input.h"
#include "parser.h"
#include "builtins.h"
#include "bashhist.h"
#include "bashline.h"
#include "execute_cmd.h"
#include "findcmd.h"
#include "pathexp.h"
#include "shmbutil.h"
#include "trap.h"
#include "flags.h"
#if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
# include <mbstr.h> /* mbschr */
#endif
#include "builtins/common.h"
#include <readline/rlconf.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <readline/rlmbutil.h>
#include <glob/glob.h>
#if defined (ALIAS)
# include "alias.h"
#endif
#if defined (PROGRAMMABLE_COMPLETION)
# include "pcomplete.h"
#endif
/* These should agree with the defines for emacs_mode and vi_mode in
rldefs.h, even though that's not a public readline header file. */
#ifndef EMACS_EDITING_MODE
# define NO_EDITING_MODE -1
# define EMACS_EDITING_MODE 1
# define VI_EDITING_MODE 0
#endif
/* Copied from rldefs.h, since that's not a public readline header file. */
#ifndef FUNCTION_TO_KEYMAP
#if defined (CRAY)
# define FUNCTION_TO_KEYMAP(map, key) (Keymap)((int)map[key].function)
# define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)((int)(data))
#else
# define FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function)
# define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data)
#endif
#endif
#define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
#if defined (BRACE_COMPLETION)
extern int bash_brace_completion PARAMS((int, int));
#endif /* BRACE_COMPLETION */
/* To avoid including curses.h/term.h/termcap.h and that whole mess. */
#ifdef _MINIX
extern int tputs PARAMS((const char *string, int nlines, void (*outx)(int)));
#else
extern int tputs PARAMS((const char *string, int nlines, int (*outx)(int)));
#endif
/* Forward declarations */
/* Functions bound to keys in Readline for Bash users. */
static int shell_expand_line PARAMS((int, int));
static int display_shell_version PARAMS((int, int));
static int operate_and_get_next PARAMS((int, int));
static int bash_ignore_filenames PARAMS((char **));
static int bash_ignore_everything PARAMS((char **));
static int bash_progcomp_ignore_filenames PARAMS((char **));
#if defined (BANG_HISTORY)
static char *history_expand_line_internal PARAMS((char *));
static int history_expand_line PARAMS((int, int));
static int tcsh_magic_space PARAMS((int, int));
#endif /* BANG_HISTORY */
#ifdef ALIAS
static int alias_expand_line PARAMS((int, int));
#endif
#if defined (BANG_HISTORY) && defined (ALIAS)
static int history_and_alias_expand_line PARAMS((int, int));
#endif
static int bash_forward_shellword PARAMS((int, int));
static int bash_backward_shellword PARAMS((int, int));
static int bash_kill_shellword PARAMS((int, int));
static int bash_backward_kill_shellword PARAMS((int, int));
static int bash_transpose_shellwords PARAMS((int, int));
/* Helper functions for Readline. */
static char *restore_tilde PARAMS((char *, char *));
static char *maybe_restore_tilde PARAMS((char *, char *));
static char *bash_filename_rewrite_hook PARAMS((char *, int));
static void bash_directory_expansion PARAMS((char **));
static int bash_filename_stat_hook PARAMS((char **));
static int bash_command_name_stat_hook PARAMS((char **));
static int bash_directory_completion_hook PARAMS((char **));
static int filename_completion_ignore PARAMS((char **));
static int bash_push_line PARAMS((void));
static int executable_completion PARAMS((const char *, int));
static rl_icppfunc_t *save_directory_hook PARAMS((void));
static void restore_directory_hook PARAMS((rl_icppfunc_t));
static int directory_exists PARAMS((const char *, int));
static void cleanup_expansion_error PARAMS((void));
static void maybe_make_readline_line PARAMS((char *));
static void set_up_new_line PARAMS((char *));
static int check_redir PARAMS((int));
static char **attempt_shell_completion PARAMS((const char *, int, int));
static char *variable_completion_function PARAMS((const char *, int));
static char *hostname_completion_function PARAMS((const char *, int));
static char *command_subst_completion_function PARAMS((const char *, int));
static void build_history_completion_array PARAMS((void));
static char *history_completion_generator PARAMS((const char *, int));
static int dynamic_complete_history PARAMS((int, int));
static int bash_dabbrev_expand PARAMS((int, int));
static void initialize_hostname_list PARAMS((void));
static void add_host_name PARAMS((char *));
static void snarf_hosts_from_file PARAMS((char *));
static char **hostnames_matching PARAMS((char *));
static void _ignore_completion_names PARAMS((char **, sh_ignore_func_t *));
static int name_is_acceptable PARAMS((const char *));
static int test_for_directory PARAMS((const char *));
static int test_for_canon_directory PARAMS((const char *));
static int return_zero PARAMS((const char *));
static char *bash_dequote_filename PARAMS((char *, int));
static char *quote_word_break_chars PARAMS((char *));
static void set_filename_bstab PARAMS((const char *));
static char *bash_quote_filename PARAMS((char *, int, char *));
#ifdef _MINIX
static void putx PARAMS((int));
#else
static int putx PARAMS((int));
#endif
static Keymap get_cmd_xmap_from_edit_mode PARAMS((void));
static Keymap get_cmd_xmap_from_keymap PARAMS((Keymap));
static int bash_execute_unix_command PARAMS((int, int));
static void init_unix_command_map PARAMS((void));
static int isolate_sequence PARAMS((char *, int, int, int *));
static int set_saved_history PARAMS((void));
#if defined (ALIAS)
static int posix_edit_macros PARAMS((int, int));
#endif
static int bash_event_hook PARAMS((void));
#if defined (PROGRAMMABLE_COMPLETION)
static int find_cmd_start PARAMS((int));
static int find_cmd_end PARAMS((int));
static char *find_cmd_name PARAMS((int, int *, int *));
static char *prog_complete_return PARAMS((const char *, int));
static char **prog_complete_matches;
#endif
extern int no_symbolic_links;
extern STRING_INT_ALIST word_token_alist[];
/* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
completion functions which indicate what type of completion should be
done (at or before point) that can be bound to key sequences with
the readline library. */
#define SPECIFIC_COMPLETION_FUNCTIONS
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
static int bash_specific_completion PARAMS((int, rl_compentry_func_t *));
static int bash_complete_filename_internal PARAMS((int));
static int bash_complete_username_internal PARAMS((int));
static int bash_complete_hostname_internal PARAMS((int));
static int bash_complete_variable_internal PARAMS((int));
static int bash_complete_command_internal PARAMS((int));
static int bash_complete_filename PARAMS((int, int));
static int bash_possible_filename_completions PARAMS((int, int));
static int bash_complete_username PARAMS((int, int));
static int bash_possible_username_completions PARAMS((int, int));
static int bash_complete_hostname PARAMS((int, int));
static int bash_possible_hostname_completions PARAMS((int, int));
static int bash_complete_variable PARAMS((int, int));
static int bash_possible_variable_completions PARAMS((int, int));
static int bash_complete_command PARAMS((int, int));
static int bash_possible_command_completions PARAMS((int, int));
static int completion_glob_pattern PARAMS((char *));
static char *glob_complete_word PARAMS((const char *, int));
static int bash_glob_completion_internal PARAMS((int));
static int bash_glob_complete_word PARAMS((int, int));
static int bash_glob_expand_word PARAMS((int, int));
static int bash_glob_list_expansions PARAMS((int, int));
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
static int edit_and_execute_command PARAMS((int, int, int, char *));
#if defined (VI_MODE)
static int vi_edit_and_execute_command PARAMS((int, int));
static int bash_vi_complete PARAMS((int, int));
#endif
static int emacs_edit_and_execute_command PARAMS((int, int));
/* Non-zero once initalize_readline () has been called. */
int bash_readline_initialized = 0;
/* If non-zero, we do hostname completion, breaking words at `@' and
trying to complete the stuff after the `@' from our own internal
host list. */
int perform_hostname_completion = 1;
/* If non-zero, we don't do command completion on an empty line. */
int no_empty_command_completion;
/* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
only possible matches. Set to 0 if you want to match filenames if they
are the only possible matches, even if FIGNORE says to. */
int force_fignore = 1;
/* Perform spelling correction on directory names during word completion */
int dircomplete_spelling = 0;
/* Expand directory names during word/filename completion. */
#if DIRCOMPLETE_EXPAND_DEFAULT
int dircomplete_expand = 1;
int dircomplete_expand_relpath = 1;
#else
int dircomplete_expand = 0;
int dircomplete_expand_relpath = 0;
#endif
/* When non-zero, perform `normal' shell quoting on completed filenames
even when the completed name contains a directory name with a shell
variable referene, so dollar signs in a filename get quoted appropriately.
Set to zero to remove dollar sign (and braces or parens as needed) from
the set of characters that will be quoted. */
int complete_fullquote = 1;
static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
/* )) */
static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
static char *custom_filename_quote_characters = 0;
static char filename_bstab[256];
static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
static int dot_in_path = 0;
/* Set to non-zero when dabbrev-expand is running */
static int dabbrev_expand_active = 0;
/* What kind of quoting is performed by bash_quote_filename:
COMPLETE_DQUOTE = double-quoting the filename
COMPLETE_SQUOTE = single_quoting the filename
COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
*/
#define COMPLETE_DQUOTE 1
#define COMPLETE_SQUOTE 2
#define COMPLETE_BSQUOTE 3
static int completion_quoting_style = COMPLETE_BSQUOTE;
/* Flag values for the final argument to bash_default_completion */
#define DEFCOMP_CMDPOS 1
static rl_command_func_t *vi_tab_binding = rl_complete;
/* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
Called when the shell is put into or out of `posix' mode. */
void
posix_readline_initialize (on_or_off)
int on_or_off;
{
static char kseq[2] = { CTRL ('I'), 0 }; /* TAB */
if (on_or_off)
rl_variable_bind ("comment-begin", "#");
#if defined (VI_MODE)
if (on_or_off)
{
vi_tab_binding = rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL);
rl_bind_key_in_map (CTRL ('I'), rl_insert, vi_insertion_keymap);
}
else
{
if (rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL) == rl_insert)
rl_bind_key_in_map (CTRL ('I'), vi_tab_binding, vi_insertion_keymap);
}
#endif
}
void
reset_completer_word_break_chars ()
{
rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
}
/* When this function returns, rl_completer_word_break_characters points to
dynamically allocated memory. */
int
enable_hostname_completion (on_or_off)
int on_or_off;
{
int old_value;
char *at, *nv, *nval;
old_value = perform_hostname_completion;
if (on_or_off)
{
perform_hostname_completion = 1;
rl_special_prefixes = "$@";
}
else
{
perform_hostname_completion = 0;
rl_special_prefixes = "$";
}
/* Now we need to figure out how to appropriately modify and assign
rl_completer_word_break_characters depending on whether we want
hostname completion on or off. */
/* If this is the first time this has been called
(bash_readline_initialized == 0), use the sames values as before, but
allocate new memory for rl_completer_word_break_characters. */
if (bash_readline_initialized == 0 &&
(rl_completer_word_break_characters == 0 ||
rl_completer_word_break_characters == rl_basic_word_break_characters))
{
if (on_or_off)
rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
else
rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
}
else
{
/* See if we have anything to do. */
at = strchr (rl_completer_word_break_characters, '@');
if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
return old_value;
/* We have something to do. Do it. */
nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
if (on_or_off == 0)
{
/* Turn it off -- just remove `@' from word break chars. We want
to remove all occurrences of `@' from the char list, so we loop
rather than just copy the rest of the list over AT. */
for (nv = nval, at = rl_completer_word_break_characters; *at; )
if (*at != '@')
*nv++ = *at++;
else
at++;
*nv = '\0';
}
else
{
nval[0] = '@';
strcpy (nval + 1, rl_completer_word_break_characters);
}
free (rl_completer_word_break_characters);
rl_completer_word_break_characters = nval;
}
return (old_value);
}
/* Called once from parse.y if we are going to use readline. */
void
initialize_readline ()
{
rl_command_func_t *func;
char kseq[2];
if (bash_readline_initialized)
return;
rl_terminal_name = get_string_value ("TERM");
rl_instream = stdin;
rl_outstream = stderr;
/* Allow conditional parsing of the ~/.inputrc file. */
rl_readline_name = "Bash";
/* Add bindable names before calling rl_initialize so they may be
referenced in the various inputrc files. */
rl_add_defun ("shell-expand-line", shell_expand_line, -1);
#ifdef BANG_HISTORY
rl_add_defun ("history-expand-line", history_expand_line, -1);
rl_add_defun ("magic-space", tcsh_magic_space, -1);
#endif
rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
rl_add_defun ("shell-transpose-words", bash_transpose_shellwords, -1);
#ifdef ALIAS
rl_add_defun ("alias-expand-line", alias_expand_line, -1);
# ifdef BANG_HISTORY
rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
# endif
#endif
/* Backwards compatibility. */
rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
rl_add_defun ("display-shell-version", display_shell_version, -1);
rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
#if defined (BRACE_COMPLETION)
rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
#endif
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
rl_add_defun ("complete-filename", bash_complete_filename, -1);
rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
rl_add_defun ("complete-username", bash_complete_username, -1);
rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
rl_add_defun ("complete-variable", bash_complete_variable, -1);
rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
rl_add_defun ("complete-command", bash_complete_command, -1);
rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
#endif
rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
/* Bind defaults before binding our custom shell keybindings. */
if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
rl_initialize ();
/* Bind up our special shell functions. */
rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
#ifdef BANG_HISTORY
rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
#endif
rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
/* In Bash, the user can switch editing modes with "set -o [vi emacs]",
so it is not necessary to allow C-M-j for context switching. Turn
off this occasionally confusing behaviour. */
kseq[0] = CTRL('J');
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == rl_vi_editing_mode)
rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
kseq[0] = CTRL('M');
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == rl_vi_editing_mode)
rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
#if defined (VI_MODE)
kseq[0] = CTRL('E');
func = rl_function_of_keyseq (kseq, vi_movement_keymap, (int *)NULL);
if (func == rl_emacs_editing_mode)
rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
#endif
#if defined (BRACE_COMPLETION)
rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
#endif /* BRACE_COMPLETION */
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
/* Have to jump through hoops here because there is a default binding for
M-~ (rl_tilde_expand) */
kseq[0] = '~';
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == 0 || func == rl_tilde_expand)
rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
kseq[0] = TAB;
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == 0 || func == rl_tab_insert)
rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
/* Tell the completer that we want a crack first. */
rl_attempted_completion_function = attempt_shell_completion;
/* Tell the completer that we might want to follow symbolic links or
do other expansion on directory names. */
set_directory_hook ();
rl_filename_rewrite_hook = bash_filename_rewrite_hook;
rl_filename_stat_hook = bash_filename_stat_hook;
/* Tell the filename completer we want a chance to ignore some names. */
rl_ignore_some_completions_function = filename_completion_ignore;
/* Bind C-xC-e to invoke emacs and run result as commands. */
rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
#if defined (VI_MODE)
rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
# if defined (ALIAS)
rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
# endif
rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
#endif
rl_completer_quote_characters = "'\"";
/* This sets rl_completer_word_break_characters and rl_special_prefixes
to the appropriate values, depending on whether or not hostname
completion is enabled. */
enable_hostname_completion (perform_hostname_completion);
/* characters that need to be quoted when appearing in filenames. */
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
rl_filename_quoting_function = bash_quote_filename;
rl_filename_dequoting_function = bash_dequote_filename;
rl_char_is_quoted_p = char_is_quoted;
/* Add some default bindings for the "shellwords" functions, roughly
parallelling the default word bindings in emacs mode. */
rl_bind_key_if_unbound_in_map (CTRL('B'), bash_backward_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('D'), bash_kill_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('F'), bash_forward_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('T'), bash_transpose_shellwords, emacs_meta_keymap);
#if 0
/* This is superfluous and makes it impossible to use tab completion in
vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
should already have called posix_readline_initialize() when
posixly_correct was set. */
if (posixly_correct)
posix_readline_initialize (1);
#endif
bash_readline_initialized = 1;
}
void
bashline_reinitialize ()
{
bash_readline_initialized = 0;
}
void
bashline_set_event_hook ()
{
rl_signal_event_hook = bash_event_hook;
}
void
bashline_reset_event_hook ()
{
rl_signal_event_hook = 0;
}
/* On Sun systems at least, rl_attempted_completion_function can end up
getting set to NULL, and rl_completion_entry_function set to do command
word completion if Bash is interrupted while trying to complete a command
word. This just resets all the completion functions to the right thing.
It's called from throw_to_top_level(). */
void
bashline_reset ()
{
tilde_initialize ();
rl_attempted_completion_function = attempt_shell_completion;
rl_completion_entry_function = NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
set_directory_hook ();
rl_filename_stat_hook = bash_filename_stat_hook;
bashline_reset_event_hook ();
rl_sort_completion_matches = 1;
}
/* Contains the line to push into readline. */
static char *push_to_readline = (char *)NULL;
/* Push the contents of push_to_readline into the
readline buffer. */
static int
bash_push_line ()
{
if (push_to_readline)
{
rl_insert_text (push_to_readline);
free (push_to_readline);
push_to_readline = (char *)NULL;
rl_startup_hook = old_rl_startup_hook;
}
return 0;
}
/* Call this to set the initial text for the next line to read
from readline. */
int
bash_re_edit (line)
char *line;
{
FREE (push_to_readline);
push_to_readline = savestring (line);
old_rl_startup_hook = rl_startup_hook;
rl_startup_hook = bash_push_line;
return (0);
}
static int
display_shell_version (count, c)
int count, c;
{
rl_crlf ();
show_shell_version (0);
putc ('\r', rl_outstream);
fflush (rl_outstream);
rl_on_new_line ();
rl_redisplay ();
return 0;
}
/* **************************************************************** */
/* */
/* Readline Stuff */
/* */
/* **************************************************************** */
/* If the user requests hostname completion, then simply build a list
of hosts, and complete from that forever more, or at least until
HOSTFILE is unset. */
/* THIS SHOULD BE A STRINGLIST. */
/* The kept list of hostnames. */
static char **hostname_list = (char **)NULL;
/* The physical size of the above list. */
static int hostname_list_size;
/* The number of hostnames in the above list. */
static int hostname_list_length;
/* Whether or not HOSTNAME_LIST has been initialized. */
int hostname_list_initialized = 0;
/* Initialize the hostname completion table. */
static void
initialize_hostname_list ()
{
char *temp;
temp = get_string_value ("HOSTFILE");
if (temp == 0)
temp = get_string_value ("hostname_completion_file");
if (temp == 0)
temp = DEFAULT_HOSTS_FILE;
snarf_hosts_from_file (temp);
if (hostname_list)
hostname_list_initialized++;
}
/* Add NAME to the list of hosts. */
static void
add_host_name (name)
char *name;
{
if (hostname_list_length + 2 > hostname_list_size)
{
hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
hostname_list = strvec_resize (hostname_list, hostname_list_size);
}
hostname_list[hostname_list_length++] = savestring (name);
hostname_list[hostname_list_length] = (char *)NULL;
}
#define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
static void
snarf_hosts_from_file (filename)
char *filename;
{
FILE *file;
char *temp, buffer[256], name[256];
register int i, start;
file = fopen (filename, "r");
if (file == 0)
return;
while (temp = fgets (buffer, 255, file))
{
/* Skip to first character. */
for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
;
/* If comment or blank line, ignore. */
if (buffer[i] == '\0' || buffer[i] == '#')
continue;
/* If `preprocessor' directive, do the include. */
if (strncmp (buffer + i, "$include ", 9) == 0)
{
char *incfile, *t;
/* Find start of filename. */
for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
;
/* Find end of filename. */
for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
;
*t = '\0';
snarf_hosts_from_file (incfile);
continue;
}
/* Skip internet address if present. */
if (DIGIT (buffer[i]))
for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
/* Gobble up names. Each name is separated with whitespace. */
while (buffer[i])
{
for (; cr_whitespace (buffer[i]); i++)
;
if (buffer[i] == '\0' || buffer[i] == '#')
break;
/* Isolate the current word. */
for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
;
if (i == start)
continue;
strncpy (name, buffer + start, i - start);
name[i - start] = '\0';
add_host_name (name);
}
}
fclose (file);
}
/* Return the hostname list. */
char **
get_hostname_list ()
{
if (hostname_list_initialized == 0)
initialize_hostname_list ();
return (hostname_list);
}
void
clear_hostname_list ()
{
register int i;
if (hostname_list_initialized == 0)
return;
for (i = 0; i < hostname_list_length; i++)
free (hostname_list[i]);
hostname_list_length = hostname_list_initialized = 0;
}
/* Return a NULL terminated list of hostnames which begin with TEXT.
Initialize the hostname list the first time if necessary.
The array is malloc ()'ed, but not the individual strings. */
static char **
hostnames_matching (text)
char *text;
{
register int i, len, nmatch, rsize;
char **result;
if (hostname_list_initialized == 0)
initialize_hostname_list ();
if (hostname_list_initialized == 0)
return ((char **)NULL);
/* Special case. If TEXT consists of nothing, then the whole list is
what is desired. */
if (*text == '\0')
{
result = strvec_create (1 + hostname_list_length);
for (i = 0; i < hostname_list_length; i++)
result[i] = hostname_list[i];
result[i] = (char *)NULL;
return (result);
}
/* Scan until found, or failure. */
len = strlen (text);
result = (char **)NULL;
for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
{
if (STREQN (text, hostname_list[i], len) == 0)
continue;
/* OK, it matches. Add it to the list. */
if (nmatch >= (rsize - 1))
{
rsize = (rsize + 16) - (rsize % 16);
result = strvec_resize (result, rsize);
}
result[nmatch++] = hostname_list[i];
}
if (nmatch)
result[nmatch] = (char *)NULL;
return (result);
}
/* The equivalent of the Korn shell C-o operate-and-get-next-history-line
editing command. */
static int saved_history_line_to_use = -1;
static int last_saved_history_line = -1;
#define HISTORY_FULL() (history_is_stifled () && history_length >= history_max_entries)
static int
set_saved_history ()
{
/* XXX - compensate for assumption that history was `shuffled' if it was
actually not. */
if (HISTORY_FULL () &&
hist_last_line_added == 0 &&
saved_history_line_to_use < history_length - 1)
saved_history_line_to_use++;
if (saved_history_line_to_use >= 0)
{
rl_get_previous_history (history_length - saved_history_line_to_use, 0);
last_saved_history_line = saved_history_line_to_use;
}
saved_history_line_to_use = -1;
rl_startup_hook = old_rl_startup_hook;
return (0);
}
static int
operate_and_get_next (count, c)
int count, c;
{
int where;
/* Accept the current line. */
rl_newline (1, c);
/* Find the current line, and find the next line to use. */
where = rl_explicit_arg ? count : where_history ();
if (HISTORY_FULL () || (where >= history_length - 1) || rl_explicit_arg)
saved_history_line_to_use = where;
else
saved_history_line_to_use = where + 1;
old_rl_startup_hook = rl_startup_hook;
rl_startup_hook = set_saved_history;
return 0;
}
/* This vi mode command causes VI_EDIT_COMMAND to be run on the current
command being entered (if no explicit argument is given), otherwise on
a command from the history file. */
#define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
#define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
#define POSIX_VI_EDIT_COMMAND "fc -e vi"
static int
edit_and_execute_command (count, c, editing_mode, edit_command)
int count, c, editing_mode;
char *edit_command;
{
char *command, *metaval;
int r, rrs, metaflag;
sh_parser_state_t ps;
rrs = rl_readline_state;
saved_command_line_count = current_command_line_count;
/* Accept the current line. */
rl_newline (1, c);
if (rl_explicit_arg)
{
command = (char *)xmalloc (strlen (edit_command) + 8);
sprintf (command, "%s %d", edit_command, count);
}
else
{
/* Take the command we were just editing, add it to the history file,
then call fc to operate on it. We have to add a dummy command to
the end of the history because fc ignores the last command (assumes
it's supposed to deal with the command before the `fc'). */
/* This breaks down when using command-oriented history and are not
finished with the command, so we should not ignore the last command */
using_history ();
current_command_line_count++; /* for rl_newline above */
bash_add_history (rl_line_buffer);
current_command_line_count = 0; /* for dummy history entry */
bash_add_history ("");
history_lines_this_session++;
using_history ();
command = savestring (edit_command);
}
metaval = rl_variable_value ("input-meta");
metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
if (rl_deprep_term_function)
(*rl_deprep_term_function) ();
save_parser_state (&ps);
r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
restore_parser_state (&ps);
if (rl_prep_term_function)
(*rl_prep_term_function) (metaflag);
current_command_line_count = saved_command_line_count;
/* Now erase the contents of the current line and undo the effects of the
rl_accept_line() above. We don't even want to make the text we just
executed available for undoing. */
rl_line_buffer[0] = '\0'; /* XXX */
rl_point = rl_end = 0;
rl_done = 0;
rl_readline_state = rrs;
#if defined (VI_MODE)
if (editing_mode == VI_EDITING_MODE)
rl_vi_insertion_mode (1, c);
#endif
rl_forced_update_display ();
return r;
}
#if defined (VI_MODE)
static int
vi_edit_and_execute_command (count, c)
int count, c;
{
if (posixly_correct)
return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
else
return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
}
#endif /* VI_MODE */
static int
emacs_edit_and_execute_command (count, c)
int count, c;
{
return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
}
#if defined (ALIAS)
static int
posix_edit_macros (count, key)
int count, key;
{
int c;
char alias_name[3], *alias_value, *macro;
c = rl_read_key ();
alias_name[0] = '_';
alias_name[1] = c;
alias_name[2] = '\0';
alias_value = get_alias_value (alias_name);
if (alias_value && *alias_value)
{
macro = savestring (alias_value);
rl_push_macro_input (macro);
}
return 0;
}
#endif
/* Bindable commands that move `shell-words': that is, sequences of
non-unquoted-metacharacters. */
#define WORDDELIM(c) (shellmeta(c) || shellblank(c))
static int
bash_forward_shellword (count, key)
int count, key;
{
size_t slen;
int c, p;
DECLARE_MBSTATE;
if (count < 0)
return (bash_backward_shellword (-count, key));
/* The tricky part of this is deciding whether or not the first character
we're on is an unquoted metacharacter. Not completely handled yet. */
/* XXX - need to test this stuff with backslash-escaped shell
metacharacters and unclosed single- and double-quoted strings. */
p = rl_point;
slen = rl_end;
while (count)
{
if (p == rl_end)
{
rl_point = rl_end;
return 0;
}
/* Are we in a quoted string? If we are, move to the end of the quoted
string and continue the outer loop. We only want quoted strings, not
backslash-escaped characters, but char_is_quoted doesn't
differentiate. */
if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
{
do
ADVANCE_CHAR (rl_line_buffer, slen, p);
while (p < rl_end && char_is_quoted (rl_line_buffer, p));
count--;
continue;
}
/* Rest of code assumes we are not in a quoted string. */
/* Move forward until we hit a non-metacharacter. */
while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
{
switch (c)
{
default:
ADVANCE_CHAR (rl_line_buffer, slen, p);
continue; /* straight back to loop, don't increment p */
case '\\':
if (p < rl_end && rl_line_buffer[p])
ADVANCE_CHAR (rl_line_buffer, slen, p);
break;
case '\'':
p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
break;
case '"':
p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
break;
}
if (p < rl_end)
p++;
}
if (rl_line_buffer[p] == 0 || p == rl_end)
{
rl_point = rl_end;
rl_ding ();
return 0;
}
/* Now move forward until we hit a non-quoted metacharacter or EOL */
while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
{
switch (c)
{
default:
ADVANCE_CHAR (rl_line_buffer, slen, p);
continue; /* straight back to loop, don't increment p */
case '\\':
if (p < rl_end && rl_line_buffer[p])
ADVANCE_CHAR (rl_line_buffer, slen, p);
break;
case '\'':
p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
break;
case '"':
p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
break;
}
if (p < rl_end)
p++;
}
if (p == rl_end || rl_line_buffer[p] == 0)
{
rl_point = rl_end;
return (0);
}
count--;
}
rl_point = p;
return (0);
}
static int
bash_backward_shellword (count, key)
int count, key;
{
size_t slen;
int c, p, prev_p;
DECLARE_MBSTATE;
if (count < 0)
return (bash_forward_shellword (-count, key));
p = rl_point;
slen = rl_end;
while (count)
{
if (p == 0)
{
rl_point = 0;
return 0;
}
/* Move backward until we hit a non-metacharacter. We want to deal
with the characters before point, so we move off a word if we're
at its first character. */
BACKUP_CHAR (rl_line_buffer, slen, p);
while (p > 0)
{
c = rl_line_buffer[p];
if (WORDDELIM (c) == 0 || char_is_quoted (rl_line_buffer, p))
break;
BACKUP_CHAR (rl_line_buffer, slen, p);
}
if (p == 0)
{
rl_point = 0;
return 0;
}
/* Now move backward until we hit a metacharacter or BOL. Leave point
at the start of the shellword or at BOL. */
prev_p = p;
while (p > 0)
{
c = rl_line_buffer[p];
if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
{
p = prev_p;
break;
}
prev_p = p;
BACKUP_CHAR (rl_line_buffer, slen, p);
}
count--;
}
rl_point = p;
return 0;
}
static int
bash_kill_shellword (count, key)
int count, key;
{
int p;
if (count < 0)
return (bash_backward_kill_shellword (-count, key));
p = rl_point;
bash_forward_shellword (count, key);
if (rl_point != p)
rl_kill_text (p, rl_point);
rl_point = p;
if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
rl_mark = rl_point;
return 0;
}
static int
bash_backward_kill_shellword (count, key)
int count, key;
{
int p;
if (count < 0)
return (bash_kill_shellword (-count, key));
p = rl_point;
bash_backward_shellword (count, key);
if (rl_point != p)
rl_kill_text (p, rl_point);
if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
rl_mark = rl_point;
return 0;
}
static int
bash_transpose_shellwords (count, key)
int count, key;
{
char *word1, *word2;
int w1_beg, w1_end, w2_beg, w2_end;
int orig_point = rl_point;
if (count == 0)
return 0;
/* Find the two shell words. */
bash_forward_shellword (count, key);
w2_end = rl_point;
bash_backward_shellword (1, key);
w2_beg = rl_point;
bash_backward_shellword (count, key);
w1_beg = rl_point;
bash_forward_shellword (1, key);
w1_end = rl_point;
/* check that there really are two words. */
if ((w1_beg == w2_beg) || (w2_beg < w1_end))
{
rl_ding ();
rl_point = orig_point;
return 1;
}
/* Get the text of the words. */
word1 = rl_copy_text (w1_beg, w1_end);
word2 = rl_copy_text (w2_beg, w2_end);
/* We are about to do many insertions and deletions. Remember them
as one operation. */
rl_begin_undo_group ();
/* Do the stuff at word2 first, so that we don't have to worry
about word1 moving. */
rl_point = w2_beg;
rl_delete_text (w2_beg, w2_end);
rl_insert_text (word1);
rl_point = w1_beg;
rl_delete_text (w1_beg, w1_end);
rl_insert_text (word2);
/* This is exactly correct since the text before this point has not
changed in length. */
rl_point = w2_end;
/* I think that does it. */
rl_end_undo_group ();
xfree (word1);
xfree (word2);
return 0;
}
/* **************************************************************** */
/* */
/* How To Do Shell Completion */
/* */
/* **************************************************************** */
#define COMMAND_SEPARATORS ";|&{(`"
/* )} */
#define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
/* )} */
/* check for redirections and other character combinations that are not
command separators */
static int
check_redir (ti)
int ti;
{
register int this_char, prev_char;
/* Handle the two character tokens `>&', `<&', and `>|'.
We are not in a command position after one of these. */
this_char = rl_line_buffer[ti];
prev_char = (ti > 0) ? rl_line_buffer[ti - 1] : 0;
if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
(this_char == '|' && prev_char == '>'))
return (1);
else if (this_char == '{' && prev_char == '$') /*}*/
return (1);
#if 0 /* Not yet */
else if (this_char == '(' && prev_char == '$') /*)*/
return (1);
else if (this_char == '(' && prev_char == '<') /*)*/
return (1);
#if defined (EXTENDED_GLOB)
else if (extended_glob && this_char == '(' && prev_char == '!') /*)*/
return (1);
#endif
#endif
else if (char_is_quoted (rl_line_buffer, ti))
return (1);
return (0);
}
#if defined (PROGRAMMABLE_COMPLETION)
/*
* XXX - because of the <= start test, and setting os = s+1, this can
* potentially return os > start. This is probably not what we want to
* happen, but fix later after 2.05a-release.
*/
static int
find_cmd_start (start)
int start;
{
register int s, os, ns;
os = 0;
/* Flags == SD_NOJMP only because we want to skip over command substitutions
in assignment statements. Have to test whether this affects `standalone'
command substitutions as individual words. */
while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/)) <= start) &&
rl_line_buffer[s])
{
/* Handle >| token crudely; treat as > not | */
if (rl_line_buffer[s] == '|' && rl_line_buffer[s-1] == '>')
{
ns = skip_to_delim (rl_line_buffer, s+1, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/);
if (ns > start || rl_line_buffer[ns] == 0)
return os;
os = ns+1;
continue;
}
os = s+1;
}
return os;
}
static int
find_cmd_end (end)
int end;
{
register int e;
e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE);
return e;
}
static char *
find_cmd_name (start, sp, ep)
int start;
int *sp, *ep;
{
char *name;
register int s, e;
for (s = start; whitespace (rl_line_buffer[s]); s++)
;
/* skip until a shell break character */
e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP|SD_COMPLETE);
name = substring (rl_line_buffer, s, e);
if (sp)
*sp = s;
if (ep)
*ep = e;
return (name);
}
static char *
prog_complete_return (text, matchnum)
const char *text;
int matchnum;
{
static int ind;
if (matchnum == 0)
ind = 0;
if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
return (char *)NULL;
return (prog_complete_matches[ind++]);
}
#endif /* PROGRAMMABLE_COMPLETION */
/* Try and catch completion attempts that are syntax errors or otherwise
invalid. */
static int
invalid_completion (text, ind)
const char *text;
int ind;
{
int pind;
/* If we don't catch these here, the next clause will */
if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
member (rl_line_buffer[ind-1], "$<>"))
return 0;
pind = ind - 1;
while (pind > 0 && whitespace (rl_line_buffer[pind]))
pind--;
/* If we have only whitespace preceding a paren, it's valid */
if (ind >= 0 && pind <= 0 && rl_line_buffer[ind] == '(') /*)*/
return 0;
/* Flag the invalid completions, which are mostly syntax errors */
if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
member (rl_line_buffer[pind], COMMAND_SEPARATORS) == 0)
return 1;
return 0;
}
/* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
at START and END. Return an array of matches, or NULL if none. */
static char **
attempt_shell_completion (text, start, end)
const char *text;
int start, end;
{
int in_command_position, ti, qc, dflags;
char **matches, *command_separator_chars;
#if defined (PROGRAMMABLE_COMPLETION)
int have_progcomps, was_assignment;
COMPSPEC *iw_compspec;
#endif
command_separator_chars = COMMAND_SEPARATORS;
matches = (char **)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
set_directory_hook ();
rl_filename_stat_hook = bash_filename_stat_hook;
rl_sort_completion_matches = 1; /* sort by default */
/* Determine if this could be a command word. It is if it appears at
the start of the line (ignoring preceding whitespace), or if it
appears after a character that separates commands. It cannot be a
command word if we aren't at the top-level prompt. */
ti = start - 1;
qc = -1;
while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
ti--;
#if 1
/* If this is an open quote, maybe we're trying to complete a quoted
command name. */
if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
{
qc = rl_line_buffer[ti];
ti--;
while (ti > -1 && (whitespace (rl_line_buffer[ti])))
ti--;
}
#endif
in_command_position = 0;
if (ti < 0)
{
/* Only do command completion at the start of a line when we
are prompting at the top level. */
if (current_prompt_string == ps1_prompt)
in_command_position++;
else if (parser_in_command_position ())
in_command_position++;
}
else if (member (rl_line_buffer[ti], command_separator_chars))
{
in_command_position++;
if (check_redir (ti) == 1)
in_command_position = 0;
}
else
{
/* This still could be in command position. It is possible
that all of the previous words on the line are variable
assignments. */
}
if (in_command_position && invalid_completion (text, ti))
{
rl_attempted_completion_over = 1;
return ((char **)NULL);
}
/* Check that we haven't incorrectly flagged a closed command substitution
as indicating we're in a command position. */
if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
*text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
in_command_position = 0;
/* Special handling for command substitution. If *TEXT is a backquote,
it can be the start or end of an old-style command substitution, or
unmatched. If it's unmatched, both calls to unclosed_pair will
succeed. Don't bother if readline found a single quote and we are
completing on the substring. */
if (*text == '`' && rl_completion_quote_character != '\'' &&
(in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
unclosed_pair (rl_line_buffer, end, "`"))))
matches = rl_completion_matches (text, command_subst_completion_function);
#if defined (PROGRAMMABLE_COMPLETION)
/* Attempt programmable completion. */
have_progcomps = prog_completion_enabled && (progcomp_size () > 0);
iw_compspec = progcomp_search (INITIALWORD);
if (matches == 0 &&
(in_command_position == 0 || text[0] == '\0' || (in_command_position && iw_compspec)) &&
current_prompt_string == ps1_prompt)
{
int s, e, s1, e1, os, foundcs;
char *n;
/* XXX - don't free the members */
if (prog_complete_matches)
free (prog_complete_matches);
prog_complete_matches = (char **)NULL;
os = start;
n = 0;
was_assignment = 0;
s = find_cmd_start (os);
e = find_cmd_end (end);
do
{
/* Don't read past the end of rl_line_buffer */
if (s > rl_end)
{
s1 = s = e1;
break;
}
/* Or past point if point is within an assignment statement */
else if (was_assignment && s > rl_point)
{
s1 = s = e1;
break;
}
/* Skip over assignment statements preceding a command name. If we
don't find a command name at all, we can perform command name
completion. If we find a partial command name, we should perform
command name completion on it. */
FREE (n);
n = find_cmd_name (s, &s1, &e1);
s = e1 + 1;
}
while (was_assignment = assignment (n, 0));
s = s1; /* reset to index where name begins */
/* s == index of where command name begins (reset above)
e == end of current command, may be end of line
s1 = index of where command name begins
e1 == index of where command name ends
start == index of where word to be completed begins
end == index of where word to be completed ends
if (s == start) we are doing command word completion for sure
if (e1 == end) we are at the end of the command name and completing it */
if (start == 0 && end == 0 && e != 0 && text[0] == '\0') /* beginning of non-empty line */
foundcs = 0;
else if (start == end && start == s1 && e != 0 && e1 > end) /* beginning of command name, leading whitespace */
foundcs = 0;
else if (e == 0 && e == s && text[0] == '\0' && have_progcomps) /* beginning of empty line */
prog_complete_matches = programmable_completions (EMPTYCMD, text, s, e, &foundcs);
else if (start == end && text[0] == '\0' && s1 > start && whitespace (rl_line_buffer[start]))
foundcs = 0; /* whitespace before command name */
else if (e > s && was_assignment == 0 && e1 == end && rl_line_buffer[e] == 0 && whitespace (rl_line_buffer[e-1]) == 0)
{
/* not assignment statement, but still want to perform command
completion if we are composing command word. */
foundcs = 0;
in_command_position = s == start && STREQ (n, text); /* XXX */
}
else if (e > s && was_assignment == 0 && have_progcomps)
{
prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
/* command completion if programmable completion fails */
/* If we have a completion for the initial word, we can prefer that */
in_command_position = s == start && (iw_compspec || STREQ (n, text)); /* XXX */
if (iw_compspec && in_command_position)
foundcs = 0;
}
/* empty command name following command separator */
else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0 &&
was_assignment == 0 && member (rl_line_buffer[start-1], COMMAND_SEPARATORS))
{
foundcs = 0;
in_command_position = 1;
}
else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0)
{
foundcs = 0; /* empty command name following optional assignments */
in_command_position += was_assignment;
}
else if (s == start && e == end && STREQ (n, text) && start > 0)
{
foundcs = 0; /* partial command name following assignments */
in_command_position = 1;
}
else
foundcs = 0;
/* If we have defined a compspec for the initial (command) word, call
it and process the results like any other programmable completion. */
if (in_command_position && have_progcomps && foundcs == 0 && iw_compspec)
prog_complete_matches = programmable_completions (INITIALWORD, text, s, e, &foundcs);
FREE (n);
/* XXX - if we found a COMPSPEC for the command, just return whatever
the programmable completion code returns, and disable the default
filename completion that readline will do unless the COPT_DEFAULT
option has been set with the `-o default' option to complete or
compopt. */
if (foundcs)
{
pcomp_set_readline_variables (foundcs, 1);
/* Turn what the programmable completion code returns into what
readline wants. I should have made compute_lcd_of_matches
external... */
matches = rl_completion_matches (text, prog_complete_return);
if ((foundcs & COPT_DEFAULT) == 0)
rl_attempted_completion_over = 1; /* no default */
if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
return (matches);
}
}
#endif
if (matches == 0)
{
dflags = 0;
if (in_command_position)
dflags |= DEFCOMP_CMDPOS;
matches = bash_default_completion (text, start, end, qc, dflags);
}
return matches;
}
char **
bash_default_completion (text, start, end, qc, compflags)
const char *text;
int start, end, qc, compflags;
{
char **matches, *t;
matches = (char **)NULL;
/* New posix-style command substitution or variable name? */
if (*text == '$')
{
if (qc != '\'' && text[1] == '(') /* ) */
matches = rl_completion_matches (text, command_subst_completion_function);
else
{
matches = rl_completion_matches (text, variable_completion_function);
/* If a single match, see if it expands to a directory name and append
a slash if it does. This requires us to expand the variable name,
so we don't want to display errors if the variable is unset. This
can happen with dynamic variables whose value has never been
requested. */
if (matches && matches[0] && matches[1] == 0)
{
t = savestring (matches[0]);
bash_filename_stat_hook (&t);
/* doesn't use test_for_directory because that performs tilde
expansion */
if (file_isdir (t))
rl_completion_append_character = '/';
free (t);
}
}
}
/* If the word starts in `~', and there is no slash in the word, then
try completing this word as a username. */
if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
matches = rl_completion_matches (text, rl_username_completion_function);
/* Another one. Why not? If the word starts in '@', then look through
the world of known hostnames for completion first. */
if (matches == 0 && perform_hostname_completion && *text == '@')
matches = rl_completion_matches (text, hostname_completion_function);
/* And last, (but not least) if this word is in a command position, then
complete over possible command names, including aliases, functions,
and command names. */
if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
{
/* If END == START and text[0] == 0, we are trying to complete an empty
command word. */
if (no_empty_command_completion && end == start && text[0] == '\0')
{
matches = (char **)NULL;
rl_ignore_some_completions_function = bash_ignore_everything;
}
else
{
#define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
dot_in_path = 0;
matches = rl_completion_matches (text, command_word_completion_function);
/* If we are attempting command completion and nothing matches, we
do not want readline to perform filename completion for us. We
still want to be able to complete partial pathnames, so set the
completion ignore function to something which will remove
filenames and leave directories in the match list. */
if (matches == (char **)NULL)
rl_ignore_some_completions_function = bash_ignore_filenames;
else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
/* If we found a single match, without looking in the current
directory (because it's not in $PATH), but the found name is
also a command in the current directory, suppress appending any
terminating character, since it's ambiguous. */
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
/* There are multiple instances of the same match (duplicate
completions haven't yet been removed). In this case, all of
the matches will be the same, and the duplicate removal code
will distill them all down to one. We turn on
rl_completion_suppress_append for the same reason as above.
Remember: we only care if there's eventually a single unique
completion. If there are multiple completions this won't
make a difference and the problem won't occur. */
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
}
}
/* This could be a globbing pattern, so try to expand it using pathname
expansion. */
if (!matches && completion_glob_pattern ((char *)text))
{
matches = rl_completion_matches (text, glob_complete_word);
/* A glob expression that matches more than one filename is problematic.
If we match more than one filename, punt. */
if (matches && matches[1] && rl_completion_type == TAB)
{
strvec_dispose (matches);
matches = (char **)0;
}
else if (matches && matches[1] && rl_completion_type == '!')
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
}
return (matches);
}
static int
bash_command_name_stat_hook (name)
char **name;
{
char *cname, *result;
/* If it's not something we're going to look up in $PATH, just call the
normal filename stat hook. */
if (absolute_program (*name))
return (bash_filename_stat_hook (name));
cname = *name;
/* XXX - we could do something here with converting aliases, builtins,
and functions into something that came out as executable, but we don't. */
result = search_for_command (cname, 0);
if (result)
{
*name = result;
return 1;
}
return 0;
}
static int
executable_completion (filename, searching_path)
const char *filename;
int searching_path;
{
char *f;
int r;
f = savestring (filename);
bash_directory_completion_hook (&f);
r = searching_path ? executable_file (f) : executable_or_directory (f);
free (f);
return r;
}
/* This is the function to call when the word to complete is in a position
where a command word can be found. It grovels $PATH, looking for commands
that match. It also scans aliases, function names, and the shell_builtin
table. */
char *
command_word_completion_function (hint_text, state)
const char *hint_text;
int state;
{
static char *hint = (char *)NULL;
static char *path = (char *)NULL;
static char *val = (char *)NULL;
static char *filename_hint = (char *)NULL;
static char *fnhint = (char *)NULL;
static char *dequoted_hint = (char *)NULL;
static char *directory_part = (char *)NULL;
static char **glob_matches = (char **)NULL;
static int path_index, hint_len, istate, igncase;
static int mapping_over, local_index, searching_path, hint_is_dir;
static int old_glob_ignore_case, globpat;
static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
#if defined (ALIAS)
static alias_t **alias_list = (alias_t **)NULL;
#endif /* ALIAS */
char *temp, *cval;
/* We have to map over the possibilities for command words. If we have
no state, then make one just for that purpose. */
if (state == 0)
{
rl_filename_stat_hook = bash_command_name_stat_hook;
if (dequoted_hint && dequoted_hint != hint)
free (dequoted_hint);
if (hint)
free (hint);
mapping_over = searching_path = 0;
hint_is_dir = CMD_IS_DIR (hint_text);
val = (char *)NULL;
temp = rl_variable_value ("completion-ignore-case");
igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
if (glob_matches)
{
free (glob_matches);
glob_matches = (char **)NULL;
}
globpat = completion_glob_pattern ((char *)hint_text);
/* If this is an absolute program name, do not check it against
aliases, reserved words, functions or builtins. We must check
whether or not it is unique, and, if so, whether that filename
is executable. */
if (globpat || absolute_program (hint_text))
{
/* Perform tilde expansion on what's passed, so we don't end up
passing filenames with tildes directly to stat(). The rest of
the shell doesn't do variable expansion on the word following
the tilde, so we don't do it here even if direxpand is set. */
if (*hint_text == '~')
{
hint = bash_tilde_expand (hint_text, 0);
directory_part = savestring (hint_text);
temp = strchr (directory_part, '/');
if (temp)
*temp = 0;
else
{
free (directory_part);
directory_part = (char *)NULL;
}
}
else if (dircomplete_expand)
{
hint = savestring (hint_text);
bash_directory_completion_hook (&hint);
}
else
hint = savestring (hint_text);
dequoted_hint = hint;
/* If readline's completer found a quote character somewhere, but
didn't set the quote character, there must have been a quote
character embedded in the filename. It can't be at the start of
the filename, so we need to dequote the filename before we look
in the file system for it. */
if (rl_completion_found_quote && rl_completion_quote_character == 0)
{
dequoted_hint = bash_dequote_filename (hint, 0);
free (hint);
hint = dequoted_hint;
}
hint_len = strlen (hint);
if (filename_hint)
free (filename_hint);
fnhint = filename_hint = savestring (hint);
istate = 0;
if (globpat)
{
mapping_over = 5;
goto globword;
}
else
{
if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
{
dircomplete_expand = 0;
set_directory_hook ();
dircomplete_expand = 1;
}
mapping_over = 4;
goto inner;
}
}
dequoted_hint = hint = savestring (hint_text);
hint_len = strlen (hint);
if (rl_completion_found_quote && rl_completion_quote_character == 0)
dequoted_hint = bash_dequote_filename (hint, 0);
path = get_string_value ("PATH");
path_index = dot_in_path = 0;
/* Initialize the variables for each type of command word. */
local_index = 0;
if (varlist)
free (varlist);
varlist = all_visible_functions ();
#if defined (ALIAS)
if (alias_list)
free (alias_list);
alias_list = all_aliases ();
#endif /* ALIAS */
}
/* mapping_over says what we are currently hacking. Note that every case
in this list must fall through when there are no more possibilities. */
switch (mapping_over)
{
case 0: /* Aliases come first. */
#if defined (ALIAS)
while (alias_list && alias_list[local_index])
{
register char *alias;
alias = alias_list[local_index++]->name;
if (igncase == 0 && (STREQN (alias, hint, hint_len)))
return (savestring (alias));
else if (igncase && strncasecmp (alias, hint, hint_len) == 0)
return (savestring (alias));
}
#endif /* ALIAS */
local_index = 0;
mapping_over++;
case 1: /* Then shell reserved words. */
{
while (word_token_alist[local_index].word)
{
register char *reserved_word;
reserved_word = word_token_alist[local_index++].word;
if (STREQN (reserved_word, hint, hint_len))
return (savestring (reserved_word));
}
local_index = 0;
mapping_over++;
}
case 2: /* Then function names. */
while (varlist && varlist[local_index])
{
register char *varname;
varname = varlist[local_index++]->name;
/* Honor completion-ignore-case for shell function names. */
if (igncase == 0 && (STREQN (varname, hint, hint_len)))
return (savestring (varname));
else if (igncase && strncasecmp (varname, hint, hint_len) == 0)
return (savestring (varname));
}
local_index = 0;
mapping_over++;
case 3: /* Then shell builtins. */
for (; local_index < num_shell_builtins; local_index++)
{
/* Ignore it if it doesn't have a function pointer or if it
is not currently enabled. */
if (!shell_builtins[local_index].function ||
(shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
continue;
if (STREQN (shell_builtins[local_index].name, hint, hint_len))
{
int i = local_index++;
return (savestring (shell_builtins[i].name));
}
}
local_index = 0;
mapping_over++;
}
globword:
/* Limited support for completing command words with globbing chars. Only
a single match (multiple matches that end up reducing the number of
characters in the common prefix are bad) will ever be returned on
regular completion. */
if (globpat)
{
if (state == 0)
{
glob_ignore_case = igncase;
glob_matches = shell_glob_filename (hint);
glob_ignore_case = old_glob_ignore_case;
if (GLOB_FAILED (glob_matches) || glob_matches == 0)
{
glob_matches = (char **)NULL;
return ((char *)NULL);
}
local_index = 0;
if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
return ((char *)NULL);
}
while (val = glob_matches[local_index++])
{
if (executable_or_directory (val))
{
if (*hint_text == '~' && directory_part)
{
temp = maybe_restore_tilde (val, directory_part);
free (val);
val = temp;
}
return (val);
}
free (val);
}
glob_ignore_case = old_glob_ignore_case;
return ((char *)NULL);
}
/* If the text passed is a directory in the current directory, return it
as a possible match. Executables in directories in the current
directory can be specified using relative pathnames and successfully
executed even when `.' is not in $PATH. */
if (hint_is_dir)
{
hint_is_dir = 0; /* only return the hint text once */
return (savestring (hint_text));
}
/* Repeatedly call filename_completion_function while we have
members of PATH left. Question: should we stat each file?
Answer: we call executable_file () on each file. */
outer:
istate = (val != (char *)NULL);
if (istate == 0)
{
char *current_path;
/* Get the next directory from the path. If there is none, then we
are all done. */
if (path == 0 || path[path_index] == 0 ||
(current_path = extract_colon_unit (path, &path_index)) == 0)
return ((char *)NULL);
searching_path = 1;
if (*current_path == 0)
{
free (current_path);
current_path = savestring (".");
}
if (*current_path == '~')
{
char *t;
t = bash_tilde_expand (current_path, 0);
free (current_path);
current_path = t;
}
if (current_path[0] == '.' && current_path[1] == '\0')
dot_in_path = 1;
if (fnhint && fnhint != filename_hint)
free (fnhint);
if (filename_hint)
free (filename_hint);
filename_hint = sh_makepath (current_path, hint, 0);
/* Need a quoted version (though it doesn't matter much in most
cases) because rl_filename_completion_function dequotes the
filename it gets, assuming that it's been quoted as part of
the input line buffer. */
if (strpbrk (filename_hint, "\"'\\"))
fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
else
fnhint = filename_hint;
free (current_path); /* XXX */
}
inner:
val = rl_filename_completion_function (fnhint, istate);
if (mapping_over == 4 && dircomplete_expand)
set_directory_hook ();
istate = 1;
if (val == 0)
{
/* If the hint text is an absolute program, then don't bother
searching through PATH. */
if (absolute_program (hint))
return ((char *)NULL);
goto outer;
}
else
{
int match, freetemp;
if (absolute_program (hint))
{
if (igncase == 0)
match = strncmp (val, hint, hint_len) == 0;
else
match = strncasecmp (val, hint, hint_len) == 0;
/* If we performed tilde expansion, restore the original
filename. */
if (*hint_text == '~')
temp = maybe_restore_tilde (val, directory_part);
else
temp = savestring (val);
freetemp = 1;
}
else
{
temp = strrchr (val, '/');
if (temp)
{
temp++;
if (igncase == 0)
freetemp = match = strncmp (temp, hint, hint_len) == 0;
else
freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
if (match)
temp = savestring (temp);
}
else
freetemp = match = 0;
}
/* If we have found a match, and it is an executable file, return it.
We don't return directory names when searching $PATH, since the
bash execution code won't find executables in directories which
appear in directories in $PATH when they're specified using
relative pathnames. */
#if 0
/* If we're not searching $PATH and we have a relative pathname, we
need to re-canonicalize it before testing whether or not it's an
executable or a directory so the shell treats .. relative to $PWD
according to the physical/logical option. The shell already
canonicalizes the directory name in order to tell readline where
to look, so not doing it here will be inconsistent. */
/* XXX -- currently not used -- will introduce more inconsistency,
since shell does not canonicalize ../foo before passing it to
shell_execve(). */
if (match && searching_path == 0 && *val == '.')
{
char *t, *t1;
t = get_working_directory ("command-word-completion");
t1 = make_absolute (val, t);
free (t);
cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
}
else
#endif
cval = val;
if (match && executable_completion ((searching_path ? val : cval), searching_path))
{
if (cval != val)
free (cval);
free (val);
val = ""; /* So it won't be NULL. */
return (temp);
}
else
{
if (freetemp)
free (temp);
if (cval != val)
free (cval);
free (val);
goto inner;
}
}
}
/* Completion inside an unterminated command substitution. */
static char *
command_subst_completion_function (text, state)
const char *text;
int state;
{
static char **matches = (char **)NULL;
static const char *orig_start;
static char *filename_text = (char *)NULL;
static int cmd_index, start_len;
char *value;
if (state == 0)
{
if (filename_text)
free (filename_text);
orig_start = text;
if (*text == '`')
text++;
else if (*text == '$' && text[1] == '(') /* ) */
text += 2;
/* If the text was quoted, suppress any quote character that the
readline completion code would insert. */
rl_completion_suppress_quote = 1;
start_len = text - orig_start;
filename_text = savestring (text);
if (matches)
free (matches);
/*
* At this point we can entertain the idea of re-parsing
* `filename_text' into a (possibly incomplete) command name and
* arguments, and doing completion based on that. This is
* currently very rudimentary, but it is a small improvement.
*/
for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
break;
if (value <= filename_text)
matches = rl_completion_matches (filename_text, command_word_completion_function);
else
{
value++;
start_len += value - filename_text;
if (whitespace (value[-1]))
matches = rl_completion_matches (value, rl_filename_completion_function);
else
matches = rl_completion_matches (value, command_word_completion_function);
}
/* If there is more than one match, rl_completion_matches has already
put the lcd in matches[0]. Skip over it. */
cmd_index = matches && matches[0] && matches[1];
/* If there's a single match and it's a directory, set the append char
to the expected `/'. Otherwise, don't append anything. */
if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
rl_completion_append_character = '/';
else
rl_completion_suppress_append = 1;
}
if (matches == 0 || matches[cmd_index] == 0)
{
rl_filename_quoting_desired = 0; /* disable quoting */
return ((char *)NULL);
}
else
{
value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
if (start_len == 1)
value[0] = *orig_start;
else
strncpy (value, orig_start, start_len);
strcpy (value + start_len, matches[cmd_index]);
cmd_index++;
return (value);
}
}
/* Okay, now we write the entry_function for variable completion. */
static char *
variable_completion_function (text, state)
const char *text;
int state;
{
static char **varlist = (char **)NULL;
static int varlist_index;
static char *varname = (char *)NULL;
static int first_char, first_char_loc;
if (!state)
{
if (varname)
free (varname);
first_char_loc = 0;
first_char = text[0];
if (first_char == '$')
first_char_loc++;
if (text[first_char_loc] == '{')
first_char_loc++;
varname = savestring (text + first_char_loc);
if (varlist)
strvec_dispose (varlist);
varlist = all_variables_matching_prefix (varname);
varlist_index = 0;
}
if (!varlist || !varlist[varlist_index])
{
return ((char *)NULL);
}
else
{
char *value;
value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
if (first_char_loc)
{
value[0] = first_char;
if (first_char_loc == 2)
value[1] = '{';
}
strcpy (value + first_char_loc, varlist[varlist_index]);
if (first_char_loc == 2)
strcat (value, "}");
varlist_index++;
return (value);
}
}
/* How about a completion function for hostnames? */
static char *
hostname_completion_function (text, state)
const char *text;
int state;
{
static char **list = (char **)NULL;
static int list_index = 0;
static int first_char, first_char_loc;
/* If we don't have any state, make some. */
if (state == 0)
{
FREE (list);
list = (char **)NULL;
first_char_loc = 0;
first_char = *text;
if (first_char == '@')
first_char_loc++;
list = hostnames_matching ((char *)text+first_char_loc);
list_index = 0;
}
if (list && list[list_index])
{
char *t;
t = (char *)xmalloc (2 + strlen (list[list_index]));
*t = first_char;
strcpy (t + first_char_loc, list[list_index]);
list_index++;
return (t);
}
return ((char *)NULL);
}
/*
* A completion function for service names from /etc/services (or wherever).
*/
char *
bash_servicename_completion_function (text, state)
const char *text;
int state;
{
#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
return ((char *)NULL);
#else
static char *sname = (char *)NULL;
static struct servent *srvent;
static int snamelen;
char *value;
char **alist, *aentry;
int afound;
if (state == 0)
{
FREE (sname);
sname = savestring (text);
snamelen = strlen (sname);
setservent (0);
}
while (srvent = getservent ())
{
afound = 0;
if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
break;
/* Not primary, check aliases */
for (alist = srvent->s_aliases; *alist; alist++)
{
aentry = *alist;
if (STREQN (sname, aentry, snamelen))
{
afound = 1;
break;
}
}
if (afound)
break;
}
if (srvent == 0)
{
endservent ();
return ((char *)NULL);
}
value = afound ? savestring (aentry) : savestring (srvent->s_name);
return value;
#endif
}
/*
* A completion function for group names from /etc/group (or wherever).
*/
char *
bash_groupname_completion_function (text, state)
const char *text;
int state;
{
#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
return ((char *)NULL);
#else
static char *gname = (char *)NULL;
static struct group *grent;
static int gnamelen;
char *value;
if (state == 0)
{
FREE (gname);
gname = savestring (text);
gnamelen = strlen (gname);
setgrent ();
}
while (grent = getgrent ())
{
if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
break;
}
if (grent == 0)
{
endgrent ();
return ((char *)NULL);
}
value = savestring (grent->gr_name);
return (value);
#endif
}
/* Functions to perform history and alias expansions on the current line. */
#if defined (BANG_HISTORY)
/* Perform history expansion on the current line. If no history expansion
is done, pre_process_line() returns what it was passed, so we need to
allocate a new line here. */
static char *
history_expand_line_internal (line)
char *line;
{
char *new_line;
int old_verify;
old_verify = hist_verify;
hist_verify = 0;
new_line = pre_process_line (line, 0, 0);
hist_verify = old_verify;
return (new_line == line) ? savestring (line) : new_line;
}
#endif
/* There was an error in expansion. Let the preprocessor print
the error here. */
static void
cleanup_expansion_error ()
{
char *to_free;
#if defined (BANG_HISTORY)
int old_verify;
old_verify = hist_verify;
hist_verify = 0;
#endif
fprintf (rl_outstream, "\r\n");
to_free = pre_process_line (rl_line_buffer, 1, 0);
#if defined (BANG_HISTORY)
hist_verify = old_verify;
#endif
if (to_free != rl_line_buffer)
FREE (to_free);
putc ('\r', rl_outstream);
rl_forced_update_display ();
}
/* If NEW_LINE differs from what is in the readline line buffer, add an
undo record to get from the readline line buffer contents to the new
line and make NEW_LINE the current readline line. */
static void
maybe_make_readline_line (new_line)
char *new_line;
{
if (new_line && strcmp (new_line, rl_line_buffer) != 0)
{
rl_point = rl_end;
rl_add_undo (UNDO_BEGIN, 0, 0, 0);
rl_delete_text (0, rl_point);
rl_point = rl_end = rl_mark = 0;
rl_insert_text (new_line);
rl_add_undo (UNDO_END, 0, 0, 0);
}
}
/* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
static void
set_up_new_line (new_line)
char *new_line;
{
int old_point, at_end;
old_point = rl_point;
at_end = rl_point == rl_end;
/* If the line was history and alias expanded, then make that
be one thing to undo. */
maybe_make_readline_line (new_line);
free (new_line);
/* Place rl_point where we think it should go. */
if (at_end)
rl_point = rl_end;
else if (old_point < rl_end)
{
rl_point = old_point;
if (!whitespace (rl_line_buffer[rl_point]))
rl_forward_word (1, 0);
}
}
#if defined (ALIAS)
/* Expand aliases in the current readline line. */
static int
alias_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = alias_expand (rl_line_buffer);
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
#endif
#if defined (BANG_HISTORY)
/* History expand the line. */
static int
history_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = history_expand_line_internal (rl_line_buffer);
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
/* Expand history substitutions in the current line and then insert a
space (hopefully close to where we were before). */
static int
tcsh_magic_space (count, ignore)
int count, ignore;
{
int dist_from_end, old_point;
old_point = rl_point;
dist_from_end = rl_end - rl_point;
if (history_expand_line (count, ignore) == 0)
{
/* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
This works if all expansions were before rl_point or if no expansions
were performed. */
rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
rl_insert (1, ' ');
return (0);
}
else
return (1);
}
#endif /* BANG_HISTORY */
/* History and alias expand the line. */
static int
history_and_alias_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = 0;
#if defined (BANG_HISTORY)
new_line = history_expand_line_internal (rl_line_buffer);
#endif
#if defined (ALIAS)
if (new_line)
{
char *alias_line;
alias_line = alias_expand (new_line);
free (new_line);
new_line = alias_line;
}
#endif /* ALIAS */
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
/* History and alias expand the line, then perform the shell word
expansions by calling expand_string. This can't use set_up_new_line()
because we want the variable expansions as a separate undo'able
set of operations. */
static int
shell_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
WORD_LIST *expanded_string;
WORD_DESC *w;
new_line = 0;
#if defined (BANG_HISTORY)
new_line = history_expand_line_internal (rl_line_buffer);
#endif
#if defined (ALIAS)
if (new_line)
{
char *alias_line;
alias_line = alias_expand (new_line);
free (new_line);
new_line = alias_line;
}
#endif /* ALIAS */
if (new_line)
{
int old_point = rl_point;
int at_end = rl_point == rl_end;
/* If the line was history and alias expanded, then make that
be one thing to undo. */
maybe_make_readline_line (new_line);
free (new_line);
/* If there is variable expansion to perform, do that as a separate
operation to be undone. */
#if 1
w = alloc_word_desc ();
w->word = savestring (rl_line_buffer);
w->flags = rl_explicit_arg ? (W_NOPROCSUB|W_NOCOMSUB) : 0;
expanded_string = expand_word (w, rl_explicit_arg ? Q_HERE_DOCUMENT : 0);
dispose_word (w);
#else
new_line = savestring (rl_line_buffer);
expanded_string = expand_string (new_line, 0);
FREE (new_line);
#endif
if (expanded_string == 0)
{
new_line = (char *)xmalloc (1);
new_line[0] = '\0';
}
else
{
new_line = string_list (expanded_string);
dispose_words (expanded_string);
}
maybe_make_readline_line (new_line);
free (new_line);
/* Place rl_point where we think it should go. */
if (at_end)
rl_point = rl_end;
else if (old_point < rl_end)
{
rl_point = old_point;
if (!whitespace (rl_line_buffer[rl_point]))
rl_forward_word (1, 0);
}
return 0;
}
else
{
cleanup_expansion_error ();
return 1;
}
}
/* If FIGNORE is set, then don't match files with the given suffixes when
completing filenames. If only one of the possibilities has an acceptable
suffix, delete the others, else just return and let the completer
signal an error. It is called by the completer when real
completions are done on filenames by the completer's internal
function, not for completion lists (M-?) and not on "other"
completion types, such as hostnames or commands. */
static struct ignorevar fignore =
{
"FIGNORE",
(struct ign *)0,
0,
(char *)0,
(sh_iv_item_func_t *) 0,
};
static void
_ignore_completion_names (names, name_func)
char **names;
sh_ignore_func_t *name_func;
{
char **newnames;
int idx, nidx;
char **oldnames;
int oidx;
/* If there is only one completion, see if it is acceptable. If it is
not, free it up. In any case, short-circuit and return. This is a
special case because names[0] is not the prefix of the list of names
if there is only one completion; it is the completion itself. */
if (names[1] == (char *)0)
{
if (force_fignore)
if ((*name_func) (names[0]) == 0)
{
free (names[0]);
names[0] = (char *)NULL;
}
return;
}
/* Allocate space for array to hold list of pointers to matching
filenames. The pointers are copied back to NAMES when done. */
for (nidx = 1; names[nidx]; nidx++)
;
newnames = strvec_create (nidx + 1);
if (force_fignore == 0)
{
oldnames = strvec_create (nidx - 1);
oidx = 0;
}
newnames[0] = names[0];
for (idx = nidx = 1; names[idx]; idx++)
{
if ((*name_func) (names[idx]))
newnames[nidx++] = names[idx];
else if (force_fignore == 0)
oldnames[oidx++] = names[idx];
else
free (names[idx]);
}
newnames[nidx] = (char *)NULL;
/* If none are acceptable then let the completer handle it. */
if (nidx == 1)
{
if (force_fignore)
{
free (names[0]);
names[0] = (char *)NULL;
}
else
free (oldnames);
free (newnames);
return;
}
if (force_fignore == 0)
{
while (oidx)
free (oldnames[--oidx]);
free (oldnames);
}
/* If only one is acceptable, copy it to names[0] and return. */
if (nidx == 2)
{
free (names[0]);
names[0] = newnames[1];
names[1] = (char *)NULL;
free (newnames);
return;
}
/* Copy the acceptable names back to NAMES, set the new array end,
and return. */
for (nidx = 1; newnames[nidx]; nidx++)
names[nidx] = newnames[nidx];
names[nidx] = (char *)NULL;
free (newnames);
}
static int
name_is_acceptable (name)
const char *name;
{
struct ign *p;
int nlen;
for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
{
if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
return (0);
}
return (1);
}
#if 0
static int
ignore_dot_names (name)
char *name;
{
return (name[0] != '.');
}
#endif
static int
filename_completion_ignore (names)
char **names;
{
#if 0
if (glob_dot_filenames == 0)
_ignore_completion_names (names, ignore_dot_names);
#endif
setup_ignore_patterns (&fignore);
if (fignore.num_ignores == 0)
return 0;
_ignore_completion_names (names, name_is_acceptable);
return 0;
}
/* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
static int
test_for_directory (name)
const char *name;
{
char *fn;
int r;
fn = bash_tilde_expand (name, 0);
r = file_isdir (fn);
free (fn);
return (r);
}
static int
test_for_canon_directory (name)
const char *name;
{
char *fn;
int r;
fn = (*name == '~') ? bash_tilde_expand (name, 0) : savestring (name);
bash_filename_stat_hook (&fn);
r = file_isdir (fn);
free (fn);
return (r);
}
/* Remove files from NAMES, leaving directories. */
static int
bash_ignore_filenames (names)
char **names;
{
_ignore_completion_names (names, test_for_directory);
return 0;
}
static int
bash_progcomp_ignore_filenames (names)
char **names;
{
_ignore_completion_names (names, test_for_canon_directory);
return 0;
}
static int
return_zero (name)
const char *name;
{
return 0;
}
static int
bash_ignore_everything (names)
char **names;
{
_ignore_completion_names (names, return_zero);
return 0;
}
/* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
of the un-tilde-expanded version of VAL (what the user typed). */
static char *
restore_tilde (val, directory_part)
char *val, *directory_part;
{
int l, vl, dl2, xl;
char *dh2, *expdir, *ret, *v;
vl = strlen (val);
/* We need to duplicate the expansions readline performs on the directory
portion before passing it to our completion function. */
dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
bash_directory_expansion (&dh2);
dl2 = strlen (dh2);
expdir = bash_tilde_expand (directory_part, 0);
xl = strlen (expdir);
if (*directory_part == '~' && STREQ (directory_part, expdir))
{
/* tilde expansion failed, so what should we return? we use what the
user typed. */
v = mbschr (val, '/');
vl = STRLEN (v);
ret = (char *)xmalloc (xl + vl + 2);
strcpy (ret, directory_part);
if (v && *v)
strcpy (ret + xl, v);
free (dh2);
free (expdir);
return ret;
}
free (expdir);
/*
dh2 = unexpanded but dequoted tilde-prefix
dl2 = length of tilde-prefix
expdir = tilde-expanded tilde-prefix
xl = length of expanded tilde-prefix
l = length of remainder after tilde-prefix
*/
l = (vl - xl) + 1;
if (l <= 0)
{
free (dh2);
return (savestring (val)); /* XXX - just punt */
}
ret = (char *)xmalloc (dl2 + 2 + l);
strcpy (ret, dh2);
strcpy (ret + dl2, val + xl);
free (dh2);
return (ret);
}
static char *
maybe_restore_tilde (val, directory_part)
char *val, *directory_part;
{
rl_icppfunc_t *save;
char *ret;
save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
ret = restore_tilde (val, directory_part);
if (save)
restore_directory_hook (save);
return ret;
}
/* Simulate the expansions that will be performed by
rl_filename_completion_function. This must be called with the address of
a pointer to malloc'd memory. */
static void
bash_directory_expansion (dirname)
char **dirname;
{
char *d, *nd;
d = savestring (*dirname);
if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
{
free (*dirname);
*dirname = d;
}
else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
{
free (*dirname);
*dirname = d;
}
else if (rl_completion_found_quote)
{
nd = bash_dequote_filename (d, rl_completion_quote_character);
free (*dirname);
free (d);
*dirname = nd;
}
}
/* If necessary, rewrite directory entry */
static char *
bash_filename_rewrite_hook (fname, fnlen)
char *fname;
int fnlen;
{
char *conv;
conv = fnx_fromfs (fname, fnlen);
if (conv != fname)
conv = savestring (conv);
return conv;
}
/* Functions to save and restore the appropriate directory hook */
/* This is not static so the shopt code can call it */
void
set_directory_hook ()
{
if (dircomplete_expand)
{
rl_directory_completion_hook = bash_directory_completion_hook;
rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
}
else
{
rl_directory_rewrite_hook = bash_directory_completion_hook;
rl_directory_completion_hook = (rl_icppfunc_t *)0;
}
}
static rl_icppfunc_t *
save_directory_hook ()
{
rl_icppfunc_t *ret;
if (dircomplete_expand)
{
ret = rl_directory_completion_hook;
rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
}
else
{
ret = rl_directory_rewrite_hook;
rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
}
return ret;
}
static void
restore_directory_hook (hookf)
rl_icppfunc_t *hookf;
{
if (dircomplete_expand)
rl_directory_completion_hook = hookf;
else
rl_directory_rewrite_hook = hookf;
}
/* Check whether not DIRNAME, with any trailing slash removed, exists. If
SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
static int
directory_exists (dirname, should_dequote)
const char *dirname;
int should_dequote;
{
char *new_dirname;
int dirlen, r;
struct stat sb;
/* We save the string and chop the trailing slash because stat/lstat behave
inconsistently if one is present. */
new_dirname = should_dequote ? bash_dequote_filename ((char *)dirname, rl_completion_quote_character) : savestring (dirname);
dirlen = STRLEN (new_dirname);
if (new_dirname[dirlen - 1] == '/')
new_dirname[dirlen - 1] = '\0';
#if defined (HAVE_LSTAT)
r = lstat (new_dirname, &sb) == 0;
#else
r = stat (new_dirname, &sb) == 0;
#endif
free (new_dirname);
return (r);
}
/* Expand a filename before the readline completion code passes it to stat(2).
The filename will already have had tilde expansion performed. */
static int
bash_filename_stat_hook (dirname)
char **dirname;
{
char *local_dirname, *new_dirname, *t;
int should_expand_dirname, return_value;
int global_nounset;
WORD_LIST *wl;
local_dirname = *dirname;
should_expand_dirname = return_value = 0;
if (t = mbschr (local_dirname, '$'))
should_expand_dirname = '$';
else if (t = mbschr (local_dirname, '`')) /* XXX */
should_expand_dirname = '`';
if (should_expand_dirname && directory_exists (local_dirname, 0))
should_expand_dirname = 0;
if (should_expand_dirname)
{
new_dirname = savestring (local_dirname);
/* no error messages, and expand_prompt_string doesn't longjmp so we don't
have to worry about restoring this setting. */
global_nounset = unbound_vars_is_error;
unbound_vars_is_error = 0;
wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
unbound_vars_is_error = global_nounset;
if (wl)
{
free (new_dirname);
new_dirname = string_list (wl);
/* Tell the completer we actually expanded something and change
*dirname only if we expanded to something non-null -- stat
behaves unpredictably when passed null or empty strings */
if (new_dirname && *new_dirname)
{
free (local_dirname); /* XXX */
local_dirname = *dirname = new_dirname;
return_value = STREQ (local_dirname, *dirname) == 0;
}
else
free (new_dirname);
dispose_words (wl);
}
else
free (new_dirname);
}
/* This is very similar to the code in bash_directory_completion_hook below,
but without spelling correction and not worrying about whether or not
we change relative pathnames. */
if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
{
char *temp1, *temp2;
t = get_working_directory ("symlink-hook");
temp1 = make_absolute (local_dirname, t);
free (t);
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
/* If we can't canonicalize, bail. */
if (temp2 == 0)
{
free (temp1);
return return_value;
}
free (local_dirname);
*dirname = temp2;
free (temp1);
}
return (return_value);
}
/* Handle symbolic link references and other directory name
expansions while hacking completion. This should return 1 if it modifies
the DIRNAME argument, 0 otherwise. It should make sure not to modify
DIRNAME if it returns 0. */
static int
bash_directory_completion_hook (dirname)
char **dirname;
{
char *local_dirname, *new_dirname, *t;
int return_value, should_expand_dirname, nextch, closer;
WORD_LIST *wl;
return_value = should_expand_dirname = nextch = closer = 0;
local_dirname = *dirname;
if (t = mbschr (local_dirname, '$'))
{
should_expand_dirname = '$';
nextch = t[1];
/* Deliberately does not handle the deprecated $[...] arithmetic
expansion syntax */
if (nextch == '(')
closer = ')';
else if (nextch == '{')
closer = '}';
else
nextch = 0;
if (closer)
{
int p;
char delims[2];
delims[0] = closer; delims[1] = 0;
p = skip_to_delim (t, 1, delims, SD_NOJMP|SD_COMPLETE);
if (t[p] != closer)
should_expand_dirname = 0;
}
}
else if (local_dirname[0] == '~')
should_expand_dirname = '~';
else
{
t = mbschr (local_dirname, '`');
if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
should_expand_dirname = '`';
}
if (should_expand_dirname && directory_exists (local_dirname, 1))
should_expand_dirname = 0;
if (should_expand_dirname)
{
new_dirname = savestring (local_dirname);
wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
if (wl)
{
*dirname = string_list (wl);
/* Tell the completer to replace the directory name only if we
actually expanded something. */
return_value = STREQ (local_dirname, *dirname) == 0;
free (local_dirname);
free (new_dirname);
dispose_words (wl);
local_dirname = *dirname;
/* XXX - change rl_filename_quote_characters here based on
should_expand_dirname/nextch/closer. This is the only place
custom_filename_quote_characters is modified. */
if (rl_filename_quote_characters && *rl_filename_quote_characters)
{
int i, j, c;
i = strlen (default_filename_quote_characters);
custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
for (i = j = 0; c = default_filename_quote_characters[i]; i++)
{
if (c == should_expand_dirname || c == nextch || c == closer)
continue;
custom_filename_quote_characters[j++] = c;
}
custom_filename_quote_characters[j] = '\0';
rl_filename_quote_characters = custom_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
}
}
else
{
free (new_dirname);
free (local_dirname);
*dirname = (char *)xmalloc (1);
**dirname = '\0';
return 1;
}
}
else
{
/* Dequote the filename even if we don't expand it. */
new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
return_value = STREQ (local_dirname, new_dirname) == 0;
free (local_dirname);
local_dirname = *dirname = new_dirname;
}
/* no_symbolic_links == 0 -> use (default) logical view of the file system.
local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
current directory (./).
local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
in the current directory (e.g., lib/sh).
XXX - should we do spelling correction on these? */
/* This is test as it was in bash-4.2: skip relative pathnames in current
directory. Change test to
(local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
if we want to skip paths beginning with ./ also. */
if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
{
char *temp1, *temp2;
int len1, len2;
/* If we have a relative path
(local_dirname[0] != '/' && local_dirname[0] != '.')
that is canonical after appending it to the current directory, then
temp1 = temp2+'/'
That is,
strcmp (temp1, temp2) == 0
after adding a slash to temp2 below. It should be safe to not
change those.
*/
t = get_working_directory ("symlink-hook");
temp1 = make_absolute (local_dirname, t);
free (t);
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
/* Try spelling correction if initial canonicalization fails. Make
sure we are set to replace the directory name with the results so
subsequent directory checks don't fail. */
if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
{
temp2 = dirspell (temp1);
if (temp2)
{
free (temp1);
temp1 = temp2;
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
return_value |= temp2 != 0;
}
}
/* If we can't canonicalize, bail. */
if (temp2 == 0)
{
free (temp1);
return return_value;
}
len1 = strlen (temp1);
if (temp1[len1 - 1] == '/')
{
len2 = strlen (temp2);
if (len2 > 2) /* don't append `/' to `/' or `//' */
{
temp2 = (char *)xrealloc (temp2, len2 + 2);
temp2[len2] = '/';
temp2[len2 + 1] = '\0';
}
}
/* dircomplete_expand_relpath == 0 means we want to leave relative
pathnames that are unchanged by canonicalization alone.
*local_dirname != '/' && *local_dirname != '.' == relative pathname
(consistent with general.c:absolute_pathname())
temp1 == temp2 (after appending a slash to temp2) means the pathname
is not changed by canonicalization as described above. */
if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
return_value |= STREQ (local_dirname, temp2) == 0;
free (local_dirname);
*dirname = temp2;
free (temp1);
}
return (return_value);
}
static char **history_completion_array = (char **)NULL;
static int harry_size;
static int harry_len;
static void
build_history_completion_array ()
{
register int i, j;
HIST_ENTRY **hlist;
char **tokens;
/* First, clear out the current dynamic history completion list. */
if (harry_size)
{
strvec_dispose (history_completion_array);
history_completion_array = (char **)NULL;
harry_size = 0;
harry_len = 0;
}
/* Next, grovel each line of history, making each shell-sized token
a separate entry in the history_completion_array. */
hlist = history_list ();
if (hlist)
{
for (i = 0; hlist[i]; i++)
;
for ( --i; i >= 0; i--)
{
/* Separate each token, and place into an array. */
tokens = history_tokenize (hlist[i]->line);
for (j = 0; tokens && tokens[j]; j++)
{
if (harry_len + 2 > harry_size)
history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
history_completion_array[harry_len++] = tokens[j];
history_completion_array[harry_len] = (char *)NULL;
}
free (tokens);
}
/* Sort the complete list of tokens. */
if (dabbrev_expand_active == 0)
qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
}
}
static char *
history_completion_generator (hint_text, state)
const char *hint_text;
int state;
{
static int local_index, len;
static const char *text;
/* If this is the first call to the generator, then initialize the
list of strings to complete over. */
if (state == 0)
{
if (dabbrev_expand_active) /* This is kind of messy */
rl_completion_suppress_append = 1;
local_index = 0;
build_history_completion_array ();
text = hint_text;
len = strlen (text);
}
while (history_completion_array && history_completion_array[local_index])
{
/* XXX - should this use completion-ignore-case? */
if (strncmp (text, history_completion_array[local_index++], len) == 0)
return (savestring (history_completion_array[local_index - 1]));
}
return ((char *)NULL);
}
static int
dynamic_complete_history (count, key)
int count, key;
{
int r;
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
rl_completion_entry_function = history_completion_generator;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
/* XXX - use rl_completion_mode here? */
if (rl_last_func == dynamic_complete_history)
r = rl_complete_internal ('?');
else
r = rl_complete_internal (TAB);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
return r;
}
static int
bash_dabbrev_expand (count, key)
int count, key;
{
int r, orig_suppress, orig_sort;
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
orig_func = rl_menu_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
orig_suppress = rl_completion_suppress_append;
orig_sort = rl_sort_completion_matches;
rl_menu_completion_entry_function = history_completion_generator;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_completion_desired = 0;
rl_completion_suppress_append = 1;
rl_sort_completion_matches = 0;
/* XXX - use rl_completion_mode here? */
dabbrev_expand_active = 1;
if (rl_last_func == bash_dabbrev_expand)
rl_last_func = rl_menu_complete;
r = rl_menu_complete (count, key);
dabbrev_expand_active = 0;
rl_last_func = bash_dabbrev_expand;
rl_menu_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
rl_completion_suppress_append = orig_suppress;
rl_sort_completion_matches = orig_sort;
return r;
}
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
static int
bash_complete_username (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
}
static int
bash_possible_username_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_username_internal ('?');
}
static int
bash_complete_username_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, rl_username_completion_function);
}
static int
bash_complete_filename (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
}
static int
bash_possible_filename_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_filename_internal ('?');
}
static int
bash_complete_filename_internal (what_to_do)
int what_to_do;
{
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_icppfunc_t *orig_dir_func;
rl_compignore_func_t *orig_ignore_func;
/*const*/ char *orig_rl_completer_word_break_characters;
int r;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
orig_dir_func = save_directory_hook ();
rl_completion_entry_function = rl_filename_completion_function;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_completer_word_break_characters = " \t\n\"\'";
r = rl_complete_internal (what_to_do);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
restore_directory_hook (orig_dir_func);
return r;
}
static int
bash_complete_hostname (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
}
static int
bash_possible_hostname_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_hostname_internal ('?');
}
static int
bash_complete_variable (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
}
static int
bash_possible_variable_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_variable_internal ('?');
}
static int
bash_complete_command (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
}
static int
bash_possible_command_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_command_internal ('?');
}
static int
bash_complete_hostname_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, hostname_completion_function);
}
static int
bash_complete_variable_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, variable_completion_function);
}
static int
bash_complete_command_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, command_word_completion_function);
}
static int
completion_glob_pattern (string)
char *string;
{
return (glob_pattern_p (string) == 1);
}
static char *globtext;
static char *globorig;
static char *
glob_complete_word (text, state)
const char *text;
int state;
{
static char **matches = (char **)NULL;
static int ind;
int glen;
char *ret, *ttext;
if (state == 0)
{
rl_filename_completion_desired = 1;
FREE (matches);
if (globorig != globtext)
FREE (globorig);
FREE (globtext);
ttext = bash_tilde_expand (text, 0);
if (rl_explicit_arg)
{
globorig = savestring (ttext);
glen = strlen (ttext);
globtext = (char *)xmalloc (glen + 2);
strcpy (globtext, ttext);
globtext[glen] = '*';
globtext[glen+1] = '\0';
}
else
globtext = globorig = savestring (ttext);
if (ttext != text)
free (ttext);
matches = shell_glob_filename (globtext);
if (GLOB_FAILED (matches))
matches = (char **)NULL;
ind = 0;
}
ret = matches ? matches[ind] : (char *)NULL;
ind++;
return ret;
}
static int
bash_glob_completion_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, glob_complete_word);
}
/* A special quoting function so we don't end up quoting globbing characters
in the word if there are no matches or multiple matches. */
static char *
bash_glob_quote_filename (s, rtype, qcp)
char *s;
int rtype;
char *qcp;
{
if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
return (savestring (s));
else
return (bash_quote_filename (s, rtype, qcp));
}
static int
bash_glob_complete_word (count, key)
int count, key;
{
int r;
rl_quote_func_t *orig_quoting_function;
if (rl_editing_mode == EMACS_EDITING_MODE)
rl_explicit_arg = 1; /* force `*' append */
orig_quoting_function = rl_filename_quoting_function;
rl_filename_quoting_function = bash_glob_quote_filename;
r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
rl_filename_quoting_function = orig_quoting_function;
return r;
}
static int
bash_glob_expand_word (count, key)
int count, key;
{
return bash_glob_completion_internal ('*');
}
static int
bash_glob_list_expansions (count, key)
int count, key;
{
return bash_glob_completion_internal ('?');
}
static int
bash_specific_completion (what_to_do, generator)
int what_to_do;
rl_compentry_func_t *generator;
{
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
int r;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
rl_completion_entry_function = generator;
rl_attempted_completion_function = NULL;
rl_ignore_some_completions_function = orig_ignore_func;
r = rl_complete_internal (what_to_do);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
return r;
}
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
#if defined (VI_MODE)
/* Completion, from vi mode's point of view. This is a modified version of
rl_vi_complete which uses the bash globbing code to implement what POSIX
specifies, which is to append a `*' and attempt filename generation (which
has the side effect of expanding any globbing characters in the word). */
static int
bash_vi_complete (count, key)
int count, key;
{
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
int p, r;
char *t;
if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
{
if (!whitespace (rl_line_buffer[rl_point + 1]))
rl_vi_end_word (1, 'E');
rl_point++;
}
/* Find boundaries of current word, according to vi definition of a
`bigword'. */
t = 0;
if (rl_point > 0)
{
p = rl_point;
rl_vi_bWord (1, 'B');
r = rl_point;
rl_point = p;
p = r;
t = substring (rl_line_buffer, p, rl_point);
}
if (t && completion_glob_pattern (t) == 0)
rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
FREE (t);
if (key == '*') /* Expansion and replacement. */
r = bash_glob_expand_word (count, key);
else if (key == '=') /* List possible completions. */
r = bash_glob_list_expansions (count, key);
else if (key == '\\') /* Standard completion */
r = bash_glob_complete_word (count, key);
else
r = rl_complete (0, key);
if (key == '*' || key == '\\')
rl_vi_start_inserting (key, 1, 1);
return (r);
#else
return rl_vi_complete (count, key);
#endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
}
#endif /* VI_MODE */
/* Filename quoting for completion. */
/* A function to strip unquoted quote characters (single quotes, double
quotes, and backslashes). It allows single quotes to appear
within double quotes, and vice versa. It should be smarter. */
static char *
bash_dequote_filename (text, quote_char)
char *text;
int quote_char;
{
char *ret, *p, *r;
int l, quoted;
l = strlen (text);
ret = (char *)xmalloc (l + 1);
for (quoted = quote_char, p = text, r = ret; p && *p; p++)
{
/* Allow backslash-escaped characters to pass through unscathed. */
if (*p == '\\')
{
/* Backslashes are preserved within single quotes. */
if (quoted == '\'')
*r++ = *p;
/* Backslashes are preserved within double quotes unless the
character is one that is defined to be escaped */
else if (quoted == '"' && ((sh_syntaxtab[(unsigned char)p[1]] & CBSDQUOTE) == 0))
*r++ = *p;
*r++ = *++p;
if (*p == '\0')
return ret; /* XXX - was break; */
continue;
}
/* Close quote. */
if (quoted && *p == quoted)
{
quoted = 0;
continue;
}
/* Open quote. */
if (quoted == 0 && (*p == '\'' || *p == '"'))
{
quoted = *p;
continue;
}
*r++ = *p;
}
*r = '\0';
return ret;
}
/* Quote characters that the readline completion code would treat as
word break characters with backslashes. Pass backslash-quoted
characters through without examination. */
static char *
quote_word_break_chars (text)
char *text;
{
char *ret, *r, *s;
int l;
l = strlen (text);
ret = (char *)xmalloc ((2 * l) + 1);
for (s = text, r = ret; *s; s++)
{
/* Pass backslash-quoted characters through, including the backslash. */
if (*s == '\\')
{
*r++ = '\\';
*r++ = *++s;
if (*s == '\0')
break;
continue;
}
/* OK, we have an unquoted character. Check its presence in
rl_completer_word_break_characters. */
if (mbschr (rl_completer_word_break_characters, *s))
*r++ = '\\';
/* XXX -- check for standalone tildes here and backslash-quote them */
if (s == text && *s == '~' && file_exists (text))
*r++ = '\\';
*r++ = *s;
}
*r = '\0';
return ret;
}
/* Use characters in STRING to populate the table of characters that should
be backslash-quoted. The table will be used for sh_backslash_quote from
this file. */
static void
set_filename_bstab (string)
const char *string;
{
const char *s;
memset (filename_bstab, 0, sizeof (filename_bstab));
for (s = string; s && *s; s++)
filename_bstab[*s] = 1;
}
/* Quote a filename using double quotes, single quotes, or backslashes
depending on the value of completion_quoting_style. If we're
completing using backslashes, we need to quote some additional
characters (those that readline treats as word breaks), so we call
quote_word_break_chars on the result. This returns newly-allocated
memory. */
static char *
bash_quote_filename (s, rtype, qcp)
char *s;
int rtype;
char *qcp;
{
char *rtext, *mtext, *ret;
int rlen, cs;
rtext = (char *)NULL;
/* If RTYPE == MULT_MATCH, it means that there is
more than one match. In this case, we do not add
the closing quote or attempt to perform tilde
expansion. If RTYPE == SINGLE_MATCH, we try
to perform tilde expansion, because single and double
quotes inhibit tilde expansion by the shell. */
cs = completion_quoting_style;
/* Might need to modify the default completion style based on *qcp,
since it's set to any user-provided opening quote. We also change
to single-quoting if there is no user-provided opening quote and
the word being completed contains newlines, since those are not
quoted correctly using backslashes (a backslash-newline pair is
special to the shell parser). */
if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
cs = COMPLETE_SQUOTE;
else if (*qcp == '"')
cs = COMPLETE_DQUOTE;
else if (*qcp == '\'')
cs = COMPLETE_SQUOTE;
#if defined (BANG_HISTORY)
else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
history_expansion_inhibited == 0 && mbschr (s, '!'))
cs = COMPLETE_BSQUOTE;
if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
history_expansion_inhibited == 0 && mbschr (s, '!'))
{
cs = COMPLETE_BSQUOTE;
*qcp = '\0';
}
#endif
/* Don't tilde-expand backslash-quoted filenames, since only single and
double quotes inhibit tilde expansion. */
mtext = s;
if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
mtext = bash_tilde_expand (s, 0);
switch (cs)
{
case COMPLETE_DQUOTE:
rtext = sh_double_quote (mtext);
break;
case COMPLETE_SQUOTE:
rtext = sh_single_quote (mtext);
break;
case COMPLETE_BSQUOTE:
rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
break;
}
if (mtext != s)
free (mtext);
/* We may need to quote additional characters: those that readline treats
as word breaks that are not quoted by backslash_quote. */
if (rtext && cs == COMPLETE_BSQUOTE)
{
mtext = quote_word_break_chars (rtext);
free (rtext);
rtext = mtext;
}
/* Leave the opening quote intact. The readline completion code takes
care of avoiding doubled opening quotes. */
if (rtext)
{
rlen = strlen (rtext);
ret = (char *)xmalloc (rlen + 1);
strcpy (ret, rtext);
}
else
{
ret = (char *)xmalloc (rlen = 1);
ret[0] = '\0';
}
/* If there are multiple matches, cut off the closing quote. */
if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
ret[rlen - 1] = '\0';
free (rtext);
return ret;
}
/* Support for binding readline key sequences to Unix commands. Each editing
mode has a separate Unix command keymap. */
static Keymap emacs_std_cmd_xmap;
#if defined (VI_MODE)
static Keymap vi_insert_cmd_xmap;
static Keymap vi_movement_cmd_xmap;
#endif
#ifdef _MINIX
static void
#else
static int
#endif
putx(c)
int c;
{
int x;
x = putc (c, rl_outstream);
#ifndef _MINIX
return x;
#endif
}
static int
bash_execute_unix_command (count, key)
int count; /* ignored */
int key;
{
int type;
register int i, r;
intmax_t mi;
sh_parser_state_t ps;
char *cmd, *value, *ce, old_ch;
SHELL_VAR *v;
char ibuf[INT_STRLEN_BOUND(int) + 1];
Keymap cmd_xmap;
/* First, we need to find the right command to execute. This is tricky,
because we might have already indirected into another keymap, so we
have to walk cmd_xmap using the entire key sequence. */
cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
cmd = (char *)rl_function_of_keyseq_len (rl_executing_keyseq, rl_key_sequence_length, cmd_xmap, &type);
if (cmd == 0 || type != ISMACR)
{
rl_crlf ();
internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
rl_forced_update_display ();
return 1;
}
ce = rl_get_termcap ("ce");
if (ce) /* clear current line */
{
#if 0
fprintf (rl_outstream, "\r");
tputs (ce, 1, putx);
#else
rl_clear_visible_line ();
#endif
fflush (rl_outstream);
}
else
rl_crlf (); /* move to a new line */
v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
if (v)
VSETATTR (v, att_exported);
i = rl_point;
#if defined (HANDLE_MULTIBYTE)
if (MB_CUR_MAX > 1)
{
old_ch = rl_line_buffer[rl_point];
rl_line_buffer[rl_point] = '\0';
i = MB_STRLEN (rl_line_buffer);
rl_line_buffer[rl_point] = old_ch;
}
#endif
value = inttostr (i, ibuf, sizeof (ibuf));
v = bind_int_variable ("READLINE_POINT", value, 0);
if (v)
VSETATTR (v, att_exported);
array_needs_making = 1;
save_parser_state (&ps);
r = parse_and_execute (savestring (cmd), "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
restore_parser_state (&ps);
v = find_variable ("READLINE_LINE");
maybe_make_readline_line (v ? value_cell (v) : 0);
v = find_variable ("READLINE_POINT");
if (v && legal_number (value_cell (v), &mi))
{
i = mi;
#if defined (HANDLE_MULTIBYTE)
if (i > 0 && MB_CUR_MAX > 1)
i = _rl_find_next_mbchar (rl_line_buffer, 0, i, 0);
#endif
if (i != rl_point)
{
rl_point = i;
if (rl_point > rl_end)
rl_point = rl_end;
else if (rl_point < 0)
rl_point = 0;
}
}
check_unbind_variable ("READLINE_LINE");
check_unbind_variable ("READLINE_POINT");
array_needs_making = 1;
/* and restore the readline buffer and display after command execution. */
/* If we clear the last line of the prompt above, redraw only that last
line. If the command returns 124, we redraw unconditionally as in
previous versions. */
if (ce && r != 124)
rl_redraw_prompt_last_line ();
else
rl_forced_update_display ();
return 0;
}
int
print_unix_command_map ()
{
Keymap save, cmd_xmap;
save = rl_get_keymap ();
cmd_xmap = get_cmd_xmap_from_keymap (save);
rl_set_keymap (cmd_xmap);
rl_macro_dumper (1);
rl_set_keymap (save);
return 0;
}
static void
init_unix_command_map ()
{
emacs_std_cmd_xmap = rl_make_bare_keymap ();
emacs_std_cmd_xmap[CTRL('X')].type = ISKMAP;
emacs_std_cmd_xmap[CTRL('X')].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
emacs_std_cmd_xmap[ESC].type = ISKMAP;
emacs_std_cmd_xmap[ESC].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
#if defined (VI_MODE)
vi_insert_cmd_xmap = rl_make_bare_keymap ();
vi_movement_cmd_xmap = rl_make_bare_keymap ();
#endif
}
static Keymap
get_cmd_xmap_from_edit_mode ()
{
if (emacs_std_cmd_xmap == 0)
init_unix_command_map ();
switch (rl_editing_mode)
{
case EMACS_EDITING_MODE:
return emacs_std_cmd_xmap;
#if defined (VI_MODE)
case VI_EDITING_MODE:
return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
#endif
default:
return (Keymap)NULL;
}
}
static Keymap
get_cmd_xmap_from_keymap (kmap)
Keymap kmap;
{
if (emacs_std_cmd_xmap == 0)
init_unix_command_map ();
if (kmap == emacs_standard_keymap)
return emacs_std_cmd_xmap;
else if (kmap == emacs_meta_keymap)
return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, ESC));
else if (kmap == emacs_ctlx_keymap)
return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, CTRL('X')));
#if defined (VI_MODE)
else if (kmap == vi_insertion_keymap)
return vi_insert_cmd_xmap;
else if (kmap == vi_movement_keymap)
return vi_movement_cmd_xmap;
#endif
else
return (Keymap)NULL;
}
static int
isolate_sequence (string, ind, need_dquote, startp)
char *string;
int ind, need_dquote, *startp;
{
register int i;
int c, passc, delim;
for (i = ind; string[i] && whitespace (string[i]); i++)
;
/* NEED_DQUOTE means that the first non-white character *must* be `"'. */
if (need_dquote && string[i] != '"')
{
builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
return -1;
}
/* We can have delimited strings even if NEED_DQUOTE == 0, like the command
string to bind the key sequence to. */
delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
if (startp)
*startp = delim ? ++i : i;
for (passc = 0; c = string[i]; i++)
{
if (passc)
{
passc = 0;
continue;
}
if (c == '\\')
{
passc++;
continue;
}
if (c == delim)
break;
}
if (delim && string[i] != delim)
{
builtin_error (_("no closing `%c' in %s"), delim, string);
return -1;
}
return i;
}
int
bind_keyseq_to_unix_command (line)
char *line;
{
Keymap kmap, cmd_xmap;
char *kseq, *value;
int i, kstart;
kmap = rl_get_keymap ();
/* We duplicate some of the work done by rl_parse_and_bind here, but
this code only has to handle `"keyseq": ["]command["]' and can
generate an error for anything else. */
i = isolate_sequence (line, 0, 1, &kstart);
if (i < 0)
return -1;
/* Create the key sequence string to pass to rl_generic_bind */
kseq = substring (line, kstart, i);
for ( ; line[i] && line[i] != ':'; i++)
;
if (line[i] != ':')
{
builtin_error (_("%s: missing colon separator"), line);
FREE (kseq);
return -1;
}
i = isolate_sequence (line, i + 1, 0, &kstart);
if (i < 0)
{
FREE (kseq);
return -1;
}
/* Create the value string containing the command to execute. */
value = substring (line, kstart, i);
/* Save the command to execute and the key sequence in the CMD_XMAP */
cmd_xmap = get_cmd_xmap_from_keymap (kmap);
rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
/* and bind the key sequence in the current keymap to a function that
understands how to execute from CMD_XMAP */
rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
free (kseq);
return 0;
}
/* Used by the programmable completion code. Complete TEXT as a filename,
but return only directories as matches. Dequotes the filename before
attempting to find matches. */
char **
bash_directory_completion_matches (text)
const char *text;
{
char **m1;
char *dfn;
int qc;
qc = rl_dispatching ? rl_completion_quote_character : 0;
/* If rl_completion_found_quote != 0, rl_completion_matches will call the
filename dequoting function, causing the directory name to be dequoted
twice. */
if (rl_dispatching && rl_completion_found_quote == 0)
dfn = bash_dequote_filename ((char *)text, qc);
else
dfn = (char *)text;
m1 = rl_completion_matches (dfn, rl_filename_completion_function);
if (dfn != text)
free (dfn);
if (m1 == 0 || m1[0] == 0)
return m1;
/* We don't bother recomputing the lcd of the matches, because it will just
get thrown away by the programmable completion code and recomputed
later. */
(void)bash_progcomp_ignore_filenames (m1);
return m1;
}
char *
bash_dequote_text (text)
const char *text;
{
char *dtxt;
int qc;
qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
dtxt = bash_dequote_filename ((char *)text, qc);
return (dtxt);
}
/* This event hook is designed to be called after readline receives a signal
that interrupts read(2). It gives reasonable responsiveness to interrupts
and fatal signals without executing too much code in a signal handler
context. */
static int
bash_event_hook ()
{
/* If we're going to longjmp to top_level, make sure we clean up readline.
check_signals will call QUIT, which will eventually longjmp to top_level,
calling run_interrupt_trap along the way. The check for sigalrm_seen is
to clean up the read builtin's state. */
if (terminating_signal || interrupt_state || sigalrm_seen)
rl_cleanup_after_signal ();
bashline_reset_event_hook ();
check_signals_and_traps (); /* XXX */
return 0;
}
#endif /* READLINE */
| ./CrossVul/dataset_final_sorted/CWE-273/c/good_1198_2 |
crossvul-cpp_data_bad_1198_11 | /* shell.c -- GNU's idea of the POSIX shell specification. */
/* Copyright (C) 1987-2017 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Birthdate:
Sunday, January 10th, 1988.
Initial author: Brian Fox
*/
#define INSTALL_DEBUG_MODE
#include "config.h"
#include "bashtypes.h"
#if !defined (_MINIX) && defined (HAVE_SYS_FILE_H)
# include <sys/file.h>
#endif
#include "posixstat.h"
#include "posixtime.h"
#include "bashansi.h"
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include "filecntl.h"
#if defined (HAVE_PWD_H)
# include <pwd.h>
#endif
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashintl.h"
#define NEED_SH_SETLINEBUF_DECL /* used in externs.h */
#include "shell.h"
#include "parser.h"
#include "flags.h"
#include "trap.h"
#include "mailcheck.h"
#include "builtins.h"
#include "builtins/common.h"
#if defined (JOB_CONTROL)
#include "jobs.h"
#else
extern int running_in_background;
extern int initialize_job_control __P((int));
extern int get_tty_state __P((void));
#endif /* JOB_CONTROL */
#include "input.h"
#include "execute_cmd.h"
#include "findcmd.h"
#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
# include <malloc/shmalloc.h>
#endif
#if defined (HISTORY)
# include "bashhist.h"
# include <readline/history.h>
#endif
#if defined (READLINE)
# include <readline/readline.h>
# include "bashline.h"
#endif
#include <tilde/tilde.h>
#include <glob/strmatch.h>
#if defined (__OPENNT)
# include <opennt/opennt.h>
#endif
#if !defined (HAVE_GETPW_DECLS)
extern struct passwd *getpwuid ();
#endif /* !HAVE_GETPW_DECLS */
#if !defined (errno)
extern int errno;
#endif
#if defined (NO_MAIN_ENV_ARG)
extern char **environ; /* used if no third argument to main() */
#endif
extern int gnu_error_format;
/* Non-zero means that this shell has already been run; i.e. you should
call shell_reinitialize () if you need to start afresh. */
int shell_initialized = 0;
int bash_argv_initialized = 0;
COMMAND *global_command = (COMMAND *)NULL;
/* Information about the current user. */
struct user_info current_user =
{
(uid_t)-1, (uid_t)-1, (gid_t)-1, (gid_t)-1,
(char *)NULL, (char *)NULL, (char *)NULL
};
/* The current host's name. */
char *current_host_name = (char *)NULL;
/* Non-zero means that this shell is a login shell.
Specifically:
0 = not login shell.
1 = login shell from getty (or equivalent fake out)
-1 = login shell from "--login" (or -l) flag.
-2 = both from getty, and from flag.
*/
int login_shell = 0;
/* Non-zero means that at this moment, the shell is interactive. In
general, this means that the shell is at this moment reading input
from the keyboard. */
int interactive = 0;
/* Non-zero means that the shell was started as an interactive shell. */
int interactive_shell = 0;
/* Non-zero means to send a SIGHUP to all jobs when an interactive login
shell exits. */
int hup_on_exit = 0;
/* Non-zero means to list status of running and stopped jobs at shell exit */
int check_jobs_at_exit = 0;
/* Non-zero means to change to a directory name supplied as a command name */
int autocd = 0;
/* Tells what state the shell was in when it started:
0 = non-interactive shell script
1 = interactive
2 = -c command
3 = wordexp evaluation
This is a superset of the information provided by interactive_shell.
*/
int startup_state = 0;
int reading_shell_script = 0;
/* Special debugging helper. */
int debugging_login_shell = 0;
/* The environment that the shell passes to other commands. */
char **shell_environment;
/* Non-zero when we are executing a top-level command. */
int executing = 0;
/* The number of commands executed so far. */
int current_command_number = 1;
/* Non-zero is the recursion depth for commands. */
int indirection_level = 0;
/* The name of this shell, as taken from argv[0]. */
char *shell_name = (char *)NULL;
/* time in seconds when the shell was started */
time_t shell_start_time;
/* Are we running in an emacs shell window? */
int running_under_emacs;
/* Do we have /dev/fd? */
#ifdef HAVE_DEV_FD
int have_devfd = HAVE_DEV_FD;
#else
int have_devfd = 0;
#endif
/* The name of the .(shell)rc file. */
static char *bashrc_file = DEFAULT_BASHRC;
/* Non-zero means to act more like the Bourne shell on startup. */
static int act_like_sh;
/* Non-zero if this shell is being run by `su'. */
static int su_shell;
/* Non-zero if we have already expanded and sourced $ENV. */
static int sourced_env;
/* Is this shell running setuid? */
static int running_setuid;
/* Values for the long-winded argument names. */
static int debugging; /* Do debugging things. */
static int no_rc; /* Don't execute ~/.bashrc */
static int no_profile; /* Don't execute .profile */
static int do_version; /* Display interesting version info. */
static int make_login_shell; /* Make this shell be a `-bash' shell. */
static int want_initial_help; /* --help option */
int debugging_mode = 0; /* In debugging mode with --debugger */
#if defined (READLINE)
int no_line_editing = 0; /* non-zero -> don't do fancy line editing. */
#else
int no_line_editing = 1; /* can't have line editing without readline */
#endif
int dump_translatable_strings; /* Dump strings in $"...", don't execute. */
int dump_po_strings; /* Dump strings in $"..." in po format */
int wordexp_only = 0; /* Do word expansion only */
int protected_mode = 0; /* No command substitution with --wordexp */
int pretty_print_mode = 0; /* pretty-print a shell script */
#if defined (STRICT_POSIX)
int posixly_correct = 1; /* Non-zero means posix.2 superset. */
#else
int posixly_correct = 0; /* Non-zero means posix.2 superset. */
#endif
/* Some long-winded argument names. These are obviously new. */
#define Int 1
#define Charp 2
static const struct {
const char *name;
int type;
int *int_value;
char **char_value;
} long_args[] = {
{ "debug", Int, &debugging, (char **)0x0 },
#if defined (DEBUGGER)
{ "debugger", Int, &debugging_mode, (char **)0x0 },
#endif
{ "dump-po-strings", Int, &dump_po_strings, (char **)0x0 },
{ "dump-strings", Int, &dump_translatable_strings, (char **)0x0 },
{ "help", Int, &want_initial_help, (char **)0x0 },
{ "init-file", Charp, (int *)0x0, &bashrc_file },
{ "login", Int, &make_login_shell, (char **)0x0 },
{ "noediting", Int, &no_line_editing, (char **)0x0 },
{ "noprofile", Int, &no_profile, (char **)0x0 },
{ "norc", Int, &no_rc, (char **)0x0 },
{ "posix", Int, &posixly_correct, (char **)0x0 },
{ "pretty-print", Int, &pretty_print_mode, (char **)0x0 },
#if defined (WORDEXP_OPTION)
{ "protected", Int, &protected_mode, (char **)0x0 },
#endif
{ "rcfile", Charp, (int *)0x0, &bashrc_file },
#if defined (RESTRICTED_SHELL)
{ "restricted", Int, &restricted, (char **)0x0 },
#endif
{ "verbose", Int, &verbose_flag, (char **)0x0 },
{ "version", Int, &do_version, (char **)0x0 },
#if defined (WORDEXP_OPTION)
{ "wordexp", Int, &wordexp_only, (char **)0x0 },
#endif
{ (char *)0x0, Int, (int *)0x0, (char **)0x0 }
};
/* These are extern so execute_simple_command can set them, and then
longjmp back to main to execute a shell script, instead of calling
main () again and resulting in indefinite, possibly fatal, stack
growth. */
procenv_t subshell_top_level;
int subshell_argc;
char **subshell_argv;
char **subshell_envp;
char *exec_argv0;
#if defined (BUFFERED_INPUT)
/* The file descriptor from which the shell is reading input. */
int default_buffered_input = -1;
#endif
/* The following two variables are not static so they can show up in $-. */
int read_from_stdin; /* -s flag supplied */
int want_pending_command; /* -c flag supplied */
/* This variable is not static so it can be bound to $BASH_EXECUTION_STRING */
char *command_execution_string; /* argument to -c option */
char *shell_script_filename; /* shell script */
int malloc_trace_at_exit = 0;
static int shell_reinitialized = 0;
static FILE *default_input;
static STRING_INT_ALIST *shopt_alist;
static int shopt_ind = 0, shopt_len = 0;
static int parse_long_options __P((char **, int, int));
static int parse_shell_options __P((char **, int, int));
static int bind_args __P((char **, int, int, int));
static void start_debugger __P((void));
static void add_shopt_to_alist __P((char *, int));
static void run_shopt_alist __P((void));
static void execute_env_file __P((char *));
static void run_startup_files __P((void));
static int open_shell_script __P((char *));
static void set_bash_input __P((void));
static int run_one_command __P((char *));
#if defined (WORDEXP_OPTION)
static int run_wordexp __P((char *));
#endif
static int uidget __P((void));
static void init_interactive __P((void));
static void init_noninteractive __P((void));
static void init_interactive_script __P((void));
static void set_shell_name __P((char *));
static void shell_initialize __P((void));
static void shell_reinitialize __P((void));
static void show_shell_usage __P((FILE *, int));
#ifdef __CYGWIN__
static void
_cygwin32_check_tmp ()
{
struct stat sb;
if (stat ("/tmp", &sb) < 0)
internal_warning (_("could not find /tmp, please create!"));
else
{
if (S_ISDIR (sb.st_mode) == 0)
internal_warning (_("/tmp must be a valid directory name"));
}
}
#endif /* __CYGWIN__ */
#if defined (NO_MAIN_ENV_ARG)
/* systems without third argument to main() */
int
main (argc, argv)
int argc;
char **argv;
#else /* !NO_MAIN_ENV_ARG */
int
main (argc, argv, env)
int argc;
char **argv, **env;
#endif /* !NO_MAIN_ENV_ARG */
{
register int i;
int code, old_errexit_flag;
#if defined (RESTRICTED_SHELL)
int saverst;
#endif
volatile int locally_skip_execution;
volatile int arg_index, top_level_arg_index;
#ifdef __OPENNT
char **env;
env = environ;
#endif /* __OPENNT */
USE_VAR(argc);
USE_VAR(argv);
USE_VAR(env);
USE_VAR(code);
USE_VAR(old_errexit_flag);
#if defined (RESTRICTED_SHELL)
USE_VAR(saverst);
#endif
/* Catch early SIGINTs. */
code = setjmp_nosigs (top_level);
if (code)
exit (2);
xtrace_init ();
#if defined (USING_BASH_MALLOC) && defined (DEBUG) && !defined (DISABLE_MALLOC_WRAPPERS)
malloc_set_register (1); /* XXX - change to 1 for malloc debugging */
#endif
check_dev_tty ();
#ifdef __CYGWIN__
_cygwin32_check_tmp ();
#endif /* __CYGWIN__ */
/* Wait forever if we are debugging a login shell. */
while (debugging_login_shell) sleep (3);
set_default_locale ();
running_setuid = uidget ();
if (getenv ("POSIXLY_CORRECT") || getenv ("POSIX_PEDANTIC"))
posixly_correct = 1;
#if defined (USE_GNU_MALLOC_LIBRARY)
mcheck (programming_error, (void (*) ())0);
#endif /* USE_GNU_MALLOC_LIBRARY */
if (setjmp_sigs (subshell_top_level))
{
argc = subshell_argc;
argv = subshell_argv;
env = subshell_envp;
sourced_env = 0;
}
shell_reinitialized = 0;
/* Initialize `local' variables for all `invocations' of main (). */
arg_index = 1;
if (arg_index > argc)
arg_index = argc;
command_execution_string = shell_script_filename = (char *)NULL;
want_pending_command = locally_skip_execution = read_from_stdin = 0;
default_input = stdin;
#if defined (BUFFERED_INPUT)
default_buffered_input = -1;
#endif
/* Fix for the `infinite process creation' bug when running shell scripts
from startup files on System V. */
login_shell = make_login_shell = 0;
/* If this shell has already been run, then reinitialize it to a
vanilla state. */
if (shell_initialized || shell_name)
{
/* Make sure that we do not infinitely recurse as a login shell. */
if (*shell_name == '-')
shell_name++;
shell_reinitialize ();
if (setjmp_nosigs (top_level))
exit (2);
}
shell_environment = env;
set_shell_name (argv[0]);
shell_start_time = NOW; /* NOW now defined in general.h */
/* Parse argument flags from the input line. */
/* Find full word arguments first. */
arg_index = parse_long_options (argv, arg_index, argc);
if (want_initial_help)
{
show_shell_usage (stdout, 1);
exit (EXECUTION_SUCCESS);
}
if (do_version)
{
show_shell_version (1);
exit (EXECUTION_SUCCESS);
}
echo_input_at_read = verbose_flag; /* --verbose given */
/* All done with full word options; do standard shell option parsing.*/
this_command_name = shell_name; /* for error reporting */
arg_index = parse_shell_options (argv, arg_index, argc);
/* If user supplied the "--login" (or -l) flag, then set and invert
LOGIN_SHELL. */
if (make_login_shell)
{
login_shell++;
login_shell = -login_shell;
}
set_login_shell ("login_shell", login_shell != 0);
if (dump_po_strings)
dump_translatable_strings = 1;
if (dump_translatable_strings)
read_but_dont_execute = 1;
if (running_setuid && privileged_mode == 0)
disable_priv_mode ();
/* Need to get the argument to a -c option processed in the
above loop. The next arg is a command to execute, and the
following args are $0...$n respectively. */
if (want_pending_command)
{
command_execution_string = argv[arg_index];
if (command_execution_string == 0)
{
report_error (_("%s: option requires an argument"), "-c");
exit (EX_BADUSAGE);
}
arg_index++;
}
this_command_name = (char *)NULL;
/* First, let the outside world know about our interactive status.
A shell is interactive if the `-i' flag was given, or if all of
the following conditions are met:
no -c command
no arguments remaining or the -s flag given
standard input is a terminal
standard error is a terminal
Refer to Posix.2, the description of the `sh' utility. */
if (forced_interactive || /* -i flag */
(!command_execution_string && /* No -c command and ... */
wordexp_only == 0 && /* No --wordexp and ... */
((arg_index == argc) || /* no remaining args or... */
read_from_stdin) && /* -s flag with args, and */
isatty (fileno (stdin)) && /* Input is a terminal and */
isatty (fileno (stderr)))) /* error output is a terminal. */
init_interactive ();
else
init_noninteractive ();
/*
* Some systems have the bad habit of starting login shells with lots of open
* file descriptors. For instance, most systems that have picked up the
* pre-4.0 Sun YP code leave a file descriptor open each time you call one
* of the getpw* functions, and it's set to be open across execs. That
* means one for login, one for xterm, one for shelltool, etc. There are
* also systems that open persistent FDs to other agents or files as part
* of process startup; these need to be set to be close-on-exec.
*/
if (login_shell && interactive_shell)
{
for (i = 3; i < 20; i++)
SET_CLOSE_ON_EXEC (i);
}
/* If we're in a strict Posix.2 mode, turn on interactive comments,
alias expansion in non-interactive shells, and other Posix.2 things. */
if (posixly_correct)
{
bind_variable ("POSIXLY_CORRECT", "y", 0);
sv_strict_posix ("POSIXLY_CORRECT");
}
/* Now we run the shopt_alist and process the options. */
if (shopt_alist)
run_shopt_alist ();
/* From here on in, the shell must be a normal functioning shell.
Variables from the environment are expected to be set, etc. */
shell_initialize ();
set_default_lang ();
set_default_locale_vars ();
/*
* M-x term -> TERM=eterm-color INSIDE_EMACS='251,term:0.96' (eterm)
* M-x shell -> TERM='dumb' INSIDE_EMACS='25.1,comint' (no line editing)
*
* Older versions of Emacs may set EMACS to 't' or to something like
* '22.1 (term:0.96)' instead of (or in addition to) setting INSIDE_EMACS.
* They may set TERM to 'eterm' instead of 'eterm-color'. They may have
* a now-obsolete command that sets neither EMACS nor INSIDE_EMACS:
* M-x terminal -> TERM='emacs-em7955' (line editing)
*/
if (interactive_shell)
{
char *term, *emacs, *inside_emacs;
int emacs_term, in_emacs;
term = get_string_value ("TERM");
emacs = get_string_value ("EMACS");
inside_emacs = get_string_value ("INSIDE_EMACS");
if (inside_emacs)
{
emacs_term = strstr (inside_emacs, ",term:") != 0;
in_emacs = 1;
}
else if (emacs)
{
/* Infer whether we are in an older Emacs. */
emacs_term = strstr (emacs, " (term:") != 0;
in_emacs = emacs_term || STREQ (emacs, "t");
}
else
in_emacs = emacs_term = 0;
/* Not sure any emacs terminal emulator sets TERM=emacs any more */
no_line_editing |= STREQ (term, "emacs");
no_line_editing |= in_emacs && STREQ (term, "dumb");
/* running_under_emacs == 2 for `eterm' */
running_under_emacs = in_emacs || STREQN (term, "emacs", 5);
running_under_emacs += emacs_term && STREQN (term, "eterm", 5);
if (running_under_emacs)
gnu_error_format = 1;
}
top_level_arg_index = arg_index;
old_errexit_flag = exit_immediately_on_error;
/* Give this shell a place to longjmp to before executing the
startup files. This allows users to press C-c to abort the
lengthy startup. */
code = setjmp_sigs (top_level);
if (code)
{
if (code == EXITPROG || code == ERREXIT)
exit_shell (last_command_exit_value);
else
{
#if defined (JOB_CONTROL)
/* Reset job control, since run_startup_files turned it off. */
set_job_control (interactive_shell);
#endif
/* Reset value of `set -e', since it's turned off before running
the startup files. */
exit_immediately_on_error += old_errexit_flag;
locally_skip_execution++;
}
}
arg_index = top_level_arg_index;
/* Execute the start-up scripts. */
if (interactive_shell == 0)
{
unbind_variable ("PS1");
unbind_variable ("PS2");
interactive = 0;
#if 0
/* This has already been done by init_noninteractive */
expand_aliases = posixly_correct;
#endif
}
else
{
change_flag ('i', FLAG_ON);
interactive = 1;
}
#if defined (RESTRICTED_SHELL)
/* Set restricted_shell based on whether the basename of $0 indicates that
the shell should be restricted or if the `-r' option was supplied at
startup. */
restricted_shell = shell_is_restricted (shell_name);
/* If the `-r' option is supplied at invocation, make sure that the shell
is not in restricted mode when running the startup files. */
saverst = restricted;
restricted = 0;
#endif
/* Set positional parameters before running startup files. top_level_arg_index
holds the index of the current argument before setting the positional
parameters, so any changes performed in the startup files won't affect
later option processing. */
if (wordexp_only)
; /* nothing yet */
else if (command_execution_string)
arg_index = bind_args (argv, arg_index, argc, 0); /* $0 ... $n */
else if (arg_index != argc && read_from_stdin == 0)
{
shell_script_filename = argv[arg_index++];
arg_index = bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
}
else
arg_index = bind_args (argv, arg_index, argc, 1); /* $1 ... $n */
/* The startup files are run with `set -e' temporarily disabled. */
if (locally_skip_execution == 0 && running_setuid == 0)
{
old_errexit_flag = exit_immediately_on_error;
exit_immediately_on_error = 0;
run_startup_files ();
exit_immediately_on_error += old_errexit_flag;
}
/* If we are invoked as `sh', turn on Posix mode. */
if (act_like_sh)
{
bind_variable ("POSIXLY_CORRECT", "y", 0);
sv_strict_posix ("POSIXLY_CORRECT");
}
#if defined (RESTRICTED_SHELL)
/* Turn on the restrictions after executing the startup files. This
means that `bash -r' or `set -r' invoked from a startup file will
turn on the restrictions after the startup files are executed. */
restricted = saverst || restricted;
if (shell_reinitialized == 0)
maybe_make_restricted (shell_name);
#endif /* RESTRICTED_SHELL */
#if defined (WORDEXP_OPTION)
if (wordexp_only)
{
startup_state = 3;
last_command_exit_value = run_wordexp (argv[top_level_arg_index]);
exit_shell (last_command_exit_value);
}
#endif
cmd_init (); /* initialize the command object caches */
uwp_init ();
if (command_execution_string)
{
startup_state = 2;
if (debugging_mode)
start_debugger ();
#if defined (ONESHOT)
executing = 1;
run_one_command (command_execution_string);
exit_shell (last_command_exit_value);
#else /* ONESHOT */
with_input_from_string (command_execution_string, "-c");
goto read_and_execute;
#endif /* !ONESHOT */
}
/* Get possible input filename and set up default_buffered_input or
default_input as appropriate. */
if (shell_script_filename)
open_shell_script (shell_script_filename);
else if (interactive == 0)
{
/* In this mode, bash is reading a script from stdin, which is a
pipe or redirected file. */
#if defined (BUFFERED_INPUT)
default_buffered_input = fileno (stdin); /* == 0 */
#else
setbuf (default_input, (char *)NULL);
#endif /* !BUFFERED_INPUT */
read_from_stdin = 1;
}
else if (top_level_arg_index == argc) /* arg index before startup files */
/* "If there are no operands and the -c option is not specified, the -s
option shall be assumed." */
read_from_stdin = 1;
set_bash_input ();
if (debugging_mode && locally_skip_execution == 0 && running_setuid == 0 && (reading_shell_script || interactive_shell == 0))
start_debugger ();
/* Do the things that should be done only for interactive shells. */
if (interactive_shell)
{
/* Set up for checking for presence of mail. */
reset_mail_timer ();
init_mail_dates ();
#if defined (HISTORY)
/* Initialize the interactive history stuff. */
bash_initialize_history ();
/* Don't load the history from the history file if we've already
saved some lines in this session (e.g., by putting `history -s xx'
into one of the startup files). */
if (shell_initialized == 0 && history_lines_this_session == 0)
load_history ();
#endif /* HISTORY */
/* Initialize terminal state for interactive shells after the
.bash_profile and .bashrc are interpreted. */
get_tty_state ();
}
#if !defined (ONESHOT)
read_and_execute:
#endif /* !ONESHOT */
shell_initialized = 1;
if (pretty_print_mode && interactive_shell)
{
internal_warning (_("pretty-printing mode ignored in interactive shells"));
pretty_print_mode = 0;
}
if (pretty_print_mode)
exit_shell (pretty_print_loop ());
/* Read commands until exit condition. */
reader_loop ();
exit_shell (last_command_exit_value);
}
static int
parse_long_options (argv, arg_start, arg_end)
char **argv;
int arg_start, arg_end;
{
int arg_index, longarg, i;
char *arg_string;
arg_index = arg_start;
while ((arg_index != arg_end) && (arg_string = argv[arg_index]) &&
(*arg_string == '-'))
{
longarg = 0;
/* Make --login equivalent to -login. */
if (arg_string[1] == '-' && arg_string[2])
{
longarg = 1;
arg_string++;
}
for (i = 0; long_args[i].name; i++)
{
if (STREQ (arg_string + 1, long_args[i].name))
{
if (long_args[i].type == Int)
*long_args[i].int_value = 1;
else if (argv[++arg_index] == 0)
{
report_error (_("%s: option requires an argument"), long_args[i].name);
exit (EX_BADUSAGE);
}
else
*long_args[i].char_value = argv[arg_index];
break;
}
}
if (long_args[i].name == 0)
{
if (longarg)
{
report_error (_("%s: invalid option"), argv[arg_index]);
show_shell_usage (stderr, 0);
exit (EX_BADUSAGE);
}
break; /* No such argument. Maybe flag arg. */
}
arg_index++;
}
return (arg_index);
}
static int
parse_shell_options (argv, arg_start, arg_end)
char **argv;
int arg_start, arg_end;
{
int arg_index;
int arg_character, on_or_off, next_arg, i;
char *o_option, *arg_string;
arg_index = arg_start;
while (arg_index != arg_end && (arg_string = argv[arg_index]) &&
(*arg_string == '-' || *arg_string == '+'))
{
/* There are flag arguments, so parse them. */
next_arg = arg_index + 1;
/* A single `-' signals the end of options. From the 4.3 BSD sh.
An option `--' means the same thing; this is the standard
getopt(3) meaning. */
if (arg_string[0] == '-' &&
(arg_string[1] == '\0' ||
(arg_string[1] == '-' && arg_string[2] == '\0')))
return (next_arg);
i = 1;
on_or_off = arg_string[0];
while (arg_character = arg_string[i++])
{
switch (arg_character)
{
case 'c':
want_pending_command = 1;
break;
case 'l':
make_login_shell = 1;
break;
case 's':
read_from_stdin = 1;
break;
case 'o':
o_option = argv[next_arg];
if (o_option == 0)
{
list_minus_o_opts (-1, (on_or_off == '-') ? 0 : 1);
break;
}
if (set_minus_o_option (on_or_off, o_option) != EXECUTION_SUCCESS)
exit (EX_BADUSAGE);
next_arg++;
break;
case 'O':
/* Since some of these can be overridden by the normal
interactive/non-interactive shell initialization or
initializing posix mode, we save the options and process
them after initialization. */
o_option = argv[next_arg];
if (o_option == 0)
{
shopt_listopt (o_option, (on_or_off == '-') ? 0 : 1);
break;
}
add_shopt_to_alist (o_option, on_or_off);
next_arg++;
break;
case 'D':
dump_translatable_strings = 1;
break;
default:
if (change_flag (arg_character, on_or_off) == FLAG_ERROR)
{
report_error (_("%c%c: invalid option"), on_or_off, arg_character);
show_shell_usage (stderr, 0);
exit (EX_BADUSAGE);
}
}
}
/* Can't do just a simple increment anymore -- what about
"bash -abouo emacs ignoreeof -hP"? */
arg_index = next_arg;
}
return (arg_index);
}
/* Exit the shell with status S. */
void
exit_shell (s)
int s;
{
fflush (stdout); /* XXX */
fflush (stderr);
/* Clean up the terminal if we are in a state where it's been modified. */
#if defined (READLINE)
if (RL_ISSTATE (RL_STATE_TERMPREPPED) && rl_deprep_term_function)
(*rl_deprep_term_function) ();
#endif
if (read_tty_modified ())
read_tty_cleanup ();
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
#if defined (PROCESS_SUBSTITUTION)
unlink_fifo_list ();
#endif /* PROCESS_SUBSTITUTION */
#if defined (HISTORY)
if (remember_on_history)
maybe_save_shell_history ();
#endif /* HISTORY */
#if defined (COPROCESS_SUPPORT)
coproc_flush ();
#endif
#if defined (JOB_CONTROL)
/* If the user has run `shopt -s huponexit', hangup all jobs when we exit
an interactive login shell. ksh does this unconditionally. */
if (interactive_shell && login_shell && hup_on_exit)
hangup_all_jobs ();
/* If this shell is interactive, or job control is active, terminate all
stopped jobs and restore the original terminal process group. Don't do
this if we're in a subshell and calling exit_shell after, for example,
a failed word expansion. We want to do this even if the shell is not
interactive because we set the terminal's process group when job control
is enabled regardless of the interactive status. */
if (subshell_environment == 0)
end_job_control ();
#endif /* JOB_CONTROL */
/* Always return the exit status of the last command to our parent. */
sh_exit (s);
}
/* A wrapper for exit that (optionally) can do other things, like malloc
statistics tracing. */
void
sh_exit (s)
int s;
{
#if defined (MALLOC_DEBUG) && defined (USING_BASH_MALLOC)
if (malloc_trace_at_exit && (subshell_environment & (SUBSHELL_COMSUB|SUBSHELL_PROCSUB)) == 0)
trace_malloc_stats (get_name_for_error (), (char *)NULL);
/* mlocation_write_table (); */
#endif
exit (s);
}
/* Exit a subshell, which includes calling the exit trap. We don't want to
do any more cleanup, since a subshell is created as an exact copy of its
parent. */
void
subshell_exit (s)
int s;
{
fflush (stdout);
fflush (stderr);
/* Do trap[0] if defined. Allow it to override the exit status
passed to us. */
if (signal_is_trapped (0))
s = run_exit_trap ();
sh_exit (s);
}
/* Source the bash startup files. If POSIXLY_CORRECT is non-zero, we obey
the Posix.2 startup file rules: $ENV is expanded, and if the file it
names exists, that file is sourced. The Posix.2 rules are in effect
for interactive shells only. (section 4.56.5.3) */
/* Execute ~/.bashrc for most shells. Never execute it if
ACT_LIKE_SH is set, or if NO_RC is set.
If the executable file "/usr/gnu/src/bash/foo" contains:
#!/usr/gnu/bin/bash
echo hello
then:
COMMAND EXECUTE BASHRC
--------------------------------
bash -c foo NO
bash foo NO
foo NO
rsh machine ls YES (for rsh, which calls `bash -c')
rsh machine foo YES (for shell started by rsh) NO (for foo!)
echo ls | bash NO
login NO
bash YES
*/
static void
execute_env_file (env_file)
char *env_file;
{
char *fn;
if (env_file && *env_file)
{
fn = expand_string_unsplit_to_string (env_file, Q_DOUBLE_QUOTES);
if (fn && *fn)
maybe_execute_file (fn, 1);
FREE (fn);
}
}
static void
run_startup_files ()
{
#if defined (JOB_CONTROL)
int old_job_control;
#endif
int sourced_login, run_by_ssh;
/* get the rshd/sshd case out of the way first. */
if (interactive_shell == 0 && no_rc == 0 && login_shell == 0 &&
act_like_sh == 0 && command_execution_string)
{
#ifdef SSH_SOURCE_BASHRC
run_by_ssh = (find_variable ("SSH_CLIENT") != (SHELL_VAR *)0) ||
(find_variable ("SSH2_CLIENT") != (SHELL_VAR *)0);
#else
run_by_ssh = 0;
#endif
/* If we were run by sshd or we think we were run by rshd, execute
~/.bashrc if we are a top-level shell. */
if ((run_by_ssh || isnetconn (fileno (stdin))) && shell_level < 2)
{
#ifdef SYS_BASHRC
# if defined (__OPENNT)
maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
# else
maybe_execute_file (SYS_BASHRC, 1);
# endif
#endif
maybe_execute_file (bashrc_file, 1);
return;
}
}
#if defined (JOB_CONTROL)
/* Startup files should be run without job control enabled. */
old_job_control = interactive_shell ? set_job_control (0) : 0;
#endif
sourced_login = 0;
/* A shell begun with the --login (or -l) flag that is not in posix mode
runs the login shell startup files, no matter whether or not it is
interactive. If NON_INTERACTIVE_LOGIN_SHELLS is defined, run the
startup files if argv[0][0] == '-' as well. */
#if defined (NON_INTERACTIVE_LOGIN_SHELLS)
if (login_shell && posixly_correct == 0)
#else
if (login_shell < 0 && posixly_correct == 0)
#endif
{
/* We don't execute .bashrc for login shells. */
no_rc++;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (no_profile == 0)
{
maybe_execute_file (SYS_PROFILE, 1);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", 1);
else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
(maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
maybe_execute_file ("~/.profile", 1);
}
sourced_login = 1;
}
/* A non-interactive shell not named `sh' and not in posix mode reads and
executes commands from $BASH_ENV. If `su' starts a shell with `-c cmd'
and `-su' as the name of the shell, we want to read the startup files.
No other non-interactive shells read any startup files. */
if (interactive_shell == 0 && !(su_shell && login_shell))
{
if (posixly_correct == 0 && act_like_sh == 0 && privileged_mode == 0 &&
sourced_env++ == 0)
execute_env_file (get_string_value ("BASH_ENV"));
return;
}
/* Interactive shell or `-su' shell. */
if (posixly_correct == 0) /* bash, sh */
{
if (login_shell && sourced_login++ == 0)
{
/* We don't execute .bashrc for login shells. */
no_rc++;
/* Execute /etc/profile and one of the personal login shell
initialization files. */
if (no_profile == 0)
{
maybe_execute_file (SYS_PROFILE, 1);
if (act_like_sh) /* sh */
maybe_execute_file ("~/.profile", 1);
else if ((maybe_execute_file ("~/.bash_profile", 1) == 0) &&
(maybe_execute_file ("~/.bash_login", 1) == 0)) /* bash */
maybe_execute_file ("~/.profile", 1);
}
}
/* bash */
if (act_like_sh == 0 && no_rc == 0)
{
#ifdef SYS_BASHRC
# if defined (__OPENNT)
maybe_execute_file (_prefixInstallPath(SYS_BASHRC, NULL, 0), 1);
# else
maybe_execute_file (SYS_BASHRC, 1);
# endif
#endif
maybe_execute_file (bashrc_file, 1);
}
/* sh */
else if (act_like_sh && privileged_mode == 0 && sourced_env++ == 0)
execute_env_file (get_string_value ("ENV"));
}
else /* bash --posix, sh --posix */
{
/* bash and sh */
if (interactive_shell && privileged_mode == 0 && sourced_env++ == 0)
execute_env_file (get_string_value ("ENV"));
}
#if defined (JOB_CONTROL)
set_job_control (old_job_control);
#endif
}
#if defined (RESTRICTED_SHELL)
/* Return 1 if the shell should be a restricted one based on NAME or the
value of `restricted'. Don't actually do anything, just return a
boolean value. */
int
shell_is_restricted (name)
char *name;
{
char *temp;
if (restricted)
return 1;
temp = base_pathname (name);
if (*temp == '-')
temp++;
return (STREQ (temp, RESTRICTED_SHELL_NAME));
}
/* Perhaps make this shell a `restricted' one, based on NAME. If the
basename of NAME is "rbash", then this shell is restricted. The
name of the restricted shell is a configurable option, see config.h.
In a restricted shell, PATH, SHELL, ENV, and BASH_ENV are read-only
and non-unsettable.
Do this also if `restricted' is already set to 1; maybe the shell was
started with -r. */
int
maybe_make_restricted (name)
char *name;
{
char *temp;
temp = base_pathname (name);
if (*temp == '-')
temp++;
if (restricted || (STREQ (temp, RESTRICTED_SHELL_NAME)))
{
#if defined (RBASH_STATIC_PATH_VALUE)
bind_variable ("PATH", RBASH_STATIC_PATH_VALUE, 0);
stupidly_hack_special_variables ("PATH"); /* clear hash table */
#endif
set_var_read_only ("PATH");
set_var_read_only ("SHELL");
set_var_read_only ("ENV");
set_var_read_only ("BASH_ENV");
restricted = 1;
}
return (restricted);
}
#endif /* RESTRICTED_SHELL */
/* Fetch the current set of uids and gids and return 1 if we're running
setuid or setgid. */
static int
uidget ()
{
uid_t u;
u = getuid ();
if (current_user.uid != u)
{
FREE (current_user.user_name);
FREE (current_user.shell);
FREE (current_user.home_dir);
current_user.user_name = current_user.shell = current_user.home_dir = (char *)NULL;
}
current_user.uid = u;
current_user.gid = getgid ();
current_user.euid = geteuid ();
current_user.egid = getegid ();
/* See whether or not we are running setuid or setgid. */
return (current_user.uid != current_user.euid) ||
(current_user.gid != current_user.egid);
}
void
disable_priv_mode ()
{
int e;
if (setuid (current_user.uid) < 0)
{
e = errno;
sys_error (_("cannot set uid to %d: effective uid %d"), current_user.uid, current_user.euid);
#if defined (EXIT_ON_SETUID_FAILURE)
if (e == EAGAIN)
exit (e);
#endif
}
if (setgid (current_user.gid) < 0)
sys_error (_("cannot set gid to %d: effective gid %d"), current_user.gid, current_user.egid);
current_user.euid = current_user.uid;
current_user.egid = current_user.gid;
}
#if defined (WORDEXP_OPTION)
static int
run_wordexp (words)
char *words;
{
int code, nw, nb;
WORD_LIST *wl, *tl, *result;
code = setjmp_nosigs (top_level);
if (code != NOT_JUMPED)
{
switch (code)
{
/* Some kind of throw to top_level has occurred. */
case FORCE_EOF:
return last_command_exit_value = 127;
case ERREXIT:
case EXITPROG:
return last_command_exit_value;
case DISCARD:
return last_command_exit_value = 1;
default:
command_error ("run_wordexp", CMDERR_BADJUMP, code, 0);
}
}
/* Run it through the parser to get a list of words and expand them */
if (words && *words)
{
with_input_from_string (words, "--wordexp");
if (parse_command () != 0)
return (126);
if (global_command == 0)
{
printf ("0\n0\n");
return (0);
}
if (global_command->type != cm_simple)
return (126);
wl = global_command->value.Simple->words;
if (protected_mode)
for (tl = wl; tl; tl = tl->next)
tl->word->flags |= W_NOCOMSUB|W_NOPROCSUB;
result = wl ? expand_words_no_vars (wl) : (WORD_LIST *)0;
}
else
result = (WORD_LIST *)0;
last_command_exit_value = 0;
if (result == 0)
{
printf ("0\n0\n");
return (0);
}
/* Count up the number of words and bytes, and print them. Don't count
the trailing NUL byte. */
for (nw = nb = 0, wl = result; wl; wl = wl->next)
{
nw++;
nb += strlen (wl->word->word);
}
printf ("%u\n%u\n", nw, nb);
/* Print each word on a separate line. This will have to be changed when
the interface to glibc is completed. */
for (wl = result; wl; wl = wl->next)
printf ("%s\n", wl->word->word);
return (0);
}
#endif
#if defined (ONESHOT)
/* Run one command, given as the argument to the -c option. Tell
parse_and_execute not to fork for a simple command. */
static int
run_one_command (command)
char *command;
{
int code;
code = setjmp_nosigs (top_level);
if (code != NOT_JUMPED)
{
#if defined (PROCESS_SUBSTITUTION)
unlink_fifo_list ();
#endif /* PROCESS_SUBSTITUTION */
switch (code)
{
/* Some kind of throw to top_level has occurred. */
case FORCE_EOF:
return last_command_exit_value = 127;
case ERREXIT:
case EXITPROG:
return last_command_exit_value;
case DISCARD:
return last_command_exit_value = 1;
default:
command_error ("run_one_command", CMDERR_BADJUMP, code, 0);
}
}
return (parse_and_execute (savestring (command), "-c", SEVAL_NOHIST));
}
#endif /* ONESHOT */
static int
bind_args (argv, arg_start, arg_end, start_index)
char **argv;
int arg_start, arg_end, start_index;
{
register int i;
WORD_LIST *args, *tl;
for (i = arg_start, args = tl = (WORD_LIST *)NULL; i < arg_end; i++)
{
if (args == 0)
args = tl = make_word_list (make_word (argv[i]), args);
else
{
tl->next = make_word_list (make_word (argv[i]), (WORD_LIST *)NULL);
tl = tl->next;
}
}
if (args)
{
if (start_index == 0) /* bind to $0...$n for sh -c command */
{
/* Posix.2 4.56.3 says that the first argument after sh -c command
becomes $0, and the rest of the arguments become $1...$n */
shell_name = savestring (args->word->word);
FREE (dollar_vars[0]);
dollar_vars[0] = savestring (args->word->word);
remember_args (args->next, 1);
if (debugging_mode)
{
push_args (args->next); /* BASH_ARGV and BASH_ARGC */
bash_argv_initialized = 1;
}
}
else /* bind to $1...$n for shell script */
{
remember_args (args, 1);
/* We do this unconditionally so something like -O extdebug doesn't
do it first. We're setting the definitive positional params
here. */
if (debugging_mode)
{
push_args (args); /* BASH_ARGV and BASH_ARGC */
bash_argv_initialized = 1;
}
}
dispose_words (args);
}
return (i);
}
void
unbind_args ()
{
remember_args ((WORD_LIST *)NULL, 1);
pop_args (); /* Reset BASH_ARGV and BASH_ARGC */
}
static void
start_debugger ()
{
#if defined (DEBUGGER) && defined (DEBUGGER_START_FILE)
int old_errexit;
int r;
old_errexit = exit_immediately_on_error;
exit_immediately_on_error = 0;
r = force_execute_file (DEBUGGER_START_FILE, 1);
if (r < 0)
{
internal_warning (_("cannot start debugger; debugging mode disabled"));
debugging_mode = 0;
}
error_trace_mode = function_trace_mode = debugging_mode;
set_shellopts ();
set_bashopts ();
exit_immediately_on_error += old_errexit;
#endif
}
static int
open_shell_script (script_name)
char *script_name;
{
int fd, e, fd_is_tty;
char *filename, *path_filename, *t;
char sample[80];
int sample_len;
struct stat sb;
#if defined (ARRAY_VARS)
SHELL_VAR *funcname_v, *bash_source_v, *bash_lineno_v;
ARRAY *funcname_a, *bash_source_a, *bash_lineno_a;
#endif
filename = savestring (script_name);
fd = open (filename, O_RDONLY);
if ((fd < 0) && (errno == ENOENT) && (absolute_program (filename) == 0))
{
e = errno;
/* If it's not in the current directory, try looking through PATH
for it. */
path_filename = find_path_file (script_name);
if (path_filename)
{
free (filename);
filename = path_filename;
fd = open (filename, O_RDONLY);
}
else
errno = e;
}
if (fd < 0)
{
e = errno;
file_error (filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
sh_exit ((e == ENOENT) ? EX_NOTFOUND : EX_NOINPUT);
}
free (dollar_vars[0]);
dollar_vars[0] = exec_argv0 ? savestring (exec_argv0) : savestring (script_name);
if (exec_argv0)
{
free (exec_argv0);
exec_argv0 = (char *)NULL;
}
if (file_isdir (filename))
{
#if defined (EISDIR)
errno = EISDIR;
#else
errno = EINVAL;
#endif
file_error (filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
sh_exit (EX_NOINPUT);
}
#if defined (ARRAY_VARS)
GET_ARRAY_FROM_VAR ("FUNCNAME", funcname_v, funcname_a);
GET_ARRAY_FROM_VAR ("BASH_SOURCE", bash_source_v, bash_source_a);
GET_ARRAY_FROM_VAR ("BASH_LINENO", bash_lineno_v, bash_lineno_a);
array_push (bash_source_a, filename);
if (bash_lineno_a)
{
t = itos (executing_line_number ());
array_push (bash_lineno_a, t);
free (t);
}
array_push (funcname_a, "main");
#endif
#ifdef HAVE_DEV_FD
fd_is_tty = isatty (fd);
#else
fd_is_tty = 0;
#endif
/* Only do this with non-tty file descriptors we can seek on. */
if (fd_is_tty == 0 && (lseek (fd, 0L, 1) != -1))
{
/* Check to see if the `file' in `bash file' is a binary file
according to the same tests done by execute_simple_command (),
and report an error and exit if it is. */
sample_len = read (fd, sample, sizeof (sample));
if (sample_len < 0)
{
e = errno;
if ((fstat (fd, &sb) == 0) && S_ISDIR (sb.st_mode))
{
#if defined (EISDIR)
errno = EISDIR;
file_error (filename);
#else
internal_error (_("%s: Is a directory"), filename);
#endif
}
else
{
errno = e;
file_error (filename);
}
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
exit (EX_NOEXEC);
}
else if (sample_len > 0 && (check_binary_file (sample, sample_len)))
{
internal_error (_("%s: cannot execute binary file"), filename);
#if defined (JOB_CONTROL)
end_job_control (); /* just in case we were run as bash -i script */
#endif
exit (EX_BINARY_FILE);
}
/* Now rewind the file back to the beginning. */
lseek (fd, 0L, 0);
}
/* Open the script. But try to move the file descriptor to a randomly
large one, in the hopes that any descriptors used by the script will
not match with ours. */
fd = move_to_high_fd (fd, 1, -1);
#if defined (BUFFERED_INPUT)
default_buffered_input = fd;
SET_CLOSE_ON_EXEC (default_buffered_input);
#else /* !BUFFERED_INPUT */
default_input = fdopen (fd, "r");
if (default_input == 0)
{
file_error (filename);
exit (EX_NOTFOUND);
}
SET_CLOSE_ON_EXEC (fd);
if (fileno (default_input) != fd)
SET_CLOSE_ON_EXEC (fileno (default_input));
#endif /* !BUFFERED_INPUT */
/* Just about the only way for this code to be executed is if something
like `bash -i /dev/stdin' is executed. */
if (interactive_shell && fd_is_tty)
{
dup2 (fd, 0);
close (fd);
fd = 0;
#if defined (BUFFERED_INPUT)
default_buffered_input = 0;
#else
fclose (default_input);
default_input = stdin;
#endif
}
else if (forced_interactive && fd_is_tty == 0)
/* But if a script is called with something like `bash -i scriptname',
we need to do a non-interactive setup here, since we didn't do it
before. */
init_interactive_script ();
free (filename);
reading_shell_script = 1;
return (fd);
}
/* Initialize the input routines for the parser. */
static void
set_bash_input ()
{
/* Make sure the fd from which we are reading input is not in
no-delay mode. */
#if defined (BUFFERED_INPUT)
if (interactive == 0)
sh_unset_nodelay_mode (default_buffered_input);
else
#endif /* !BUFFERED_INPUT */
sh_unset_nodelay_mode (fileno (stdin));
/* with_input_from_stdin really means `with_input_from_readline' */
if (interactive && no_line_editing == 0)
with_input_from_stdin ();
#if defined (BUFFERED_INPUT)
else if (interactive == 0)
with_input_from_buffered_stream (default_buffered_input, dollar_vars[0]);
#endif /* BUFFERED_INPUT */
else
with_input_from_stream (default_input, dollar_vars[0]);
}
/* Close the current shell script input source and forget about it. This is
extern so execute_cmd.c:initialize_subshell() can call it. If CHECK_ZERO
is non-zero, we close default_buffered_input even if it's the standard
input (fd 0). */
void
unset_bash_input (check_zero)
int check_zero;
{
#if defined (BUFFERED_INPUT)
if ((check_zero && default_buffered_input >= 0) ||
(check_zero == 0 && default_buffered_input > 0))
{
close_buffered_fd (default_buffered_input);
default_buffered_input = bash_input.location.buffered_fd = -1;
bash_input.type = st_none; /* XXX */
}
#else /* !BUFFERED_INPUT */
if (default_input)
{
fclose (default_input);
default_input = (FILE *)NULL;
}
#endif /* !BUFFERED_INPUT */
}
#if !defined (PROGRAM)
# define PROGRAM "bash"
#endif
static void
set_shell_name (argv0)
char *argv0;
{
/* Here's a hack. If the name of this shell is "sh", then don't do
any startup files; just try to be more like /bin/sh. */
shell_name = argv0 ? base_pathname (argv0) : PROGRAM;
if (argv0 && *argv0 == '-')
{
if (*shell_name == '-')
shell_name++;
login_shell = 1;
}
if (shell_name[0] == 's' && shell_name[1] == 'h' && shell_name[2] == '\0')
act_like_sh++;
if (shell_name[0] == 's' && shell_name[1] == 'u' && shell_name[2] == '\0')
su_shell++;
shell_name = argv0 ? argv0 : PROGRAM;
FREE (dollar_vars[0]);
dollar_vars[0] = savestring (shell_name);
/* A program may start an interactive shell with
"execl ("/bin/bash", "-", NULL)".
If so, default the name of this shell to our name. */
if (!shell_name || !*shell_name || (shell_name[0] == '-' && !shell_name[1]))
shell_name = PROGRAM;
}
static void
init_interactive ()
{
expand_aliases = interactive_shell = startup_state = 1;
interactive = 1;
#if defined (HISTORY)
remember_on_history = enable_history_list = 1; /* XXX */
# if defined (BANG_HISTORY)
histexp_flag = history_expansion; /* XXX */
# endif
#endif
}
static void
init_noninteractive ()
{
#if defined (HISTORY)
bash_history_reinit (0);
#endif /* HISTORY */
interactive_shell = startup_state = interactive = 0;
expand_aliases = posixly_correct; /* XXX - was 0 not posixly_correct */
no_line_editing = 1;
#if defined (JOB_CONTROL)
/* Even if the shell is not interactive, enable job control if the -i or
-m option is supplied at startup. */
set_job_control (forced_interactive||jobs_m_flag);
#endif /* JOB_CONTROL */
}
static void
init_interactive_script ()
{
init_noninteractive ();
expand_aliases = interactive_shell = startup_state = 1;
#if defined (HISTORY)
remember_on_history = enable_history_list = 1; /* XXX */
#endif
}
void
get_current_user_info ()
{
struct passwd *entry;
/* Don't fetch this more than once. */
if (current_user.user_name == 0)
{
#if defined (__TANDEM)
entry = getpwnam (getlogin ());
#else
entry = getpwuid (current_user.uid);
#endif
if (entry)
{
current_user.user_name = savestring (entry->pw_name);
current_user.shell = (entry->pw_shell && entry->pw_shell[0])
? savestring (entry->pw_shell)
: savestring ("/bin/sh");
current_user.home_dir = savestring (entry->pw_dir);
}
else
{
current_user.user_name = _("I have no name!");
current_user.user_name = savestring (current_user.user_name);
current_user.shell = savestring ("/bin/sh");
current_user.home_dir = savestring ("/");
}
#if defined (HAVE_GETPWENT)
endpwent ();
#endif
}
}
/* Do whatever is necessary to initialize the shell.
Put new initializations in here. */
static void
shell_initialize ()
{
char hostname[256];
int should_be_restricted;
/* Line buffer output for stderr and stdout. */
if (shell_initialized == 0)
{
sh_setlinebuf (stderr);
sh_setlinebuf (stdout);
}
/* Sort the array of shell builtins so that the binary search in
find_shell_builtin () works correctly. */
initialize_shell_builtins ();
/* Initialize the trap signal handlers before installing our own
signal handlers. traps.c:restore_original_signals () is responsible
for restoring the original default signal handlers. That function
is called when we make a new child. */
initialize_traps ();
initialize_signals (0);
/* It's highly unlikely that this will change. */
if (current_host_name == 0)
{
/* Initialize current_host_name. */
if (gethostname (hostname, 255) < 0)
current_host_name = "??host??";
else
current_host_name = savestring (hostname);
}
/* Initialize the stuff in current_user that comes from the password
file. We don't need to do this right away if the shell is not
interactive. */
if (interactive_shell)
get_current_user_info ();
/* Initialize our interface to the tilde expander. */
tilde_initialize ();
#if defined (RESTRICTED_SHELL)
should_be_restricted = shell_is_restricted (shell_name);
#endif
/* Initialize internal and environment variables. Don't import shell
functions from the environment if we are running in privileged or
restricted mode or if the shell is running setuid. */
#if defined (RESTRICTED_SHELL)
initialize_shell_variables (shell_environment, privileged_mode||restricted||should_be_restricted||running_setuid);
#else
initialize_shell_variables (shell_environment, privileged_mode||running_setuid);
#endif
/* Initialize the data structures for storing and running jobs. */
initialize_job_control (jobs_m_flag);
/* Initialize input streams to null. */
initialize_bash_input ();
initialize_flags ();
/* Initialize the shell options. Don't import the shell options
from the environment variables $SHELLOPTS or $BASHOPTS if we are
running in privileged or restricted mode or if the shell is running
setuid. */
#if defined (RESTRICTED_SHELL)
initialize_shell_options (privileged_mode||restricted||should_be_restricted||running_setuid);
initialize_bashopts (privileged_mode||restricted||should_be_restricted||running_setuid);
#else
initialize_shell_options (privileged_mode||running_setuid);
initialize_bashopts (privileged_mode||running_setuid);
#endif
}
/* Function called by main () when it appears that the shell has already
had some initialization performed. This is supposed to reset the world
back to a pristine state, as if we had been exec'ed. */
static void
shell_reinitialize ()
{
/* The default shell prompts. */
primary_prompt = PPROMPT;
secondary_prompt = SPROMPT;
/* Things that get 1. */
current_command_number = 1;
/* We have decided that the ~/.bashrc file should not be executed
for the invocation of each shell script. If the variable $ENV
(or $BASH_ENV) is set, its value is used as the name of a file
to source. */
no_rc = no_profile = 1;
/* Things that get 0. */
login_shell = make_login_shell = interactive = executing = 0;
debugging = do_version = line_number = last_command_exit_value = 0;
forced_interactive = interactive_shell = 0;
subshell_environment = running_in_background = 0;
expand_aliases = 0;
bash_argv_initialized = 0;
/* XXX - should we set jobs_m_flag to 0 here? */
#if defined (HISTORY)
bash_history_reinit (enable_history_list = 0);
#endif /* HISTORY */
#if defined (RESTRICTED_SHELL)
restricted = 0;
#endif /* RESTRICTED_SHELL */
/* Ensure that the default startup file is used. (Except that we don't
execute this file for reinitialized shells). */
bashrc_file = DEFAULT_BASHRC;
/* Delete all variables and functions. They will be reinitialized when
the environment is parsed. */
delete_all_contexts (shell_variables);
delete_all_variables (shell_functions);
reinit_special_variables ();
#if defined (READLINE)
bashline_reinitialize ();
#endif
shell_reinitialized = 1;
}
static void
show_shell_usage (fp, extra)
FILE *fp;
int extra;
{
int i;
char *set_opts, *s, *t;
if (extra)
fprintf (fp, _("GNU bash, version %s-(%s)\n"), shell_version_string (), MACHTYPE);
fprintf (fp, _("Usage:\t%s [GNU long option] [option] ...\n\t%s [GNU long option] [option] script-file ...\n"),
shell_name, shell_name);
fputs (_("GNU long options:\n"), fp);
for (i = 0; long_args[i].name; i++)
fprintf (fp, "\t--%s\n", long_args[i].name);
fputs (_("Shell options:\n"), fp);
fputs (_("\t-ilrsD or -c command or -O shopt_option\t\t(invocation only)\n"), fp);
for (i = 0, set_opts = 0; shell_builtins[i].name; i++)
if (STREQ (shell_builtins[i].name, "set"))
{
set_opts = savestring (shell_builtins[i].short_doc);
break;
}
if (set_opts)
{
s = strchr (set_opts, '[');
if (s == 0)
s = set_opts;
while (*++s == '-')
;
t = strchr (s, ']');
if (t)
*t = '\0';
fprintf (fp, _("\t-%s or -o option\n"), s);
free (set_opts);
}
if (extra)
{
fprintf (fp, _("Type `%s -c \"help set\"' for more information about shell options.\n"), shell_name);
fprintf (fp, _("Type `%s -c help' for more information about shell builtin commands.\n"), shell_name);
fprintf (fp, _("Use the `bashbug' command to report bugs.\n"));
fprintf (fp, "\n");
fprintf (fp, _("bash home page: <http://www.gnu.org/software/bash>\n"));
fprintf (fp, _("General help using GNU software: <http://www.gnu.org/gethelp/>\n"));
}
}
static void
add_shopt_to_alist (opt, on_or_off)
char *opt;
int on_or_off;
{
if (shopt_ind >= shopt_len)
{
shopt_len += 8;
shopt_alist = (STRING_INT_ALIST *)xrealloc (shopt_alist, shopt_len * sizeof (shopt_alist[0]));
}
shopt_alist[shopt_ind].word = opt;
shopt_alist[shopt_ind].token = on_or_off;
shopt_ind++;
}
static void
run_shopt_alist ()
{
register int i;
for (i = 0; i < shopt_ind; i++)
if (shopt_setopt (shopt_alist[i].word, (shopt_alist[i].token == '-')) != EXECUTION_SUCCESS)
exit (EX_BADUSAGE);
free (shopt_alist);
shopt_alist = 0;
shopt_ind = shopt_len = 0;
}
| ./CrossVul/dataset_final_sorted/CWE-273/c/bad_1198_11 |
crossvul-cpp_data_bad_1198_9 | /* glob.c -- file-name wildcard pattern matching for Bash.
Copyright (C) 1985-2019 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne-Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
/* To whomever it may concern: I have never seen the code which most
Unix programs use to perform this function. I wrote this from scratch
based on specifications for the pattern matching. --RMS. */
#include <config.h>
#if !defined (__GNUC__) && !defined (HAVE_ALLOCA_H) && defined (_AIX)
#pragma alloca
#endif /* _AIX && RISC6000 && !__GNUC__ */
#include "bashtypes.h"
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#include "bashansi.h"
#include "posixdir.h"
#include "posixstat.h"
#include "shmbutil.h"
#include "xmalloc.h"
#include "filecntl.h"
#if !defined (F_OK)
# define F_OK 0
#endif
#include "stdc.h"
#include "memalloc.h"
#include <signal.h>
#include "shell.h"
#include "general.h"
#include "glob.h"
#include "strmatch.h"
#if !defined (HAVE_BCOPY) && !defined (bcopy)
# define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
#endif /* !HAVE_BCOPY && !bcopy */
#if !defined (NULL)
# if defined (__STDC__)
# define NULL ((void *) 0)
# else
# define NULL 0x0
# endif /* __STDC__ */
#endif /* !NULL */
#if !defined (FREE)
# define FREE(x) if (x) free (x)
#endif
/* Don't try to alloca() more than this much memory for `struct globval'
in glob_vector() */
#ifndef ALLOCA_MAX
# define ALLOCA_MAX 100000
#endif
struct globval
{
struct globval *next;
char *name;
};
extern void throw_to_top_level __P((void));
extern int sh_eaccess __P((const char *, int));
extern char *sh_makepath __P((const char *, const char *, int));
extern int signal_is_pending __P((int));
extern void run_pending_traps __P((void));
extern int extended_glob;
extern int posix_glob_backslash;
/* Global variable which controls whether or not * matches .*.
Non-zero means don't match .*. */
int noglob_dot_filenames = 1;
/* Global variable which controls whether or not filename globbing
is done without regard to case. */
int glob_ignore_case = 0;
/* Global variable controlling whether globbing ever returns . or ..
regardless of the pattern. If set to 1, no glob pattern will ever
match `.' or `..'. Disabled by default. */
int glob_always_skip_dot_and_dotdot = 0;
/* Global variable to return to signify an error in globbing. */
char *glob_error_return;
static struct globval finddirs_error_return;
/* Some forward declarations. */
static int skipname __P((char *, char *, int));
#if HANDLE_MULTIBYTE
static int mbskipname __P((char *, char *, int));
#endif
#if HANDLE_MULTIBYTE
static void udequote_pathname __P((char *));
static void wdequote_pathname __P((char *));
#else
# define dequote_pathname udequote_pathname
#endif
static void dequote_pathname __P((char *));
static int glob_testdir __P((char *, int));
static char **glob_dir_to_array __P((char *, char **, int));
/* Make sure these names continue to agree with what's in smatch.c */
extern char *glob_patscan __P((char *, char *, int));
extern wchar_t *glob_patscan_wc __P((wchar_t *, wchar_t *, int));
/* And this from gmisc.c/gm_loop.c */
extern int wextglob_pattern_p __P((wchar_t *));
extern char *glob_dirscan __P((char *, int));
/* Compile `glob_loop.c' for single-byte characters. */
#define GCHAR unsigned char
#define CHAR char
#define INT int
#define L(CS) CS
#define INTERNAL_GLOB_PATTERN_P internal_glob_pattern_p
#include "glob_loop.c"
/* Compile `glob_loop.c' again for multibyte characters. */
#if HANDLE_MULTIBYTE
#define GCHAR wchar_t
#define CHAR wchar_t
#define INT wint_t
#define L(CS) L##CS
#define INTERNAL_GLOB_PATTERN_P internal_glob_wpattern_p
#include "glob_loop.c"
#endif /* HANDLE_MULTIBYTE */
/* And now a function that calls either the single-byte or multibyte version
of internal_glob_pattern_p. */
int
glob_pattern_p (pattern)
const char *pattern;
{
#if HANDLE_MULTIBYTE
size_t n;
wchar_t *wpattern;
int r;
if (MB_CUR_MAX == 1 || mbsmbchar (pattern) == 0)
return (internal_glob_pattern_p ((unsigned char *)pattern));
/* Convert strings to wide chars, and call the multibyte version. */
n = xdupmbstowcs (&wpattern, NULL, pattern);
if (n == (size_t)-1)
/* Oops. Invalid multibyte sequence. Try it as single-byte sequence. */
return (internal_glob_pattern_p ((unsigned char *)pattern));
r = internal_glob_wpattern_p (wpattern);
free (wpattern);
return r;
#else
return (internal_glob_pattern_p ((unsigned char *)pattern));
#endif
}
#if EXTENDED_GLOB
/* Return 1 if all subpatterns in the extended globbing pattern PAT indicate
that the name should be skipped. XXX - doesn't handle pattern negation,
not sure if it should */
static int
extglob_skipname (pat, dname, flags)
char *pat, *dname;
int flags;
{
char *pp, *pe, *t, *se;
int n, r, negate, wild, nullpat;
negate = *pat == '!';
wild = *pat == '*' || *pat == '?';
pp = pat + 2;
se = pp + strlen (pp) - 1; /* end of string */
pe = glob_patscan (pp, se, 0); /* end of extglob pattern (( */
/* we should check for invalid extglob pattern here */
if (pe == 0)
return 0;
/* if pe != se we have more of the pattern at the end of the extglob
pattern. Check the easy case first ( */
if (pe == se && *pe == ')' && (t = strchr (pp, '|')) == 0)
{
*pe = '\0';
#if defined (HANDLE_MULTIBYTE)
r = mbskipname (pp, dname, flags);
#else
r = skipname (pp, dname, flags); /*(*/
#endif
*pe = ')';
if (wild && pe[1]) /* if we can match zero instances, check further */
return (skipname (pe+1, dname, flags));
return r;
}
/* Is the extglob pattern between the parens the null pattern? The null
pattern can match nothing, so should we check any remaining portion of
the pattern? */
nullpat = pe >= (pat + 2) && pe[-2] == '(' && pe[-1] == ')';
/* check every subpattern */
while (t = glob_patscan (pp, pe, '|'))
{
n = t[-1]; /* ( */
if (extglob_pattern_p (pp) && n == ')')
t[-1] = n; /* no-op for now */
else
t[-1] = '\0';
#if defined (HANDLE_MULTIBYTE)
r = mbskipname (pp, dname, flags);
#else
r = skipname (pp, dname, flags);
#endif
t[-1] = n;
if (r == 0) /* if any pattern says not skip, we don't skip */
return r;
pp = t;
} /*(*/
/* glob_patscan might find end of string */
if (pp == se)
return r;
/* but if it doesn't then we didn't match a leading dot */
if (wild && *pe) /* if we can match zero instances, check further */
return (skipname (pe, dname, flags));
return 1;
}
#endif
/* Return 1 if DNAME should be skipped according to PAT. Mostly concerned
with matching leading `.'. */
static int
skipname (pat, dname, flags)
char *pat;
char *dname;
int flags;
{
#if EXTENDED_GLOB
if (extglob_pattern_p (pat)) /* XXX */
return (extglob_skipname (pat, dname, flags));
#endif
if (glob_always_skip_dot_and_dotdot && DOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot need not be explicitly matched, and the pattern
doesn't start with a `.', don't match `.' or `..' */
if (noglob_dot_filenames == 0 && pat[0] != '.' &&
(pat[0] != '\\' || pat[1] != '.') &&
DOT_OR_DOTDOT (dname))
return 1;
/* If a dot must be explicitly matched, check to see if they do. */
else if (noglob_dot_filenames && dname[0] == '.' && pat[0] != '.' &&
(pat[0] != '\\' || pat[1] != '.'))
return 1;
return 0;
}
#if HANDLE_MULTIBYTE
static int
wskipname (pat, dname, flags)
wchar_t *pat, *dname;
int flags;
{
if (glob_always_skip_dot_and_dotdot && WDOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot need not be explicitly matched, and the
pattern doesn't start with a `.', don't match `.' or `..' */
if (noglob_dot_filenames == 0 && pat[0] != L'.' &&
(pat[0] != L'\\' || pat[1] != L'.') &&
WDOT_OR_DOTDOT (dname))
return 1;
/* If a leading dot must be explicitly matched, check to see if the
pattern and dirname both have one. */
else if (noglob_dot_filenames && dname[0] == L'.' &&
pat[0] != L'.' &&
(pat[0] != L'\\' || pat[1] != L'.'))
return 1;
return 0;
}
static int
wextglob_skipname (pat, dname, flags)
wchar_t *pat, *dname;
int flags;
{
#if EXTENDED_GLOB
wchar_t *pp, *pe, *t, n, *se;
int r, negate, wild, nullpat;
negate = *pat == L'!';
wild = *pat == L'*' || *pat == L'?';
pp = pat + 2;
se = pp + wcslen (pp) - 1; /*(*/
pe = glob_patscan_wc (pp, se, 0);
if (pe == se && *pe == ')' && (t = wcschr (pp, L'|')) == 0)
{
*pe = L'\0';
r = wskipname (pp, dname, flags); /*(*/
*pe = L')';
if (wild && pe[1] != L'\0')
return (wskipname (pe+1, dname, flags));
return r;
}
/* Is the extglob pattern between the parens the null pattern? The null
pattern can match nothing, so should we check any remaining portion of
the pattern? */
nullpat = pe >= (pat + 2) && pe[-2] == L'(' && pe[-1] == L')';
/* check every subpattern */
while (t = glob_patscan_wc (pp, pe, '|'))
{
n = t[-1]; /* ( */
if (wextglob_pattern_p (pp) && n == L')')
t[-1] = n; /* no-op for now */
else
t[-1] = L'\0';
r = wskipname (pp, dname, flags);
t[-1] = n;
if (r == 0)
return 0;
pp = t;
}
if (pp == pe) /* glob_patscan_wc might find end of pattern */
return r;
/* but if it doesn't then we didn't match a leading dot */
if (wild && *pe != L'\0')
return (wskipname (pe, dname, flags));
return 1;
#else
return (wskipname (pat, dname, flags));
#endif
}
/* Return 1 if DNAME should be skipped according to PAT. Handles multibyte
characters in PAT and DNAME. Mostly concerned with matching leading `.'. */
static int
mbskipname (pat, dname, flags)
char *pat, *dname;
int flags;
{
int ret, ext;
wchar_t *pat_wc, *dn_wc;
size_t pat_n, dn_n;
if (mbsmbchar (dname) == 0 && mbsmbchar (pat) == 0)
return (skipname (pat, dname, flags));
ext = 0;
#if EXTENDED_GLOB
ext = extglob_pattern_p (pat);
#endif
pat_wc = dn_wc = (wchar_t *)NULL;
pat_n = xdupmbstowcs (&pat_wc, NULL, pat);
if (pat_n != (size_t)-1)
dn_n = xdupmbstowcs (&dn_wc, NULL, dname);
ret = 0;
if (pat_n != (size_t)-1 && dn_n !=(size_t)-1)
ret = ext ? wextglob_skipname (pat_wc, dn_wc, flags) : wskipname (pat_wc, dn_wc, flags);
else
ret = skipname (pat, dname, flags);
FREE (pat_wc);
FREE (dn_wc);
return ret;
}
#endif /* HANDLE_MULTIBYTE */
/* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */
static void
udequote_pathname (pathname)
char *pathname;
{
register int i, j;
for (i = j = 0; pathname && pathname[i]; )
{
if (pathname[i] == '\\')
i++;
pathname[j++] = pathname[i++];
if (pathname[i - 1] == 0)
break;
}
if (pathname)
pathname[j] = '\0';
}
#if HANDLE_MULTIBYTE
/* Remove backslashes quoting characters in PATHNAME by modifying PATHNAME. */
static void
wdequote_pathname (pathname)
char *pathname;
{
mbstate_t ps;
size_t len, n;
wchar_t *wpathname;
int i, j;
wchar_t *orig_wpathname;
if (mbsmbchar (pathname) == 0)
{
udequote_pathname (pathname);
return;
}
len = strlen (pathname);
/* Convert the strings into wide characters. */
n = xdupmbstowcs (&wpathname, NULL, pathname);
if (n == (size_t) -1)
{
/* Something wrong. Fall back to single-byte */
udequote_pathname (pathname);
return;
}
orig_wpathname = wpathname;
for (i = j = 0; wpathname && wpathname[i]; )
{
if (wpathname[i] == L'\\')
i++;
wpathname[j++] = wpathname[i++];
if (wpathname[i - 1] == L'\0')
break;
}
if (wpathname)
wpathname[j] = L'\0';
/* Convert the wide character string into unibyte character set. */
memset (&ps, '\0', sizeof(mbstate_t));
n = wcsrtombs(pathname, (const wchar_t **)&wpathname, len, &ps);
pathname[len] = '\0';
/* Can't just free wpathname here; wcsrtombs changes it in many cases. */
free (orig_wpathname);
}
static void
dequote_pathname (pathname)
char *pathname;
{
if (MB_CUR_MAX > 1)
wdequote_pathname (pathname);
else
udequote_pathname (pathname);
}
#endif /* HANDLE_MULTIBYTE */
/* Test whether NAME exists. */
#if defined (HAVE_LSTAT)
# define GLOB_TESTNAME(name) (lstat (name, &finfo))
#else /* !HAVE_LSTAT */
# if !defined (AFS)
# define GLOB_TESTNAME(name) (sh_eaccess (name, F_OK))
# else /* AFS */
# define GLOB_TESTNAME(name) (access (name, F_OK))
# endif /* AFS */
#endif /* !HAVE_LSTAT */
/* Return 0 if DIR is a directory, -2 if DIR is a symlink, -1 otherwise. */
static int
glob_testdir (dir, flags)
char *dir;
int flags;
{
struct stat finfo;
int r;
/*itrace("glob_testdir: testing %s" flags = %d, dir, flags);*/
#if defined (HAVE_LSTAT)
r = (flags & GX_ALLDIRS) ? lstat (dir, &finfo) : stat (dir, &finfo);
#else
r = stat (dir, &finfo);
#endif
if (r < 0)
return (-1);
#if defined (S_ISLNK)
if (S_ISLNK (finfo.st_mode))
return (-2);
#endif
if (S_ISDIR (finfo.st_mode) == 0)
return (-1);
return (0);
}
/* Recursively scan SDIR for directories matching PAT (PAT is always `**').
FLAGS is simply passed down to the recursive call to glob_vector. Returns
a list of matching directory names. EP, if non-null, is set to the last
element of the returned list. NP, if non-null, is set to the number of
directories in the returned list. These two variables exist for the
convenience of the caller (always glob_vector). */
static struct globval *
finddirs (pat, sdir, flags, ep, np)
char *pat;
char *sdir;
int flags;
struct globval **ep;
int *np;
{
char **r, *n;
int ndirs;
struct globval *ret, *e, *g;
/*itrace("finddirs: pat = `%s' sdir = `%s' flags = 0x%x", pat, sdir, flags);*/
e = ret = 0;
r = glob_vector (pat, sdir, flags);
if (r == 0 || r[0] == 0)
{
if (np)
*np = 0;
if (ep)
*ep = 0;
if (r && r != &glob_error_return)
free (r);
return (struct globval *)0;
}
for (ndirs = 0; r[ndirs] != 0; ndirs++)
{
g = (struct globval *) malloc (sizeof (struct globval));
if (g == 0)
{
while (ret) /* free list built so far */
{
g = ret->next;
free (ret);
ret = g;
}
free (r);
if (np)
*np = 0;
if (ep)
*ep = 0;
return (&finddirs_error_return);
}
if (e == 0)
e = g;
g->next = ret;
ret = g;
g->name = r[ndirs];
}
free (r);
if (ep)
*ep = e;
if (np)
*np = ndirs;
return ret;
}
/* Return a vector of names of files in directory DIR
whose names match glob pattern PAT.
The names are not in any particular order.
Wildcards at the beginning of PAT do not match an initial period.
The vector is terminated by an element that is a null pointer.
To free the space allocated, first free the vector's elements,
then free the vector.
Return 0 if cannot get enough memory to hold the pointer
and the names.
Return -1 if cannot access directory DIR.
Look in errno for more information. */
char **
glob_vector (pat, dir, flags)
char *pat;
char *dir;
int flags;
{
DIR *d;
register struct dirent *dp;
struct globval *lastlink, *e, *dirlist;
register struct globval *nextlink;
register char *nextname, *npat, *subdir;
unsigned int count;
int lose, skip, ndirs, isdir, sdlen, add_current, patlen;
register char **name_vector;
register unsigned int i;
int mflags; /* Flags passed to strmatch (). */
int pflags; /* flags passed to sh_makepath () */
int nalloca;
struct globval *firstmalloc, *tmplink;
char *convfn;
lastlink = 0;
count = lose = skip = add_current = 0;
firstmalloc = 0;
nalloca = 0;
name_vector = NULL;
/*itrace("glob_vector: pat = `%s' dir = `%s' flags = 0x%x", pat, dir, flags);*/
/* If PAT is empty, skip the loop, but return one (empty) filename. */
if (pat == 0 || *pat == '\0')
{
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
nextlink = (struct globval *)alloca (sizeof (struct globval));
if (nextlink == NULL)
return ((char **) NULL);
nextlink->next = (struct globval *)0;
nextname = (char *) malloc (1);
if (nextname == 0)
lose = 1;
else
{
lastlink = nextlink;
nextlink->name = nextname;
nextname[0] = '\0';
count = 1;
}
skip = 1;
}
patlen = (pat && *pat) ? strlen (pat) : 0;
/* If the filename pattern (PAT) does not contain any globbing characters,
we can dispense with reading the directory, and just see if there is
a filename `DIR/PAT'. If there is, and we can access it, just make the
vector to return and bail immediately. */
if (skip == 0 && glob_pattern_p (pat) == 0)
{
int dirlen;
struct stat finfo;
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
dirlen = strlen (dir);
nextname = (char *)malloc (dirlen + patlen + 2);
npat = (char *)malloc (patlen + 1);
if (nextname == 0 || npat == 0)
{
FREE (nextname);
FREE (npat);
lose = 1;
}
else
{
strcpy (npat, pat);
dequote_pathname (npat);
strcpy (nextname, dir);
nextname[dirlen++] = '/';
strcpy (nextname + dirlen, npat);
if (GLOB_TESTNAME (nextname) >= 0)
{
free (nextname);
nextlink = (struct globval *)alloca (sizeof (struct globval));
if (nextlink)
{
nextlink->next = (struct globval *)0;
lastlink = nextlink;
nextlink->name = npat;
count = 1;
}
else
{
free (npat);
lose = 1;
}
}
else
{
free (nextname);
free (npat);
}
}
skip = 1;
}
if (skip == 0)
{
/* Open the directory, punting immediately if we cannot. If opendir
is not robust (i.e., it opens non-directories successfully), test
that DIR is a directory and punt if it's not. */
#if defined (OPENDIR_NOT_ROBUST)
if (glob_testdir (dir, 0) < 0)
return ((char **) &glob_error_return);
#endif
d = opendir (dir);
if (d == NULL)
return ((char **) &glob_error_return);
/* Compute the flags that will be passed to strmatch(). We don't
need to do this every time through the loop. */
mflags = (noglob_dot_filenames ? FNM_PERIOD : 0) | FNM_PATHNAME;
#ifdef FNM_CASEFOLD
if (glob_ignore_case)
mflags |= FNM_CASEFOLD;
#endif
if (extended_glob)
mflags |= FNM_EXTMATCH;
add_current = ((flags & (GX_ALLDIRS|GX_ADDCURDIR)) == (GX_ALLDIRS|GX_ADDCURDIR));
/* Scan the directory, finding all names that match.
For each name that matches, allocate a struct globval
on the stack and store the name in it.
Chain those structs together; lastlink is the front of the chain. */
while (1)
{
/* Make globbing interruptible in the shell. */
if (interrupt_state || terminating_signal)
{
lose = 1;
break;
}
else if (signal_is_pending (SIGINT)) /* XXX - make SIGINT traps responsive */
{
lose = 1;
break;
}
dp = readdir (d);
if (dp == NULL)
break;
/* If this directory entry is not to be used, try again. */
if (REAL_DIR_ENTRY (dp) == 0)
continue;
#if 0
if (dp->d_name == 0 || *dp->d_name == 0)
continue;
#endif
#if HANDLE_MULTIBYTE
if (MB_CUR_MAX > 1 && mbskipname (pat, dp->d_name, flags))
continue;
else
#endif
if (skipname (pat, dp->d_name, flags))
continue;
/* If we're only interested in directories, don't bother with files */
if (flags & (GX_MATCHDIRS|GX_ALLDIRS))
{
pflags = (flags & GX_ALLDIRS) ? MP_RMDOT : 0;
if (flags & GX_NULLDIR)
pflags |= MP_IGNDOT;
subdir = sh_makepath (dir, dp->d_name, pflags);
isdir = glob_testdir (subdir, flags);
if (isdir < 0 && (flags & GX_MATCHDIRS))
{
free (subdir);
continue;
}
}
if (flags & GX_ALLDIRS)
{
if (isdir == 0)
{
dirlist = finddirs (pat, subdir, (flags & ~GX_ADDCURDIR), &e, &ndirs);
if (dirlist == &finddirs_error_return)
{
free (subdir);
lose = 1;
break;
}
if (ndirs) /* add recursive directories to list */
{
if (firstmalloc == 0)
firstmalloc = e;
e->next = lastlink;
lastlink = dirlist;
count += ndirs;
}
}
/* XXX - should we even add this if it's not a directory? */
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (firstmalloc == 0)
firstmalloc = nextlink;
sdlen = strlen (subdir);
nextname = (char *) malloc (sdlen + 1);
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
free (subdir);
lose = 1;
break;
}
nextlink->next = lastlink;
lastlink = nextlink;
nextlink->name = nextname;
bcopy (subdir, nextname, sdlen + 1);
free (subdir);
++count;
continue;
}
else if (flags & GX_MATCHDIRS)
free (subdir);
convfn = fnx_fromfs (dp->d_name, D_NAMLEN (dp));
if (strmatch (pat, convfn, mflags) != FNM_NOMATCH)
{
if (nalloca < ALLOCA_MAX)
{
nextlink = (struct globval *) alloca (sizeof (struct globval));
nalloca += sizeof (struct globval);
}
else
{
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (firstmalloc == 0)
firstmalloc = nextlink;
}
nextname = (char *) malloc (D_NAMLEN (dp) + 1);
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
lose = 1;
break;
}
nextlink->next = lastlink;
lastlink = nextlink;
nextlink->name = nextname;
bcopy (dp->d_name, nextname, D_NAMLEN (dp) + 1);
++count;
}
}
(void) closedir (d);
}
/* compat: if GX_ADDCURDIR, add the passed directory also. Add an empty
directory name as a placeholder if GX_NULLDIR (in which case the passed
directory name is "."). */
if (add_current)
{
sdlen = strlen (dir);
nextname = (char *)malloc (sdlen + 1);
nextlink = (struct globval *) malloc (sizeof (struct globval));
if (nextlink == 0 || nextname == 0)
{
FREE (nextlink);
FREE (nextname);
lose = 1;
}
else
{
nextlink->name = nextname;
nextlink->next = lastlink;
lastlink = nextlink;
if (flags & GX_NULLDIR)
nextname[0] = '\0';
else
bcopy (dir, nextname, sdlen + 1);
++count;
}
}
if (lose == 0)
{
name_vector = (char **) malloc ((count + 1) * sizeof (char *));
lose |= name_vector == NULL;
}
/* Have we run out of memory? */
if (lose)
{
tmplink = 0;
/* Here free the strings we have got. */
while (lastlink)
{
/* Since we build the list in reverse order, the first N entries
will be allocated with malloc, if firstmalloc is set, from
lastlink to firstmalloc. */
if (firstmalloc)
{
if (lastlink == firstmalloc)
firstmalloc = 0;
tmplink = lastlink;
}
else
tmplink = 0;
free (lastlink->name);
lastlink = lastlink->next;
FREE (tmplink);
}
/* Don't call QUIT; here; let higher layers deal with it. */
return ((char **)NULL);
}
/* Copy the name pointers from the linked list into the vector. */
for (tmplink = lastlink, i = 0; i < count; ++i)
{
name_vector[i] = tmplink->name;
tmplink = tmplink->next;
}
name_vector[count] = NULL;
/* If we allocated some of the struct globvals, free them now. */
if (firstmalloc)
{
tmplink = 0;
while (lastlink)
{
tmplink = lastlink;
if (lastlink == firstmalloc)
lastlink = firstmalloc = 0;
else
lastlink = lastlink->next;
free (tmplink);
}
}
return (name_vector);
}
/* Return a new array which is the concatenation of each string in ARRAY
to DIR. This function expects you to pass in an allocated ARRAY, and
it takes care of free()ing that array. Thus, you might think of this
function as side-effecting ARRAY. This should handle GX_MARKDIRS. */
static char **
glob_dir_to_array (dir, array, flags)
char *dir, **array;
int flags;
{
register unsigned int i, l;
int add_slash;
char **result, *new;
struct stat sb;
l = strlen (dir);
if (l == 0)
{
if (flags & GX_MARKDIRS)
for (i = 0; array[i]; i++)
{
if ((stat (array[i], &sb) == 0) && S_ISDIR (sb.st_mode))
{
l = strlen (array[i]);
new = (char *)realloc (array[i], l + 2);
if (new == 0)
return NULL;
new[l] = '/';
new[l+1] = '\0';
array[i] = new;
}
}
return (array);
}
add_slash = dir[l - 1] != '/';
i = 0;
while (array[i] != NULL)
++i;
result = (char **) malloc ((i + 1) * sizeof (char *));
if (result == NULL)
return (NULL);
for (i = 0; array[i] != NULL; i++)
{
/* 3 == 1 for NUL, 1 for slash at end of DIR, 1 for GX_MARKDIRS */
result[i] = (char *) malloc (l + strlen (array[i]) + 3);
if (result[i] == NULL)
{
int ind;
for (ind = 0; ind < i; ind++)
free (result[ind]);
free (result);
return (NULL);
}
strcpy (result[i], dir);
if (add_slash)
result[i][l] = '/';
if (array[i][0])
{
strcpy (result[i] + l + add_slash, array[i]);
if (flags & GX_MARKDIRS)
{
if ((stat (result[i], &sb) == 0) && S_ISDIR (sb.st_mode))
{
size_t rlen;
rlen = strlen (result[i]);
result[i][rlen] = '/';
result[i][rlen+1] = '\0';
}
}
}
else
result[i][l+add_slash] = '\0';
}
result[i] = NULL;
/* Free the input array. */
for (i = 0; array[i] != NULL; i++)
free (array[i]);
free ((char *) array);
return (result);
}
/* Do globbing on PATHNAME. Return an array of pathnames that match,
marking the end of the array with a null-pointer as an element.
If no pathnames match, then the array is empty (first element is null).
If there isn't enough memory, then return NULL.
If a file system error occurs, return -1; `errno' has the error code. */
char **
glob_filename (pathname, flags)
char *pathname;
int flags;
{
char **result, **new_result;
unsigned int result_size;
char *directory_name, *filename, *dname, *fn;
unsigned int directory_len;
int free_dirname; /* flag */
int dflags, hasglob;
result = (char **) malloc (sizeof (char *));
result_size = 1;
if (result == NULL)
return (NULL);
result[0] = NULL;
directory_name = NULL;
/* Find the filename. */
filename = strrchr (pathname, '/');
#if defined (EXTENDED_GLOB)
if (filename && extended_glob)
{
fn = glob_dirscan (pathname, '/');
#if DEBUG_MATCHING
if (fn != filename)
fprintf (stderr, "glob_filename: glob_dirscan: fn (%s) != filename (%s)\n", fn ? fn : "(null)", filename);
#endif
filename = fn;
}
#endif
if (filename == NULL)
{
filename = pathname;
directory_name = "";
directory_len = 0;
free_dirname = 0;
}
else
{
directory_len = (filename - pathname) + 1;
directory_name = (char *) malloc (directory_len + 1);
if (directory_name == 0) /* allocation failed? */
{
free (result);
return (NULL);
}
bcopy (pathname, directory_name, directory_len);
directory_name[directory_len] = '\0';
++filename;
free_dirname = 1;
}
hasglob = 0;
/* If directory_name contains globbing characters, then we
have to expand the previous levels. Just recurse.
If glob_pattern_p returns != [0,1] we have a pattern that has backslash
quotes but no unquoted glob pattern characters. We dequote it below. */
if (directory_len > 0 && (hasglob = glob_pattern_p (directory_name)) == 1)
{
char **directories, *d, *p;
register unsigned int i;
int all_starstar, last_starstar;
all_starstar = last_starstar = 0;
d = directory_name;
dflags = flags & ~GX_MARKDIRS;
/* Collapse a sequence of ** patterns separated by one or more slashes
to a single ** terminated by a slash or NUL */
if ((flags & GX_GLOBSTAR) && d[0] == '*' && d[1] == '*' && (d[2] == '/' || d[2] == '\0'))
{
p = d;
while (d[0] == '*' && d[1] == '*' && (d[2] == '/' || d[2] == '\0'))
{
p = d;
if (d[2])
{
d += 3;
while (*d == '/')
d++;
if (*d == 0)
break;
}
}
if (*d == 0)
all_starstar = 1;
d = p;
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
directory_len = strlen (d);
}
/* If there is a non [star][star]/ component in directory_name, we
still need to collapse trailing sequences of [star][star]/ into
a single one and note that the directory name ends with [star][star],
so we can compensate if filename is [star][star] */
if ((flags & GX_GLOBSTAR) && all_starstar == 0)
{
int dl, prev;
prev = dl = directory_len;
while (dl >= 4 && d[dl - 1] == '/' &&
d[dl - 2] == '*' &&
d[dl - 3] == '*' &&
d[dl - 4] == '/')
prev = dl, dl -= 3;
if (dl != directory_len)
last_starstar = 1;
directory_len = prev;
}
/* If the directory name ends in [star][star]/ but the filename is
[star][star], just remove the final [star][star] from the directory
so we don't have to scan everything twice. */
if (last_starstar && directory_len > 4 &&
filename[0] == '*' && filename[1] == '*' && filename[2] == 0)
{
directory_len -= 3;
}
if (d[directory_len - 1] == '/')
d[directory_len - 1] = '\0';
directories = glob_filename (d, dflags|GX_RECURSE);
if (free_dirname)
{
free (directory_name);
directory_name = NULL;
}
if (directories == NULL)
goto memory_error;
else if (directories == (char **)&glob_error_return)
{
free ((char *) result);
return ((char **) &glob_error_return);
}
else if (*directories == NULL)
{
free ((char *) directories);
free ((char *) result);
return ((char **) &glob_error_return);
}
/* If we have something like [star][star]/[star][star], it's no use to
glob **, then do it again, and throw half the results away. */
if (all_starstar && filename[0] == '*' && filename[1] == '*' && filename[2] == 0)
{
free ((char *) directories);
free (directory_name);
directory_name = NULL;
directory_len = 0;
goto only_filename;
}
/* We have successfully globbed the preceding directory name.
For each name in DIRECTORIES, call glob_vector on it and
FILENAME. Concatenate the results together. */
for (i = 0; directories[i] != NULL; ++i)
{
char **temp_results;
int shouldbreak;
shouldbreak = 0;
/* XXX -- we've recursively scanned any directories resulting from
a `**', so turn off the flag. We turn it on again below if
filename is `**' */
/* Scan directory even on a NULL filename. That way, `*h/'
returns only directories ending in `h', instead of all
files ending in `h' with a `/' appended. */
dname = directories[i];
dflags = flags & ~(GX_MARKDIRS|GX_ALLDIRS|GX_ADDCURDIR);
/* last_starstar? */
if ((flags & GX_GLOBSTAR) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
if (dname[0] == '\0' && filename[0])
{
dflags |= GX_NULLDIR;
dname = "."; /* treat null directory name and non-null filename as current directory */
}
/* Special handling for symlinks to directories with globstar on */
if (all_starstar && (dflags & GX_NULLDIR) == 0)
{
int dlen;
/* If we have a directory name that is not null (GX_NULLDIR above)
and is a symlink to a directory, we return the symlink if
we're not `descending' into it (filename[0] == 0) and return
glob_error_return (which causes the code below to skip the
name) otherwise. I should fold this into a test that does both
checks instead of calling stat twice. */
if (glob_testdir (dname, flags|GX_ALLDIRS) == -2 && glob_testdir (dname, 0) == 0)
{
if (filename[0] != 0)
temp_results = (char **)&glob_error_return; /* skip */
else
{
/* Construct array to pass to glob_dir_to_array */
temp_results = (char **)malloc (2 * sizeof (char *));
if (temp_results == NULL)
goto memory_error;
temp_results[0] = (char *)malloc (1);
if (temp_results[0] == 0)
{
free (temp_results);
goto memory_error;
}
**temp_results = '\0';
temp_results[1] = NULL;
dflags |= GX_SYMLINK; /* mostly for debugging */
}
}
else
temp_results = glob_vector (filename, dname, dflags);
}
else
temp_results = glob_vector (filename, dname, dflags);
/* Handle error cases. */
if (temp_results == NULL)
goto memory_error;
else if (temp_results == (char **)&glob_error_return)
/* This filename is probably not a directory. Ignore it. */
;
else
{
char **array;
register unsigned int l;
/* If we're expanding **, we don't need to glue the directory
name to the results; we've already done it in glob_vector */
if ((dflags & GX_ALLDIRS) && filename[0] == '*' && filename[1] == '*' && (filename[2] == '\0' || filename[2] == '/'))
{
/* When do we remove null elements from temp_results? And
how to avoid duplicate elements in the final result? */
/* If (dflags & GX_NULLDIR) glob_filename potentially left a
NULL placeholder in the temp results just in case
glob_vector/glob_dir_to_array did something with it, but
if it didn't, and we're not supposed to be passing them
through for some reason ((flags & GX_NULLDIR) == 0) we
need to remove all the NULL elements from the beginning
of TEMP_RESULTS. */
/* If we have a null directory name and ** as the filename,
we have just searched for everything from the current
directory on down. Break now (shouldbreak = 1) to avoid
duplicate entries in the final result. */
#define NULL_PLACEHOLDER(x) ((x) && *(x) && **(x) == 0)
if ((dflags & GX_NULLDIR) && (flags & GX_NULLDIR) == 0 &&
NULL_PLACEHOLDER (temp_results))
#undef NULL_PLACEHOLDER
{
register int i, n;
for (n = 0; temp_results[n] && *temp_results[n] == 0; n++)
;
i = n;
do
temp_results[i - n] = temp_results[i];
while (temp_results[i++] != 0);
array = temp_results;
shouldbreak = 1;
}
else
array = temp_results;
}
else if (dflags & GX_SYMLINK)
array = glob_dir_to_array (directories[i], temp_results, flags);
else
array = glob_dir_to_array (directories[i], temp_results, flags);
l = 0;
while (array[l] != NULL)
++l;
new_result = (char **)realloc (result, (result_size + l) * sizeof (char *));
if (new_result == NULL)
{
for (l = 0; array[l]; ++l)
free (array[l]);
free ((char *)array);
goto memory_error;
}
result = new_result;
for (l = 0; array[l] != NULL; ++l)
result[result_size++ - 1] = array[l];
result[result_size - 1] = NULL;
/* Note that the elements of ARRAY are not freed. */
if (array != temp_results)
free ((char *) array);
else if ((dflags & GX_ALLDIRS) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
free (temp_results); /* expanding ** case above */
if (shouldbreak)
break;
}
}
/* Free the directories. */
for (i = 0; directories[i]; i++)
free (directories[i]);
free ((char *) directories);
return (result);
}
only_filename:
/* If there is only a directory name, return it. */
if (*filename == '\0')
{
result = (char **) realloc ((char *) result, 2 * sizeof (char *));
if (result == NULL)
{
if (free_dirname)
free (directory_name);
return (NULL);
}
/* If we have a directory name with quoted characters, and we are
being called recursively to glob the directory portion of a pathname,
we need to dequote the directory name before returning it so the
caller can read the directory */
if (directory_len > 0 && hasglob == 2 && (flags & GX_RECURSE) != 0)
{
dequote_pathname (directory_name);
directory_len = strlen (directory_name);
}
/* We could check whether or not the dequoted directory_name is a
directory and return it here, returning the original directory_name
if not, but we don't do that. We do return the dequoted directory
name if we're not being called recursively and the dequoted name
corresponds to an actual directory. For better backwards compatibility,
we can return &glob_error_return unconditionally in this case. */
if (directory_len > 0 && hasglob == 2 && (flags & GX_RECURSE) == 0)
{
#if 1
dequote_pathname (directory_name);
if (glob_testdir (directory_name, 0) < 0)
{
if (free_dirname)
free (directory_name);
return ((char **)&glob_error_return);
}
#else
return ((char **)&glob_error_return);
#endif
}
/* Handle GX_MARKDIRS here. */
result[0] = (char *) malloc (directory_len + 1);
if (result[0] == NULL)
goto memory_error;
bcopy (directory_name, result[0], directory_len + 1);
if (free_dirname)
free (directory_name);
result[1] = NULL;
return (result);
}
else
{
char **temp_results;
/* There are no unquoted globbing characters in DIRECTORY_NAME.
Dequote it before we try to open the directory since there may
be quoted globbing characters which should be treated verbatim. */
if (directory_len > 0)
dequote_pathname (directory_name);
/* We allocated a small array called RESULT, which we won't be using.
Free that memory now. */
free (result);
/* Just return what glob_vector () returns appended to the
directory name. */
/* If flags & GX_ALLDIRS, we're called recursively */
dflags = flags & ~GX_MARKDIRS;
if (directory_len == 0)
dflags |= GX_NULLDIR;
if ((flags & GX_GLOBSTAR) && filename[0] == '*' && filename[1] == '*' && filename[2] == '\0')
{
dflags |= GX_ALLDIRS|GX_ADDCURDIR;
#if 0
/* If we want all directories (dflags & GX_ALLDIRS) and we're not
being called recursively as something like `echo [star][star]/[star].o'
((flags & GX_ALLDIRS) == 0), we want to prevent glob_vector from
adding a null directory name to the front of the temp_results
array. We turn off ADDCURDIR if not called recursively and
dlen == 0 */
#endif
if (directory_len == 0 && (flags & GX_ALLDIRS) == 0)
dflags &= ~GX_ADDCURDIR;
}
temp_results = glob_vector (filename,
(directory_len == 0 ? "." : directory_name),
dflags);
if (temp_results == NULL || temp_results == (char **)&glob_error_return)
{
if (free_dirname)
free (directory_name);
QUIT; /* XXX - shell */
run_pending_traps ();
return (temp_results);
}
result = glob_dir_to_array ((dflags & GX_ALLDIRS) ? "" : directory_name, temp_results, flags);
if (free_dirname)
free (directory_name);
return (result);
}
/* We get to memory_error if the program has run out of memory, or
if this is the shell, and we have been interrupted. */
memory_error:
if (result != NULL)
{
register unsigned int i;
for (i = 0; result[i] != NULL; ++i)
free (result[i]);
free ((char *) result);
}
if (free_dirname && directory_name)
free (directory_name);
QUIT;
run_pending_traps ();
return (NULL);
}
#if defined (TEST)
main (argc, argv)
int argc;
char **argv;
{
unsigned int i;
for (i = 1; i < argc; ++i)
{
char **value = glob_filename (argv[i], 0);
if (value == NULL)
puts ("Out of memory.");
else if (value == &glob_error_return)
perror (argv[i]);
else
for (i = 0; value[i] != NULL; i++)
puts (value[i]);
}
exit (0);
}
#endif /* TEST. */
| ./CrossVul/dataset_final_sorted/CWE-273/c/bad_1198_9 |
crossvul-cpp_data_bad_1198_2 | /* bashline.c -- Bash's interface to the readline library. */
/* Copyright (C) 1987-2019 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash 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.
Bash 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 Bash. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#if defined (READLINE)
#include "bashtypes.h"
#include "posixstat.h"
#if defined (HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined (HAVE_GRP_H)
# include <grp.h>
#endif
#if defined (HAVE_NETDB_H)
# include <netdb.h>
#endif
#include <signal.h>
#include <stdio.h>
#include "chartypes.h"
#include "bashansi.h"
#include "bashintl.h"
#include "shell.h"
#include "input.h"
#include "parser.h"
#include "builtins.h"
#include "bashhist.h"
#include "bashline.h"
#include "execute_cmd.h"
#include "findcmd.h"
#include "pathexp.h"
#include "shmbutil.h"
#include "trap.h"
#include "flags.h"
#if defined (HAVE_MBSTR_H) && defined (HAVE_MBSCHR)
# include <mbstr.h> /* mbschr */
#endif
#include "builtins/common.h"
#include <readline/rlconf.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <readline/rlmbutil.h>
#include <glob/glob.h>
#if defined (ALIAS)
# include "alias.h"
#endif
#if defined (PROGRAMMABLE_COMPLETION)
# include "pcomplete.h"
#endif
/* These should agree with the defines for emacs_mode and vi_mode in
rldefs.h, even though that's not a public readline header file. */
#ifndef EMACS_EDITING_MODE
# define NO_EDITING_MODE -1
# define EMACS_EDITING_MODE 1
# define VI_EDITING_MODE 0
#endif
/* Copied from rldefs.h, since that's not a public readline header file. */
#ifndef FUNCTION_TO_KEYMAP
#if defined (CRAY)
# define FUNCTION_TO_KEYMAP(map, key) (Keymap)((int)map[key].function)
# define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)((int)(data))
#else
# define FUNCTION_TO_KEYMAP(map, key) (Keymap)(map[key].function)
# define KEYMAP_TO_FUNCTION(data) (rl_command_func_t *)(data)
#endif
#endif
#define RL_BOOLEAN_VARIABLE_VALUE(s) ((s)[0] == 'o' && (s)[1] == 'n' && (s)[2] == '\0')
#if defined (BRACE_COMPLETION)
extern int bash_brace_completion PARAMS((int, int));
#endif /* BRACE_COMPLETION */
/* To avoid including curses.h/term.h/termcap.h and that whole mess. */
#ifdef _MINIX
extern int tputs PARAMS((const char *string, int nlines, void (*outx)(int)));
#else
extern int tputs PARAMS((const char *string, int nlines, int (*outx)(int)));
#endif
/* Forward declarations */
/* Functions bound to keys in Readline for Bash users. */
static int shell_expand_line PARAMS((int, int));
static int display_shell_version PARAMS((int, int));
static int operate_and_get_next PARAMS((int, int));
static int bash_ignore_filenames PARAMS((char **));
static int bash_ignore_everything PARAMS((char **));
static int bash_progcomp_ignore_filenames PARAMS((char **));
#if defined (BANG_HISTORY)
static char *history_expand_line_internal PARAMS((char *));
static int history_expand_line PARAMS((int, int));
static int tcsh_magic_space PARAMS((int, int));
#endif /* BANG_HISTORY */
#ifdef ALIAS
static int alias_expand_line PARAMS((int, int));
#endif
#if defined (BANG_HISTORY) && defined (ALIAS)
static int history_and_alias_expand_line PARAMS((int, int));
#endif
static int bash_forward_shellword PARAMS((int, int));
static int bash_backward_shellword PARAMS((int, int));
static int bash_kill_shellword PARAMS((int, int));
static int bash_backward_kill_shellword PARAMS((int, int));
static int bash_transpose_shellwords PARAMS((int, int));
/* Helper functions for Readline. */
static char *restore_tilde PARAMS((char *, char *));
static char *maybe_restore_tilde PARAMS((char *, char *));
static char *bash_filename_rewrite_hook PARAMS((char *, int));
static void bash_directory_expansion PARAMS((char **));
static int bash_filename_stat_hook PARAMS((char **));
static int bash_command_name_stat_hook PARAMS((char **));
static int bash_directory_completion_hook PARAMS((char **));
static int filename_completion_ignore PARAMS((char **));
static int bash_push_line PARAMS((void));
static int executable_completion PARAMS((const char *, int));
static rl_icppfunc_t *save_directory_hook PARAMS((void));
static void restore_directory_hook PARAMS((rl_icppfunc_t));
static int directory_exists PARAMS((const char *, int));
static void cleanup_expansion_error PARAMS((void));
static void maybe_make_readline_line PARAMS((char *));
static void set_up_new_line PARAMS((char *));
static int check_redir PARAMS((int));
static char **attempt_shell_completion PARAMS((const char *, int, int));
static char *variable_completion_function PARAMS((const char *, int));
static char *hostname_completion_function PARAMS((const char *, int));
static char *command_subst_completion_function PARAMS((const char *, int));
static void build_history_completion_array PARAMS((void));
static char *history_completion_generator PARAMS((const char *, int));
static int dynamic_complete_history PARAMS((int, int));
static int bash_dabbrev_expand PARAMS((int, int));
static void initialize_hostname_list PARAMS((void));
static void add_host_name PARAMS((char *));
static void snarf_hosts_from_file PARAMS((char *));
static char **hostnames_matching PARAMS((char *));
static void _ignore_completion_names PARAMS((char **, sh_ignore_func_t *));
static int name_is_acceptable PARAMS((const char *));
static int test_for_directory PARAMS((const char *));
static int test_for_canon_directory PARAMS((const char *));
static int return_zero PARAMS((const char *));
static char *bash_dequote_filename PARAMS((char *, int));
static char *quote_word_break_chars PARAMS((char *));
static void set_filename_bstab PARAMS((const char *));
static char *bash_quote_filename PARAMS((char *, int, char *));
#ifdef _MINIX
static void putx PARAMS((int));
#else
static int putx PARAMS((int));
#endif
static Keymap get_cmd_xmap_from_edit_mode PARAMS((void));
static Keymap get_cmd_xmap_from_keymap PARAMS((Keymap));
static int bash_execute_unix_command PARAMS((int, int));
static void init_unix_command_map PARAMS((void));
static int isolate_sequence PARAMS((char *, int, int, int *));
static int set_saved_history PARAMS((void));
#if defined (ALIAS)
static int posix_edit_macros PARAMS((int, int));
#endif
static int bash_event_hook PARAMS((void));
#if defined (PROGRAMMABLE_COMPLETION)
static int find_cmd_start PARAMS((int));
static int find_cmd_end PARAMS((int));
static char *find_cmd_name PARAMS((int, int *, int *));
static char *prog_complete_return PARAMS((const char *, int));
static char **prog_complete_matches;
#endif
extern int no_symbolic_links;
extern STRING_INT_ALIST word_token_alist[];
/* SPECIFIC_COMPLETION_FUNCTIONS specifies that we have individual
completion functions which indicate what type of completion should be
done (at or before point) that can be bound to key sequences with
the readline library. */
#define SPECIFIC_COMPLETION_FUNCTIONS
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
static int bash_specific_completion PARAMS((int, rl_compentry_func_t *));
static int bash_complete_filename_internal PARAMS((int));
static int bash_complete_username_internal PARAMS((int));
static int bash_complete_hostname_internal PARAMS((int));
static int bash_complete_variable_internal PARAMS((int));
static int bash_complete_command_internal PARAMS((int));
static int bash_complete_filename PARAMS((int, int));
static int bash_possible_filename_completions PARAMS((int, int));
static int bash_complete_username PARAMS((int, int));
static int bash_possible_username_completions PARAMS((int, int));
static int bash_complete_hostname PARAMS((int, int));
static int bash_possible_hostname_completions PARAMS((int, int));
static int bash_complete_variable PARAMS((int, int));
static int bash_possible_variable_completions PARAMS((int, int));
static int bash_complete_command PARAMS((int, int));
static int bash_possible_command_completions PARAMS((int, int));
static int completion_glob_pattern PARAMS((char *));
static char *glob_complete_word PARAMS((const char *, int));
static int bash_glob_completion_internal PARAMS((int));
static int bash_glob_complete_word PARAMS((int, int));
static int bash_glob_expand_word PARAMS((int, int));
static int bash_glob_list_expansions PARAMS((int, int));
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
static int edit_and_execute_command PARAMS((int, int, int, char *));
#if defined (VI_MODE)
static int vi_edit_and_execute_command PARAMS((int, int));
static int bash_vi_complete PARAMS((int, int));
#endif
static int emacs_edit_and_execute_command PARAMS((int, int));
/* Non-zero once initalize_readline () has been called. */
int bash_readline_initialized = 0;
/* If non-zero, we do hostname completion, breaking words at `@' and
trying to complete the stuff after the `@' from our own internal
host list. */
int perform_hostname_completion = 1;
/* If non-zero, we don't do command completion on an empty line. */
int no_empty_command_completion;
/* Set FORCE_FIGNORE if you want to honor FIGNORE even if it ignores the
only possible matches. Set to 0 if you want to match filenames if they
are the only possible matches, even if FIGNORE says to. */
int force_fignore = 1;
/* Perform spelling correction on directory names during word completion */
int dircomplete_spelling = 0;
/* Expand directory names during word/filename completion. */
#if DIRCOMPLETE_EXPAND_DEFAULT
int dircomplete_expand = 1;
int dircomplete_expand_relpath = 1;
#else
int dircomplete_expand = 0;
int dircomplete_expand_relpath = 0;
#endif
/* When non-zero, perform `normal' shell quoting on completed filenames
even when the completed name contains a directory name with a shell
variable referene, so dollar signs in a filename get quoted appropriately.
Set to zero to remove dollar sign (and braces or parens as needed) from
the set of characters that will be quoted. */
int complete_fullquote = 1;
static char *bash_completer_word_break_characters = " \t\n\"'@><=;|&(:";
static char *bash_nohostname_word_break_characters = " \t\n\"'><=;|&(:";
/* )) */
static const char *default_filename_quote_characters = " \t\n\\\"'@<>=;|&()#$`?*[!:{~"; /*}*/
static char *custom_filename_quote_characters = 0;
static char filename_bstab[256];
static rl_hook_func_t *old_rl_startup_hook = (rl_hook_func_t *)NULL;
static int dot_in_path = 0;
/* Set to non-zero when dabbrev-expand is running */
static int dabbrev_expand_active = 0;
/* What kind of quoting is performed by bash_quote_filename:
COMPLETE_DQUOTE = double-quoting the filename
COMPLETE_SQUOTE = single_quoting the filename
COMPLETE_BSQUOTE = backslash-quoting special chars in the filename
*/
#define COMPLETE_DQUOTE 1
#define COMPLETE_SQUOTE 2
#define COMPLETE_BSQUOTE 3
static int completion_quoting_style = COMPLETE_BSQUOTE;
/* Flag values for the final argument to bash_default_completion */
#define DEFCOMP_CMDPOS 1
static rl_command_func_t *vi_tab_binding = rl_complete;
/* Change the readline VI-mode keymaps into or out of Posix.2 compliance.
Called when the shell is put into or out of `posix' mode. */
void
posix_readline_initialize (on_or_off)
int on_or_off;
{
static char kseq[2] = { CTRL ('I'), 0 }; /* TAB */
if (on_or_off)
rl_variable_bind ("comment-begin", "#");
#if defined (VI_MODE)
if (on_or_off)
{
vi_tab_binding = rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL);
rl_bind_key_in_map (CTRL ('I'), rl_insert, vi_insertion_keymap);
}
else
{
if (rl_function_of_keyseq (kseq, vi_insertion_keymap, (int *)NULL) == rl_insert)
rl_bind_key_in_map (CTRL ('I'), vi_tab_binding, vi_insertion_keymap);
}
#endif
}
void
reset_completer_word_break_chars ()
{
rl_completer_word_break_characters = perform_hostname_completion ? savestring (bash_completer_word_break_characters) : savestring (bash_nohostname_word_break_characters);
}
/* When this function returns, rl_completer_word_break_characters points to
dynamically allocated memory. */
int
enable_hostname_completion (on_or_off)
int on_or_off;
{
int old_value;
char *at, *nv, *nval;
old_value = perform_hostname_completion;
if (on_or_off)
{
perform_hostname_completion = 1;
rl_special_prefixes = "$@";
}
else
{
perform_hostname_completion = 0;
rl_special_prefixes = "$";
}
/* Now we need to figure out how to appropriately modify and assign
rl_completer_word_break_characters depending on whether we want
hostname completion on or off. */
/* If this is the first time this has been called
(bash_readline_initialized == 0), use the sames values as before, but
allocate new memory for rl_completer_word_break_characters. */
if (bash_readline_initialized == 0 &&
(rl_completer_word_break_characters == 0 ||
rl_completer_word_break_characters == rl_basic_word_break_characters))
{
if (on_or_off)
rl_completer_word_break_characters = savestring (bash_completer_word_break_characters);
else
rl_completer_word_break_characters = savestring (bash_nohostname_word_break_characters);
}
else
{
/* See if we have anything to do. */
at = strchr (rl_completer_word_break_characters, '@');
if ((at == 0 && on_or_off == 0) || (at != 0 && on_or_off != 0))
return old_value;
/* We have something to do. Do it. */
nval = (char *)xmalloc (strlen (rl_completer_word_break_characters) + 1 + on_or_off);
if (on_or_off == 0)
{
/* Turn it off -- just remove `@' from word break chars. We want
to remove all occurrences of `@' from the char list, so we loop
rather than just copy the rest of the list over AT. */
for (nv = nval, at = rl_completer_word_break_characters; *at; )
if (*at != '@')
*nv++ = *at++;
else
at++;
*nv = '\0';
}
else
{
nval[0] = '@';
strcpy (nval + 1, rl_completer_word_break_characters);
}
free (rl_completer_word_break_characters);
rl_completer_word_break_characters = nval;
}
return (old_value);
}
/* Called once from parse.y if we are going to use readline. */
void
initialize_readline ()
{
rl_command_func_t *func;
char kseq[2];
if (bash_readline_initialized)
return;
rl_terminal_name = get_string_value ("TERM");
rl_instream = stdin;
rl_outstream = stderr;
/* Allow conditional parsing of the ~/.inputrc file. */
rl_readline_name = "Bash";
/* Add bindable names before calling rl_initialize so they may be
referenced in the various inputrc files. */
rl_add_defun ("shell-expand-line", shell_expand_line, -1);
#ifdef BANG_HISTORY
rl_add_defun ("history-expand-line", history_expand_line, -1);
rl_add_defun ("magic-space", tcsh_magic_space, -1);
#endif
rl_add_defun ("shell-forward-word", bash_forward_shellword, -1);
rl_add_defun ("shell-backward-word", bash_backward_shellword, -1);
rl_add_defun ("shell-kill-word", bash_kill_shellword, -1);
rl_add_defun ("shell-backward-kill-word", bash_backward_kill_shellword, -1);
rl_add_defun ("shell-transpose-words", bash_transpose_shellwords, -1);
#ifdef ALIAS
rl_add_defun ("alias-expand-line", alias_expand_line, -1);
# ifdef BANG_HISTORY
rl_add_defun ("history-and-alias-expand-line", history_and_alias_expand_line, -1);
# endif
#endif
/* Backwards compatibility. */
rl_add_defun ("insert-last-argument", rl_yank_last_arg, -1);
rl_add_defun ("operate-and-get-next", operate_and_get_next, -1);
rl_add_defun ("display-shell-version", display_shell_version, -1);
rl_add_defun ("edit-and-execute-command", emacs_edit_and_execute_command, -1);
#if defined (BRACE_COMPLETION)
rl_add_defun ("complete-into-braces", bash_brace_completion, -1);
#endif
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
rl_add_defun ("complete-filename", bash_complete_filename, -1);
rl_add_defun ("possible-filename-completions", bash_possible_filename_completions, -1);
rl_add_defun ("complete-username", bash_complete_username, -1);
rl_add_defun ("possible-username-completions", bash_possible_username_completions, -1);
rl_add_defun ("complete-hostname", bash_complete_hostname, -1);
rl_add_defun ("possible-hostname-completions", bash_possible_hostname_completions, -1);
rl_add_defun ("complete-variable", bash_complete_variable, -1);
rl_add_defun ("possible-variable-completions", bash_possible_variable_completions, -1);
rl_add_defun ("complete-command", bash_complete_command, -1);
rl_add_defun ("possible-command-completions", bash_possible_command_completions, -1);
rl_add_defun ("glob-complete-word", bash_glob_complete_word, -1);
rl_add_defun ("glob-expand-word", bash_glob_expand_word, -1);
rl_add_defun ("glob-list-expansions", bash_glob_list_expansions, -1);
#endif
rl_add_defun ("dynamic-complete-history", dynamic_complete_history, -1);
rl_add_defun ("dabbrev-expand", bash_dabbrev_expand, -1);
/* Bind defaults before binding our custom shell keybindings. */
if (RL_ISSTATE(RL_STATE_INITIALIZED) == 0)
rl_initialize ();
/* Bind up our special shell functions. */
rl_bind_key_if_unbound_in_map (CTRL('E'), shell_expand_line, emacs_meta_keymap);
#ifdef BANG_HISTORY
rl_bind_key_if_unbound_in_map ('^', history_expand_line, emacs_meta_keymap);
#endif
rl_bind_key_if_unbound_in_map (CTRL ('O'), operate_and_get_next, emacs_standard_keymap);
rl_bind_key_if_unbound_in_map (CTRL ('V'), display_shell_version, emacs_ctlx_keymap);
/* In Bash, the user can switch editing modes with "set -o [vi emacs]",
so it is not necessary to allow C-M-j for context switching. Turn
off this occasionally confusing behaviour. */
kseq[0] = CTRL('J');
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == rl_vi_editing_mode)
rl_unbind_key_in_map (CTRL('J'), emacs_meta_keymap);
kseq[0] = CTRL('M');
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == rl_vi_editing_mode)
rl_unbind_key_in_map (CTRL('M'), emacs_meta_keymap);
#if defined (VI_MODE)
kseq[0] = CTRL('E');
func = rl_function_of_keyseq (kseq, vi_movement_keymap, (int *)NULL);
if (func == rl_emacs_editing_mode)
rl_unbind_key_in_map (CTRL('E'), vi_movement_keymap);
#endif
#if defined (BRACE_COMPLETION)
rl_bind_key_if_unbound_in_map ('{', bash_brace_completion, emacs_meta_keymap); /*}*/
#endif /* BRACE_COMPLETION */
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
rl_bind_key_if_unbound_in_map ('/', bash_complete_filename, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('/', bash_possible_filename_completions, emacs_ctlx_keymap);
/* Have to jump through hoops here because there is a default binding for
M-~ (rl_tilde_expand) */
kseq[0] = '~';
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == 0 || func == rl_tilde_expand)
rl_bind_keyseq_in_map (kseq, bash_complete_username, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('~', bash_possible_username_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('@', bash_complete_hostname, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('@', bash_possible_hostname_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('$', bash_complete_variable, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('$', bash_possible_variable_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('!', bash_complete_command, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('!', bash_possible_command_completions, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('g', bash_glob_complete_word, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map ('*', bash_glob_expand_word, emacs_ctlx_keymap);
rl_bind_key_if_unbound_in_map ('g', bash_glob_list_expansions, emacs_ctlx_keymap);
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
kseq[0] = TAB;
kseq[1] = '\0';
func = rl_function_of_keyseq (kseq, emacs_meta_keymap, (int *)NULL);
if (func == 0 || func == rl_tab_insert)
rl_bind_key_in_map (TAB, dynamic_complete_history, emacs_meta_keymap);
/* Tell the completer that we want a crack first. */
rl_attempted_completion_function = attempt_shell_completion;
/* Tell the completer that we might want to follow symbolic links or
do other expansion on directory names. */
set_directory_hook ();
rl_filename_rewrite_hook = bash_filename_rewrite_hook;
rl_filename_stat_hook = bash_filename_stat_hook;
/* Tell the filename completer we want a chance to ignore some names. */
rl_ignore_some_completions_function = filename_completion_ignore;
/* Bind C-xC-e to invoke emacs and run result as commands. */
rl_bind_key_if_unbound_in_map (CTRL ('E'), emacs_edit_and_execute_command, emacs_ctlx_keymap);
#if defined (VI_MODE)
rl_bind_key_if_unbound_in_map ('v', vi_edit_and_execute_command, vi_movement_keymap);
# if defined (ALIAS)
rl_bind_key_if_unbound_in_map ('@', posix_edit_macros, vi_movement_keymap);
# endif
rl_bind_key_in_map ('\\', bash_vi_complete, vi_movement_keymap);
rl_bind_key_in_map ('*', bash_vi_complete, vi_movement_keymap);
rl_bind_key_in_map ('=', bash_vi_complete, vi_movement_keymap);
#endif
rl_completer_quote_characters = "'\"";
/* This sets rl_completer_word_break_characters and rl_special_prefixes
to the appropriate values, depending on whether or not hostname
completion is enabled. */
enable_hostname_completion (perform_hostname_completion);
/* characters that need to be quoted when appearing in filenames. */
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
rl_filename_quoting_function = bash_quote_filename;
rl_filename_dequoting_function = bash_dequote_filename;
rl_char_is_quoted_p = char_is_quoted;
/* Add some default bindings for the "shellwords" functions, roughly
parallelling the default word bindings in emacs mode. */
rl_bind_key_if_unbound_in_map (CTRL('B'), bash_backward_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('D'), bash_kill_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('F'), bash_forward_shellword, emacs_meta_keymap);
rl_bind_key_if_unbound_in_map (CTRL('T'), bash_transpose_shellwords, emacs_meta_keymap);
#if 0
/* This is superfluous and makes it impossible to use tab completion in
vi mode even when explicitly binding it in ~/.inputrc. sv_strict_posix()
should already have called posix_readline_initialize() when
posixly_correct was set. */
if (posixly_correct)
posix_readline_initialize (1);
#endif
bash_readline_initialized = 1;
}
void
bashline_reinitialize ()
{
bash_readline_initialized = 0;
}
void
bashline_set_event_hook ()
{
rl_signal_event_hook = bash_event_hook;
}
void
bashline_reset_event_hook ()
{
rl_signal_event_hook = 0;
}
/* On Sun systems at least, rl_attempted_completion_function can end up
getting set to NULL, and rl_completion_entry_function set to do command
word completion if Bash is interrupted while trying to complete a command
word. This just resets all the completion functions to the right thing.
It's called from throw_to_top_level(). */
void
bashline_reset ()
{
tilde_initialize ();
rl_attempted_completion_function = attempt_shell_completion;
rl_completion_entry_function = NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
set_directory_hook ();
rl_filename_stat_hook = bash_filename_stat_hook;
bashline_reset_event_hook ();
rl_sort_completion_matches = 1;
}
/* Contains the line to push into readline. */
static char *push_to_readline = (char *)NULL;
/* Push the contents of push_to_readline into the
readline buffer. */
static int
bash_push_line ()
{
if (push_to_readline)
{
rl_insert_text (push_to_readline);
free (push_to_readline);
push_to_readline = (char *)NULL;
rl_startup_hook = old_rl_startup_hook;
}
return 0;
}
/* Call this to set the initial text for the next line to read
from readline. */
int
bash_re_edit (line)
char *line;
{
FREE (push_to_readline);
push_to_readline = savestring (line);
old_rl_startup_hook = rl_startup_hook;
rl_startup_hook = bash_push_line;
return (0);
}
static int
display_shell_version (count, c)
int count, c;
{
rl_crlf ();
show_shell_version (0);
putc ('\r', rl_outstream);
fflush (rl_outstream);
rl_on_new_line ();
rl_redisplay ();
return 0;
}
/* **************************************************************** */
/* */
/* Readline Stuff */
/* */
/* **************************************************************** */
/* If the user requests hostname completion, then simply build a list
of hosts, and complete from that forever more, or at least until
HOSTFILE is unset. */
/* THIS SHOULD BE A STRINGLIST. */
/* The kept list of hostnames. */
static char **hostname_list = (char **)NULL;
/* The physical size of the above list. */
static int hostname_list_size;
/* The number of hostnames in the above list. */
static int hostname_list_length;
/* Whether or not HOSTNAME_LIST has been initialized. */
int hostname_list_initialized = 0;
/* Initialize the hostname completion table. */
static void
initialize_hostname_list ()
{
char *temp;
temp = get_string_value ("HOSTFILE");
if (temp == 0)
temp = get_string_value ("hostname_completion_file");
if (temp == 0)
temp = DEFAULT_HOSTS_FILE;
snarf_hosts_from_file (temp);
if (hostname_list)
hostname_list_initialized++;
}
/* Add NAME to the list of hosts. */
static void
add_host_name (name)
char *name;
{
if (hostname_list_length + 2 > hostname_list_size)
{
hostname_list_size = (hostname_list_size + 32) - (hostname_list_size % 32);
hostname_list = strvec_resize (hostname_list, hostname_list_size);
}
hostname_list[hostname_list_length++] = savestring (name);
hostname_list[hostname_list_length] = (char *)NULL;
}
#define cr_whitespace(c) ((c) == '\r' || (c) == '\n' || whitespace(c))
static void
snarf_hosts_from_file (filename)
char *filename;
{
FILE *file;
char *temp, buffer[256], name[256];
register int i, start;
file = fopen (filename, "r");
if (file == 0)
return;
while (temp = fgets (buffer, 255, file))
{
/* Skip to first character. */
for (i = 0; buffer[i] && cr_whitespace (buffer[i]); i++)
;
/* If comment or blank line, ignore. */
if (buffer[i] == '\0' || buffer[i] == '#')
continue;
/* If `preprocessor' directive, do the include. */
if (strncmp (buffer + i, "$include ", 9) == 0)
{
char *incfile, *t;
/* Find start of filename. */
for (incfile = buffer + i + 9; *incfile && whitespace (*incfile); incfile++)
;
/* Find end of filename. */
for (t = incfile; *t && cr_whitespace (*t) == 0; t++)
;
*t = '\0';
snarf_hosts_from_file (incfile);
continue;
}
/* Skip internet address if present. */
if (DIGIT (buffer[i]))
for (; buffer[i] && cr_whitespace (buffer[i]) == 0; i++);
/* Gobble up names. Each name is separated with whitespace. */
while (buffer[i])
{
for (; cr_whitespace (buffer[i]); i++)
;
if (buffer[i] == '\0' || buffer[i] == '#')
break;
/* Isolate the current word. */
for (start = i; buffer[i] && cr_whitespace (buffer[i]) == 0; i++)
;
if (i == start)
continue;
strncpy (name, buffer + start, i - start);
name[i - start] = '\0';
add_host_name (name);
}
}
fclose (file);
}
/* Return the hostname list. */
char **
get_hostname_list ()
{
if (hostname_list_initialized == 0)
initialize_hostname_list ();
return (hostname_list);
}
void
clear_hostname_list ()
{
register int i;
if (hostname_list_initialized == 0)
return;
for (i = 0; i < hostname_list_length; i++)
free (hostname_list[i]);
hostname_list_length = hostname_list_initialized = 0;
}
/* Return a NULL terminated list of hostnames which begin with TEXT.
Initialize the hostname list the first time if necessary.
The array is malloc ()'ed, but not the individual strings. */
static char **
hostnames_matching (text)
char *text;
{
register int i, len, nmatch, rsize;
char **result;
if (hostname_list_initialized == 0)
initialize_hostname_list ();
if (hostname_list_initialized == 0)
return ((char **)NULL);
/* Special case. If TEXT consists of nothing, then the whole list is
what is desired. */
if (*text == '\0')
{
result = strvec_create (1 + hostname_list_length);
for (i = 0; i < hostname_list_length; i++)
result[i] = hostname_list[i];
result[i] = (char *)NULL;
return (result);
}
/* Scan until found, or failure. */
len = strlen (text);
result = (char **)NULL;
for (i = nmatch = rsize = 0; i < hostname_list_length; i++)
{
if (STREQN (text, hostname_list[i], len) == 0)
continue;
/* OK, it matches. Add it to the list. */
if (nmatch >= (rsize - 1))
{
rsize = (rsize + 16) - (rsize % 16);
result = strvec_resize (result, rsize);
}
result[nmatch++] = hostname_list[i];
}
if (nmatch)
result[nmatch] = (char *)NULL;
return (result);
}
/* The equivalent of the Korn shell C-o operate-and-get-next-history-line
editing command. */
static int saved_history_line_to_use = -1;
static int last_saved_history_line = -1;
#define HISTORY_FULL() (history_is_stifled () && history_length >= history_max_entries)
static int
set_saved_history ()
{
/* XXX - compensate for assumption that history was `shuffled' if it was
actually not. */
if (HISTORY_FULL () &&
hist_last_line_added == 0 &&
saved_history_line_to_use < history_length - 1)
saved_history_line_to_use++;
if (saved_history_line_to_use >= 0)
{
rl_get_previous_history (history_length - saved_history_line_to_use, 0);
last_saved_history_line = saved_history_line_to_use;
}
saved_history_line_to_use = -1;
rl_startup_hook = old_rl_startup_hook;
return (0);
}
static int
operate_and_get_next (count, c)
int count, c;
{
int where;
/* Accept the current line. */
rl_newline (1, c);
/* Find the current line, and find the next line to use. */
where = rl_explicit_arg ? count : where_history ();
if (HISTORY_FULL () || (where >= history_length - 1) || rl_explicit_arg)
saved_history_line_to_use = where;
else
saved_history_line_to_use = where + 1;
old_rl_startup_hook = rl_startup_hook;
rl_startup_hook = set_saved_history;
return 0;
}
/* This vi mode command causes VI_EDIT_COMMAND to be run on the current
command being entered (if no explicit argument is given), otherwise on
a command from the history file. */
#define VI_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-vi}}\""
#define EMACS_EDIT_COMMAND "fc -e \"${VISUAL:-${EDITOR:-emacs}}\""
#define POSIX_VI_EDIT_COMMAND "fc -e vi"
static int
edit_and_execute_command (count, c, editing_mode, edit_command)
int count, c, editing_mode;
char *edit_command;
{
char *command, *metaval;
int r, rrs, metaflag;
sh_parser_state_t ps;
rrs = rl_readline_state;
saved_command_line_count = current_command_line_count;
/* Accept the current line. */
rl_newline (1, c);
if (rl_explicit_arg)
{
command = (char *)xmalloc (strlen (edit_command) + 8);
sprintf (command, "%s %d", edit_command, count);
}
else
{
/* Take the command we were just editing, add it to the history file,
then call fc to operate on it. We have to add a dummy command to
the end of the history because fc ignores the last command (assumes
it's supposed to deal with the command before the `fc'). */
/* This breaks down when using command-oriented history and are not
finished with the command, so we should not ignore the last command */
using_history ();
current_command_line_count++; /* for rl_newline above */
bash_add_history (rl_line_buffer);
current_command_line_count = 0; /* for dummy history entry */
bash_add_history ("");
history_lines_this_session++;
using_history ();
command = savestring (edit_command);
}
metaval = rl_variable_value ("input-meta");
metaflag = RL_BOOLEAN_VARIABLE_VALUE (metaval);
if (rl_deprep_term_function)
(*rl_deprep_term_function) ();
save_parser_state (&ps);
r = parse_and_execute (command, (editing_mode == VI_EDITING_MODE) ? "v" : "C-xC-e", SEVAL_NOHIST);
restore_parser_state (&ps);
if (rl_prep_term_function)
(*rl_prep_term_function) (metaflag);
current_command_line_count = saved_command_line_count;
/* Now erase the contents of the current line and undo the effects of the
rl_accept_line() above. We don't even want to make the text we just
executed available for undoing. */
rl_line_buffer[0] = '\0'; /* XXX */
rl_point = rl_end = 0;
rl_done = 0;
rl_readline_state = rrs;
#if defined (VI_MODE)
if (editing_mode == VI_EDITING_MODE)
rl_vi_insertion_mode (1, c);
#endif
rl_forced_update_display ();
return r;
}
#if defined (VI_MODE)
static int
vi_edit_and_execute_command (count, c)
int count, c;
{
if (posixly_correct)
return (edit_and_execute_command (count, c, VI_EDITING_MODE, POSIX_VI_EDIT_COMMAND));
else
return (edit_and_execute_command (count, c, VI_EDITING_MODE, VI_EDIT_COMMAND));
}
#endif /* VI_MODE */
static int
emacs_edit_and_execute_command (count, c)
int count, c;
{
return (edit_and_execute_command (count, c, EMACS_EDITING_MODE, EMACS_EDIT_COMMAND));
}
#if defined (ALIAS)
static int
posix_edit_macros (count, key)
int count, key;
{
int c;
char alias_name[3], *alias_value, *macro;
c = rl_read_key ();
alias_name[0] = '_';
alias_name[1] = c;
alias_name[2] = '\0';
alias_value = get_alias_value (alias_name);
if (alias_value && *alias_value)
{
macro = savestring (alias_value);
rl_push_macro_input (macro);
}
return 0;
}
#endif
/* Bindable commands that move `shell-words': that is, sequences of
non-unquoted-metacharacters. */
#define WORDDELIM(c) (shellmeta(c) || shellblank(c))
static int
bash_forward_shellword (count, key)
int count, key;
{
size_t slen;
int c, p;
DECLARE_MBSTATE;
if (count < 0)
return (bash_backward_shellword (-count, key));
/* The tricky part of this is deciding whether or not the first character
we're on is an unquoted metacharacter. Not completely handled yet. */
/* XXX - need to test this stuff with backslash-escaped shell
metacharacters and unclosed single- and double-quoted strings. */
p = rl_point;
slen = rl_end;
while (count)
{
if (p == rl_end)
{
rl_point = rl_end;
return 0;
}
/* Are we in a quoted string? If we are, move to the end of the quoted
string and continue the outer loop. We only want quoted strings, not
backslash-escaped characters, but char_is_quoted doesn't
differentiate. */
if (char_is_quoted (rl_line_buffer, p) && p > 0 && rl_line_buffer[p-1] != '\\')
{
do
ADVANCE_CHAR (rl_line_buffer, slen, p);
while (p < rl_end && char_is_quoted (rl_line_buffer, p));
count--;
continue;
}
/* Rest of code assumes we are not in a quoted string. */
/* Move forward until we hit a non-metacharacter. */
while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c))
{
switch (c)
{
default:
ADVANCE_CHAR (rl_line_buffer, slen, p);
continue; /* straight back to loop, don't increment p */
case '\\':
if (p < rl_end && rl_line_buffer[p])
ADVANCE_CHAR (rl_line_buffer, slen, p);
break;
case '\'':
p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
break;
case '"':
p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
break;
}
if (p < rl_end)
p++;
}
if (rl_line_buffer[p] == 0 || p == rl_end)
{
rl_point = rl_end;
rl_ding ();
return 0;
}
/* Now move forward until we hit a non-quoted metacharacter or EOL */
while (p < rl_end && (c = rl_line_buffer[p]) && WORDDELIM (c) == 0)
{
switch (c)
{
default:
ADVANCE_CHAR (rl_line_buffer, slen, p);
continue; /* straight back to loop, don't increment p */
case '\\':
if (p < rl_end && rl_line_buffer[p])
ADVANCE_CHAR (rl_line_buffer, slen, p);
break;
case '\'':
p = skip_to_delim (rl_line_buffer, ++p, "'", SD_NOJMP);
break;
case '"':
p = skip_to_delim (rl_line_buffer, ++p, "\"", SD_NOJMP);
break;
}
if (p < rl_end)
p++;
}
if (p == rl_end || rl_line_buffer[p] == 0)
{
rl_point = rl_end;
return (0);
}
count--;
}
rl_point = p;
return (0);
}
static int
bash_backward_shellword (count, key)
int count, key;
{
size_t slen;
int c, p, prev_p;
DECLARE_MBSTATE;
if (count < 0)
return (bash_forward_shellword (-count, key));
p = rl_point;
slen = rl_end;
while (count)
{
if (p == 0)
{
rl_point = 0;
return 0;
}
/* Move backward until we hit a non-metacharacter. We want to deal
with the characters before point, so we move off a word if we're
at its first character. */
BACKUP_CHAR (rl_line_buffer, slen, p);
while (p > 0)
{
c = rl_line_buffer[p];
if (WORDDELIM (c) == 0 || char_is_quoted (rl_line_buffer, p))
break;
BACKUP_CHAR (rl_line_buffer, slen, p);
}
if (p == 0)
{
rl_point = 0;
return 0;
}
/* Now move backward until we hit a metacharacter or BOL. Leave point
at the start of the shellword or at BOL. */
prev_p = p;
while (p > 0)
{
c = rl_line_buffer[p];
if (WORDDELIM (c) && char_is_quoted (rl_line_buffer, p) == 0)
{
p = prev_p;
break;
}
prev_p = p;
BACKUP_CHAR (rl_line_buffer, slen, p);
}
count--;
}
rl_point = p;
return 0;
}
static int
bash_kill_shellword (count, key)
int count, key;
{
int p;
if (count < 0)
return (bash_backward_kill_shellword (-count, key));
p = rl_point;
bash_forward_shellword (count, key);
if (rl_point != p)
rl_kill_text (p, rl_point);
rl_point = p;
if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
rl_mark = rl_point;
return 0;
}
static int
bash_backward_kill_shellword (count, key)
int count, key;
{
int p;
if (count < 0)
return (bash_kill_shellword (-count, key));
p = rl_point;
bash_backward_shellword (count, key);
if (rl_point != p)
rl_kill_text (p, rl_point);
if (rl_editing_mode == EMACS_EDITING_MODE) /* 1 == emacs_mode */
rl_mark = rl_point;
return 0;
}
static int
bash_transpose_shellwords (count, key)
int count, key;
{
char *word1, *word2;
int w1_beg, w1_end, w2_beg, w2_end;
int orig_point = rl_point;
if (count == 0)
return 0;
/* Find the two shell words. */
bash_forward_shellword (count, key);
w2_end = rl_point;
bash_backward_shellword (1, key);
w2_beg = rl_point;
bash_backward_shellword (count, key);
w1_beg = rl_point;
bash_forward_shellword (1, key);
w1_end = rl_point;
/* check that there really are two words. */
if ((w1_beg == w2_beg) || (w2_beg < w1_end))
{
rl_ding ();
rl_point = orig_point;
return 1;
}
/* Get the text of the words. */
word1 = rl_copy_text (w1_beg, w1_end);
word2 = rl_copy_text (w2_beg, w2_end);
/* We are about to do many insertions and deletions. Remember them
as one operation. */
rl_begin_undo_group ();
/* Do the stuff at word2 first, so that we don't have to worry
about word1 moving. */
rl_point = w2_beg;
rl_delete_text (w2_beg, w2_end);
rl_insert_text (word1);
rl_point = w1_beg;
rl_delete_text (w1_beg, w1_end);
rl_insert_text (word2);
/* This is exactly correct since the text before this point has not
changed in length. */
rl_point = w2_end;
/* I think that does it. */
rl_end_undo_group ();
xfree (word1);
xfree (word2);
return 0;
}
/* **************************************************************** */
/* */
/* How To Do Shell Completion */
/* */
/* **************************************************************** */
#define COMMAND_SEPARATORS ";|&{(`"
/* )} */
#define COMMAND_SEPARATORS_PLUS_WS ";|&{(` \t"
/* )} */
/* check for redirections and other character combinations that are not
command separators */
static int
check_redir (ti)
int ti;
{
register int this_char, prev_char;
/* Handle the two character tokens `>&', `<&', and `>|'.
We are not in a command position after one of these. */
this_char = rl_line_buffer[ti];
prev_char = (ti > 0) ? rl_line_buffer[ti - 1] : 0;
if ((this_char == '&' && (prev_char == '<' || prev_char == '>')) ||
(this_char == '|' && prev_char == '>'))
return (1);
else if (this_char == '{' && prev_char == '$') /*}*/
return (1);
#if 0 /* Not yet */
else if (this_char == '(' && prev_char == '$') /*)*/
return (1);
else if (this_char == '(' && prev_char == '<') /*)*/
return (1);
#if defined (EXTENDED_GLOB)
else if (extended_glob && this_char == '(' && prev_char == '!') /*)*/
return (1);
#endif
#endif
else if (char_is_quoted (rl_line_buffer, ti))
return (1);
return (0);
}
#if defined (PROGRAMMABLE_COMPLETION)
/*
* XXX - because of the <= start test, and setting os = s+1, this can
* potentially return os > start. This is probably not what we want to
* happen, but fix later after 2.05a-release.
*/
static int
find_cmd_start (start)
int start;
{
register int s, os, ns;
os = 0;
/* Flags == SD_NOJMP only because we want to skip over command substitutions
in assignment statements. Have to test whether this affects `standalone'
command substitutions as individual words. */
while (((s = skip_to_delim (rl_line_buffer, os, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/)) <= start) &&
rl_line_buffer[s])
{
/* Handle >| token crudely; treat as > not | */
if (rl_line_buffer[s] == '|' && rl_line_buffer[s-1] == '>')
{
ns = skip_to_delim (rl_line_buffer, s+1, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE/*|SD_NOSKIPCMD*/);
if (ns > start || rl_line_buffer[ns] == 0)
return os;
os = ns+1;
continue;
}
os = s+1;
}
return os;
}
static int
find_cmd_end (end)
int end;
{
register int e;
e = skip_to_delim (rl_line_buffer, end, COMMAND_SEPARATORS, SD_NOJMP|SD_COMPLETE);
return e;
}
static char *
find_cmd_name (start, sp, ep)
int start;
int *sp, *ep;
{
char *name;
register int s, e;
for (s = start; whitespace (rl_line_buffer[s]); s++)
;
/* skip until a shell break character */
e = skip_to_delim (rl_line_buffer, s, "()<>;&| \t\n", SD_NOJMP|SD_COMPLETE);
name = substring (rl_line_buffer, s, e);
if (sp)
*sp = s;
if (ep)
*ep = e;
return (name);
}
static char *
prog_complete_return (text, matchnum)
const char *text;
int matchnum;
{
static int ind;
if (matchnum == 0)
ind = 0;
if (prog_complete_matches == 0 || prog_complete_matches[ind] == 0)
return (char *)NULL;
return (prog_complete_matches[ind++]);
}
#endif /* PROGRAMMABLE_COMPLETION */
/* Try and catch completion attempts that are syntax errors or otherwise
invalid. */
static int
invalid_completion (text, ind)
const char *text;
int ind;
{
int pind;
/* If we don't catch these here, the next clause will */
if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
member (rl_line_buffer[ind-1], "$<>"))
return 0;
pind = ind - 1;
while (pind > 0 && whitespace (rl_line_buffer[pind]))
pind--;
/* If we have only whitespace preceding a paren, it's valid */
if (ind >= 0 && pind <= 0 && rl_line_buffer[ind] == '(') /*)*/
return 0;
/* Flag the invalid completions, which are mostly syntax errors */
if (ind > 0 && rl_line_buffer[ind] == '(' && /*)*/
member (rl_line_buffer[pind], COMMAND_SEPARATORS) == 0)
return 1;
return 0;
}
/* Do some completion on TEXT. The indices of TEXT in RL_LINE_BUFFER are
at START and END. Return an array of matches, or NULL if none. */
static char **
attempt_shell_completion (text, start, end)
const char *text;
int start, end;
{
int in_command_position, ti, qc, dflags;
char **matches, *command_separator_chars;
#if defined (PROGRAMMABLE_COMPLETION)
int have_progcomps, was_assignment;
COMPSPEC *iw_compspec;
#endif
command_separator_chars = COMMAND_SEPARATORS;
matches = (char **)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_quote_characters = default_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
set_directory_hook ();
rl_filename_stat_hook = bash_filename_stat_hook;
rl_sort_completion_matches = 1; /* sort by default */
/* Determine if this could be a command word. It is if it appears at
the start of the line (ignoring preceding whitespace), or if it
appears after a character that separates commands. It cannot be a
command word if we aren't at the top-level prompt. */
ti = start - 1;
qc = -1;
while ((ti > -1) && (whitespace (rl_line_buffer[ti])))
ti--;
#if 1
/* If this is an open quote, maybe we're trying to complete a quoted
command name. */
if (ti >= 0 && (rl_line_buffer[ti] == '"' || rl_line_buffer[ti] == '\''))
{
qc = rl_line_buffer[ti];
ti--;
while (ti > -1 && (whitespace (rl_line_buffer[ti])))
ti--;
}
#endif
in_command_position = 0;
if (ti < 0)
{
/* Only do command completion at the start of a line when we
are prompting at the top level. */
if (current_prompt_string == ps1_prompt)
in_command_position++;
else if (parser_in_command_position ())
in_command_position++;
}
else if (member (rl_line_buffer[ti], command_separator_chars))
{
in_command_position++;
if (check_redir (ti) == 1)
in_command_position = 0;
}
else
{
/* This still could be in command position. It is possible
that all of the previous words on the line are variable
assignments. */
}
if (in_command_position && invalid_completion (text, ti))
{
rl_attempted_completion_over = 1;
return ((char **)NULL);
}
/* Check that we haven't incorrectly flagged a closed command substitution
as indicating we're in a command position. */
if (in_command_position && ti >= 0 && rl_line_buffer[ti] == '`' &&
*text != '`' && unclosed_pair (rl_line_buffer, end, "`") == 0)
in_command_position = 0;
/* Special handling for command substitution. If *TEXT is a backquote,
it can be the start or end of an old-style command substitution, or
unmatched. If it's unmatched, both calls to unclosed_pair will
succeed. Don't bother if readline found a single quote and we are
completing on the substring. */
if (*text == '`' && rl_completion_quote_character != '\'' &&
(in_command_position || (unclosed_pair (rl_line_buffer, start, "`") &&
unclosed_pair (rl_line_buffer, end, "`"))))
matches = rl_completion_matches (text, command_subst_completion_function);
#if defined (PROGRAMMABLE_COMPLETION)
/* Attempt programmable completion. */
have_progcomps = prog_completion_enabled && (progcomp_size () > 0);
iw_compspec = progcomp_search (INITIALWORD);
if (matches == 0 &&
(in_command_position == 0 || text[0] == '\0' || (in_command_position && iw_compspec)) &&
current_prompt_string == ps1_prompt)
{
int s, e, s1, e1, os, foundcs;
char *n;
/* XXX - don't free the members */
if (prog_complete_matches)
free (prog_complete_matches);
prog_complete_matches = (char **)NULL;
os = start;
n = 0;
was_assignment = 0;
s = find_cmd_start (os);
e = find_cmd_end (end);
do
{
/* Don't read past the end of rl_line_buffer */
if (s > rl_end)
{
s1 = s = e1;
break;
}
/* Or past point if point is within an assignment statement */
else if (was_assignment && s > rl_point)
{
s1 = s = e1;
break;
}
/* Skip over assignment statements preceding a command name. If we
don't find a command name at all, we can perform command name
completion. If we find a partial command name, we should perform
command name completion on it. */
FREE (n);
n = find_cmd_name (s, &s1, &e1);
s = e1 + 1;
}
while (was_assignment = assignment (n, 0));
s = s1; /* reset to index where name begins */
/* s == index of where command name begins (reset above)
e == end of current command, may be end of line
s1 = index of where command name begins
e1 == index of where command name ends
start == index of where word to be completed begins
end == index of where word to be completed ends
if (s == start) we are doing command word completion for sure
if (e1 == end) we are at the end of the command name and completing it */
if (start == 0 && end == 0 && e != 0 && text[0] == '\0') /* beginning of non-empty line */
foundcs = 0;
else if (start == end && start == s1 && e != 0 && e1 > end) /* beginning of command name, leading whitespace */
foundcs = 0;
else if (e == 0 && e == s && text[0] == '\0' && have_progcomps) /* beginning of empty line */
prog_complete_matches = programmable_completions (EMPTYCMD, text, s, e, &foundcs);
else if (start == end && text[0] == '\0' && s1 > start && whitespace (rl_line_buffer[start]))
foundcs = 0; /* whitespace before command name */
else if (e > s && was_assignment == 0 && e1 == end && rl_line_buffer[e] == 0 && whitespace (rl_line_buffer[e-1]) == 0)
{
/* not assignment statement, but still want to perform command
completion if we are composing command word. */
foundcs = 0;
in_command_position = s == start && STREQ (n, text); /* XXX */
}
else if (e > s && was_assignment == 0 && have_progcomps)
{
prog_complete_matches = programmable_completions (n, text, s, e, &foundcs);
/* command completion if programmable completion fails */
/* If we have a completion for the initial word, we can prefer that */
in_command_position = s == start && (iw_compspec || STREQ (n, text)); /* XXX */
if (iw_compspec && in_command_position)
foundcs = 0;
}
/* empty command name following command separator */
else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0 &&
was_assignment == 0 && member (rl_line_buffer[start-1], COMMAND_SEPARATORS))
{
foundcs = 0;
in_command_position = 1;
}
else if (s >= e && n[0] == '\0' && text[0] == '\0' && start > 0)
{
foundcs = 0; /* empty command name following optional assignments */
in_command_position += was_assignment;
}
else if (s == start && e == end && STREQ (n, text) && start > 0)
{
foundcs = 0; /* partial command name following assignments */
in_command_position = 1;
}
else
foundcs = 0;
/* If we have defined a compspec for the initial (command) word, call
it and process the results like any other programmable completion. */
if (in_command_position && have_progcomps && foundcs == 0 && iw_compspec)
prog_complete_matches = programmable_completions (INITIALWORD, text, s, e, &foundcs);
FREE (n);
/* XXX - if we found a COMPSPEC for the command, just return whatever
the programmable completion code returns, and disable the default
filename completion that readline will do unless the COPT_DEFAULT
option has been set with the `-o default' option to complete or
compopt. */
if (foundcs)
{
pcomp_set_readline_variables (foundcs, 1);
/* Turn what the programmable completion code returns into what
readline wants. I should have made compute_lcd_of_matches
external... */
matches = rl_completion_matches (text, prog_complete_return);
if ((foundcs & COPT_DEFAULT) == 0)
rl_attempted_completion_over = 1; /* no default */
if (matches || ((foundcs & COPT_BASHDEFAULT) == 0))
return (matches);
}
}
#endif
if (matches == 0)
{
dflags = 0;
if (in_command_position)
dflags |= DEFCOMP_CMDPOS;
matches = bash_default_completion (text, start, end, qc, dflags);
}
return matches;
}
char **
bash_default_completion (text, start, end, qc, compflags)
const char *text;
int start, end, qc, compflags;
{
char **matches, *t;
matches = (char **)NULL;
/* New posix-style command substitution or variable name? */
if (*text == '$')
{
if (qc != '\'' && text[1] == '(') /* ) */
matches = rl_completion_matches (text, command_subst_completion_function);
else
{
matches = rl_completion_matches (text, variable_completion_function);
/* If a single match, see if it expands to a directory name and append
a slash if it does. This requires us to expand the variable name,
so we don't want to display errors if the variable is unset. This
can happen with dynamic variables whose value has never been
requested. */
if (matches && matches[0] && matches[1] == 0)
{
t = savestring (matches[0]);
bash_filename_stat_hook (&t);
/* doesn't use test_for_directory because that performs tilde
expansion */
if (file_isdir (t))
rl_completion_append_character = '/';
free (t);
}
}
}
/* If the word starts in `~', and there is no slash in the word, then
try completing this word as a username. */
if (matches == 0 && *text == '~' && mbschr (text, '/') == 0)
matches = rl_completion_matches (text, rl_username_completion_function);
/* Another one. Why not? If the word starts in '@', then look through
the world of known hostnames for completion first. */
if (matches == 0 && perform_hostname_completion && *text == '@')
matches = rl_completion_matches (text, hostname_completion_function);
/* And last, (but not least) if this word is in a command position, then
complete over possible command names, including aliases, functions,
and command names. */
if (matches == 0 && (compflags & DEFCOMP_CMDPOS))
{
/* If END == START and text[0] == 0, we are trying to complete an empty
command word. */
if (no_empty_command_completion && end == start && text[0] == '\0')
{
matches = (char **)NULL;
rl_ignore_some_completions_function = bash_ignore_everything;
}
else
{
#define CMD_IS_DIR(x) (absolute_pathname(x) == 0 && absolute_program(x) == 0 && *(x) != '~' && test_for_directory (x))
dot_in_path = 0;
matches = rl_completion_matches (text, command_word_completion_function);
/* If we are attempting command completion and nothing matches, we
do not want readline to perform filename completion for us. We
still want to be able to complete partial pathnames, so set the
completion ignore function to something which will remove
filenames and leave directories in the match list. */
if (matches == (char **)NULL)
rl_ignore_some_completions_function = bash_ignore_filenames;
else if (matches[1] == 0 && CMD_IS_DIR(matches[0]) && dot_in_path == 0)
/* If we found a single match, without looking in the current
directory (because it's not in $PATH), but the found name is
also a command in the current directory, suppress appending any
terminating character, since it's ambiguous. */
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
else if (matches[0] && matches[1] && STREQ (matches[0], matches[1]) && CMD_IS_DIR (matches[0]))
/* There are multiple instances of the same match (duplicate
completions haven't yet been removed). In this case, all of
the matches will be the same, and the duplicate removal code
will distill them all down to one. We turn on
rl_completion_suppress_append for the same reason as above.
Remember: we only care if there's eventually a single unique
completion. If there are multiple completions this won't
make a difference and the problem won't occur. */
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
}
}
/* This could be a globbing pattern, so try to expand it using pathname
expansion. */
if (!matches && completion_glob_pattern ((char *)text))
{
matches = rl_completion_matches (text, glob_complete_word);
/* A glob expression that matches more than one filename is problematic.
If we match more than one filename, punt. */
if (matches && matches[1] && rl_completion_type == TAB)
{
strvec_dispose (matches);
matches = (char **)0;
}
else if (matches && matches[1] && rl_completion_type == '!')
{
rl_completion_suppress_append = 1;
rl_filename_completion_desired = 0;
}
}
return (matches);
}
static int
bash_command_name_stat_hook (name)
char **name;
{
char *cname, *result;
/* If it's not something we're going to look up in $PATH, just call the
normal filename stat hook. */
if (absolute_program (*name))
return (bash_filename_stat_hook (name));
cname = *name;
/* XXX - we could do something here with converting aliases, builtins,
and functions into something that came out as executable, but we don't. */
result = search_for_command (cname, 0);
if (result)
{
*name = result;
return 1;
}
return 0;
}
static int
executable_completion (filename, searching_path)
const char *filename;
int searching_path;
{
char *f;
int r;
f = savestring (filename);
bash_directory_completion_hook (&f);
r = searching_path ? executable_file (f) : executable_or_directory (f);
free (f);
return r;
}
/* This is the function to call when the word to complete is in a position
where a command word can be found. It grovels $PATH, looking for commands
that match. It also scans aliases, function names, and the shell_builtin
table. */
char *
command_word_completion_function (hint_text, state)
const char *hint_text;
int state;
{
static char *hint = (char *)NULL;
static char *path = (char *)NULL;
static char *val = (char *)NULL;
static char *filename_hint = (char *)NULL;
static char *fnhint = (char *)NULL;
static char *dequoted_hint = (char *)NULL;
static char *directory_part = (char *)NULL;
static char **glob_matches = (char **)NULL;
static int path_index, hint_len, istate, igncase;
static int mapping_over, local_index, searching_path, hint_is_dir;
static int old_glob_ignore_case, globpat;
static SHELL_VAR **varlist = (SHELL_VAR **)NULL;
#if defined (ALIAS)
static alias_t **alias_list = (alias_t **)NULL;
#endif /* ALIAS */
char *temp, *cval;
/* We have to map over the possibilities for command words. If we have
no state, then make one just for that purpose. */
if (state == 0)
{
rl_filename_stat_hook = bash_command_name_stat_hook;
if (dequoted_hint && dequoted_hint != hint)
free (dequoted_hint);
if (hint)
free (hint);
mapping_over = searching_path = 0;
hint_is_dir = CMD_IS_DIR (hint_text);
val = (char *)NULL;
temp = rl_variable_value ("completion-ignore-case");
igncase = RL_BOOLEAN_VARIABLE_VALUE (temp);
if (glob_matches)
{
free (glob_matches);
glob_matches = (char **)NULL;
}
globpat = completion_glob_pattern ((char *)hint_text);
/* If this is an absolute program name, do not check it against
aliases, reserved words, functions or builtins. We must check
whether or not it is unique, and, if so, whether that filename
is executable. */
if (globpat || absolute_program (hint_text))
{
/* Perform tilde expansion on what's passed, so we don't end up
passing filenames with tildes directly to stat(). The rest of
the shell doesn't do variable expansion on the word following
the tilde, so we don't do it here even if direxpand is set. */
if (*hint_text == '~')
{
hint = bash_tilde_expand (hint_text, 0);
directory_part = savestring (hint_text);
temp = strchr (directory_part, '/');
if (temp)
*temp = 0;
else
{
free (directory_part);
directory_part = (char *)NULL;
}
}
else if (dircomplete_expand)
{
hint = savestring (hint_text);
bash_directory_completion_hook (&hint);
}
else
hint = savestring (hint_text);
dequoted_hint = hint;
/* If readline's completer found a quote character somewhere, but
didn't set the quote character, there must have been a quote
character embedded in the filename. It can't be at the start of
the filename, so we need to dequote the filename before we look
in the file system for it. */
if (rl_completion_found_quote && rl_completion_quote_character == 0)
{
dequoted_hint = bash_dequote_filename (hint, 0);
free (hint);
hint = dequoted_hint;
}
hint_len = strlen (hint);
if (filename_hint)
free (filename_hint);
fnhint = filename_hint = savestring (hint);
istate = 0;
if (globpat)
{
mapping_over = 5;
goto globword;
}
else
{
if (dircomplete_expand && path_dot_or_dotdot (filename_hint))
{
dircomplete_expand = 0;
set_directory_hook ();
dircomplete_expand = 1;
}
mapping_over = 4;
goto inner;
}
}
dequoted_hint = hint = savestring (hint_text);
hint_len = strlen (hint);
if (rl_completion_found_quote && rl_completion_quote_character == 0)
dequoted_hint = bash_dequote_filename (hint, 0);
path = get_string_value ("PATH");
path_index = dot_in_path = 0;
/* Initialize the variables for each type of command word. */
local_index = 0;
if (varlist)
free (varlist);
varlist = all_visible_functions ();
#if defined (ALIAS)
if (alias_list)
free (alias_list);
alias_list = all_aliases ();
#endif /* ALIAS */
}
/* mapping_over says what we are currently hacking. Note that every case
in this list must fall through when there are no more possibilities. */
switch (mapping_over)
{
case 0: /* Aliases come first. */
#if defined (ALIAS)
while (alias_list && alias_list[local_index])
{
register char *alias;
alias = alias_list[local_index++]->name;
if (igncase == 0 && (STREQN (alias, hint, hint_len)))
return (savestring (alias));
else if (igncase && strncasecmp (alias, hint, hint_len) == 0)
return (savestring (alias));
}
#endif /* ALIAS */
local_index = 0;
mapping_over++;
case 1: /* Then shell reserved words. */
{
while (word_token_alist[local_index].word)
{
register char *reserved_word;
reserved_word = word_token_alist[local_index++].word;
if (STREQN (reserved_word, hint, hint_len))
return (savestring (reserved_word));
}
local_index = 0;
mapping_over++;
}
case 2: /* Then function names. */
while (varlist && varlist[local_index])
{
register char *varname;
varname = varlist[local_index++]->name;
/* Honor completion-ignore-case for shell function names. */
if (igncase == 0 && (STREQN (varname, hint, hint_len)))
return (savestring (varname));
else if (igncase && strncasecmp (varname, hint, hint_len) == 0)
return (savestring (varname));
}
local_index = 0;
mapping_over++;
case 3: /* Then shell builtins. */
for (; local_index < num_shell_builtins; local_index++)
{
/* Ignore it if it doesn't have a function pointer or if it
is not currently enabled. */
if (!shell_builtins[local_index].function ||
(shell_builtins[local_index].flags & BUILTIN_ENABLED) == 0)
continue;
if (STREQN (shell_builtins[local_index].name, hint, hint_len))
{
int i = local_index++;
return (savestring (shell_builtins[i].name));
}
}
local_index = 0;
mapping_over++;
}
globword:
/* Limited support for completing command words with globbing chars. Only
a single match (multiple matches that end up reducing the number of
characters in the common prefix are bad) will ever be returned on
regular completion. */
if (globpat)
{
if (state == 0)
{
glob_ignore_case = igncase;
glob_matches = shell_glob_filename (hint);
glob_ignore_case = old_glob_ignore_case;
if (GLOB_FAILED (glob_matches) || glob_matches == 0)
{
glob_matches = (char **)NULL;
return ((char *)NULL);
}
local_index = 0;
if (glob_matches[1] && rl_completion_type == TAB) /* multiple matches are bad */
return ((char *)NULL);
}
while (val = glob_matches[local_index++])
{
if (executable_or_directory (val))
{
if (*hint_text == '~' && directory_part)
{
temp = maybe_restore_tilde (val, directory_part);
free (val);
val = temp;
}
return (val);
}
free (val);
}
glob_ignore_case = old_glob_ignore_case;
return ((char *)NULL);
}
/* If the text passed is a directory in the current directory, return it
as a possible match. Executables in directories in the current
directory can be specified using relative pathnames and successfully
executed even when `.' is not in $PATH. */
if (hint_is_dir)
{
hint_is_dir = 0; /* only return the hint text once */
return (savestring (hint_text));
}
/* Repeatedly call filename_completion_function while we have
members of PATH left. Question: should we stat each file?
Answer: we call executable_file () on each file. */
outer:
istate = (val != (char *)NULL);
if (istate == 0)
{
char *current_path;
/* Get the next directory from the path. If there is none, then we
are all done. */
if (path == 0 || path[path_index] == 0 ||
(current_path = extract_colon_unit (path, &path_index)) == 0)
return ((char *)NULL);
searching_path = 1;
if (*current_path == 0)
{
free (current_path);
current_path = savestring (".");
}
if (*current_path == '~')
{
char *t;
t = bash_tilde_expand (current_path, 0);
free (current_path);
current_path = t;
}
if (current_path[0] == '.' && current_path[1] == '\0')
dot_in_path = 1;
if (fnhint && fnhint != filename_hint)
free (fnhint);
if (filename_hint)
free (filename_hint);
filename_hint = sh_makepath (current_path, hint, 0);
/* Need a quoted version (though it doesn't matter much in most
cases) because rl_filename_completion_function dequotes the
filename it gets, assuming that it's been quoted as part of
the input line buffer. */
if (strpbrk (filename_hint, "\"'\\"))
fnhint = sh_backslash_quote (filename_hint, filename_bstab, 0);
else
fnhint = filename_hint;
free (current_path); /* XXX */
}
inner:
val = rl_filename_completion_function (fnhint, istate);
if (mapping_over == 4 && dircomplete_expand)
set_directory_hook ();
istate = 1;
if (val == 0)
{
/* If the hint text is an absolute program, then don't bother
searching through PATH. */
if (absolute_program (hint))
return ((char *)NULL);
goto outer;
}
else
{
int match, freetemp;
if (absolute_program (hint))
{
if (igncase == 0)
match = strncmp (val, hint, hint_len) == 0;
else
match = strncasecmp (val, hint, hint_len) == 0;
/* If we performed tilde expansion, restore the original
filename. */
if (*hint_text == '~')
temp = maybe_restore_tilde (val, directory_part);
else
temp = savestring (val);
freetemp = 1;
}
else
{
temp = strrchr (val, '/');
if (temp)
{
temp++;
if (igncase == 0)
freetemp = match = strncmp (temp, hint, hint_len) == 0;
else
freetemp = match = strncasecmp (temp, hint, hint_len) == 0;
if (match)
temp = savestring (temp);
}
else
freetemp = match = 0;
}
/* If we have found a match, and it is an executable file, return it.
We don't return directory names when searching $PATH, since the
bash execution code won't find executables in directories which
appear in directories in $PATH when they're specified using
relative pathnames. */
#if 0
/* If we're not searching $PATH and we have a relative pathname, we
need to re-canonicalize it before testing whether or not it's an
executable or a directory so the shell treats .. relative to $PWD
according to the physical/logical option. The shell already
canonicalizes the directory name in order to tell readline where
to look, so not doing it here will be inconsistent. */
/* XXX -- currently not used -- will introduce more inconsistency,
since shell does not canonicalize ../foo before passing it to
shell_execve(). */
if (match && searching_path == 0 && *val == '.')
{
char *t, *t1;
t = get_working_directory ("command-word-completion");
t1 = make_absolute (val, t);
free (t);
cval = sh_canonpath (t1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
}
else
#endif
cval = val;
if (match && executable_completion ((searching_path ? val : cval), searching_path))
{
if (cval != val)
free (cval);
free (val);
val = ""; /* So it won't be NULL. */
return (temp);
}
else
{
if (freetemp)
free (temp);
if (cval != val)
free (cval);
free (val);
goto inner;
}
}
}
/* Completion inside an unterminated command substitution. */
static char *
command_subst_completion_function (text, state)
const char *text;
int state;
{
static char **matches = (char **)NULL;
static const char *orig_start;
static char *filename_text = (char *)NULL;
static int cmd_index, start_len;
char *value;
if (state == 0)
{
if (filename_text)
free (filename_text);
orig_start = text;
if (*text == '`')
text++;
else if (*text == '$' && text[1] == '(') /* ) */
text += 2;
/* If the text was quoted, suppress any quote character that the
readline completion code would insert. */
rl_completion_suppress_quote = 1;
start_len = text - orig_start;
filename_text = savestring (text);
if (matches)
free (matches);
/*
* At this point we can entertain the idea of re-parsing
* `filename_text' into a (possibly incomplete) command name and
* arguments, and doing completion based on that. This is
* currently very rudimentary, but it is a small improvement.
*/
for (value = filename_text + strlen (filename_text) - 1; value > filename_text; value--)
if (whitespace (*value) || member (*value, COMMAND_SEPARATORS))
break;
if (value <= filename_text)
matches = rl_completion_matches (filename_text, command_word_completion_function);
else
{
value++;
start_len += value - filename_text;
if (whitespace (value[-1]))
matches = rl_completion_matches (value, rl_filename_completion_function);
else
matches = rl_completion_matches (value, command_word_completion_function);
}
/* If there is more than one match, rl_completion_matches has already
put the lcd in matches[0]. Skip over it. */
cmd_index = matches && matches[0] && matches[1];
/* If there's a single match and it's a directory, set the append char
to the expected `/'. Otherwise, don't append anything. */
if (matches && matches[0] && matches[1] == 0 && test_for_directory (matches[0]))
rl_completion_append_character = '/';
else
rl_completion_suppress_append = 1;
}
if (matches == 0 || matches[cmd_index] == 0)
{
rl_filename_quoting_desired = 0; /* disable quoting */
return ((char *)NULL);
}
else
{
value = (char *)xmalloc (1 + start_len + strlen (matches[cmd_index]));
if (start_len == 1)
value[0] = *orig_start;
else
strncpy (value, orig_start, start_len);
strcpy (value + start_len, matches[cmd_index]);
cmd_index++;
return (value);
}
}
/* Okay, now we write the entry_function for variable completion. */
static char *
variable_completion_function (text, state)
const char *text;
int state;
{
static char **varlist = (char **)NULL;
static int varlist_index;
static char *varname = (char *)NULL;
static int first_char, first_char_loc;
if (!state)
{
if (varname)
free (varname);
first_char_loc = 0;
first_char = text[0];
if (first_char == '$')
first_char_loc++;
if (text[first_char_loc] == '{')
first_char_loc++;
varname = savestring (text + first_char_loc);
if (varlist)
strvec_dispose (varlist);
varlist = all_variables_matching_prefix (varname);
varlist_index = 0;
}
if (!varlist || !varlist[varlist_index])
{
return ((char *)NULL);
}
else
{
char *value;
value = (char *)xmalloc (4 + strlen (varlist[varlist_index]));
if (first_char_loc)
{
value[0] = first_char;
if (first_char_loc == 2)
value[1] = '{';
}
strcpy (value + first_char_loc, varlist[varlist_index]);
if (first_char_loc == 2)
strcat (value, "}");
varlist_index++;
return (value);
}
}
/* How about a completion function for hostnames? */
static char *
hostname_completion_function (text, state)
const char *text;
int state;
{
static char **list = (char **)NULL;
static int list_index = 0;
static int first_char, first_char_loc;
/* If we don't have any state, make some. */
if (state == 0)
{
FREE (list);
list = (char **)NULL;
first_char_loc = 0;
first_char = *text;
if (first_char == '@')
first_char_loc++;
list = hostnames_matching ((char *)text+first_char_loc);
list_index = 0;
}
if (list && list[list_index])
{
char *t;
t = (char *)xmalloc (2 + strlen (list[list_index]));
*t = first_char;
strcpy (t + first_char_loc, list[list_index]);
list_index++;
return (t);
}
return ((char *)NULL);
}
/*
* A completion function for service names from /etc/services (or wherever).
*/
char *
bash_servicename_completion_function (text, state)
const char *text;
int state;
{
#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GETSERVENT)
return ((char *)NULL);
#else
static char *sname = (char *)NULL;
static struct servent *srvent;
static int snamelen;
char *value;
char **alist, *aentry;
int afound;
if (state == 0)
{
FREE (sname);
sname = savestring (text);
snamelen = strlen (sname);
setservent (0);
}
while (srvent = getservent ())
{
afound = 0;
if (snamelen == 0 || (STREQN (sname, srvent->s_name, snamelen)))
break;
/* Not primary, check aliases */
for (alist = srvent->s_aliases; *alist; alist++)
{
aentry = *alist;
if (STREQN (sname, aentry, snamelen))
{
afound = 1;
break;
}
}
if (afound)
break;
}
if (srvent == 0)
{
endservent ();
return ((char *)NULL);
}
value = afound ? savestring (aentry) : savestring (srvent->s_name);
return value;
#endif
}
/*
* A completion function for group names from /etc/group (or wherever).
*/
char *
bash_groupname_completion_function (text, state)
const char *text;
int state;
{
#if defined (__WIN32__) || defined (__OPENNT) || !defined (HAVE_GRP_H)
return ((char *)NULL);
#else
static char *gname = (char *)NULL;
static struct group *grent;
static int gnamelen;
char *value;
if (state == 0)
{
FREE (gname);
gname = savestring (text);
gnamelen = strlen (gname);
setgrent ();
}
while (grent = getgrent ())
{
if (gnamelen == 0 || (STREQN (gname, grent->gr_name, gnamelen)))
break;
}
if (grent == 0)
{
endgrent ();
return ((char *)NULL);
}
value = savestring (grent->gr_name);
return (value);
#endif
}
/* Functions to perform history and alias expansions on the current line. */
#if defined (BANG_HISTORY)
/* Perform history expansion on the current line. If no history expansion
is done, pre_process_line() returns what it was passed, so we need to
allocate a new line here. */
static char *
history_expand_line_internal (line)
char *line;
{
char *new_line;
int old_verify;
old_verify = hist_verify;
hist_verify = 0;
new_line = pre_process_line (line, 0, 0);
hist_verify = old_verify;
return (new_line == line) ? savestring (line) : new_line;
}
#endif
/* There was an error in expansion. Let the preprocessor print
the error here. */
static void
cleanup_expansion_error ()
{
char *to_free;
#if defined (BANG_HISTORY)
int old_verify;
old_verify = hist_verify;
hist_verify = 0;
#endif
fprintf (rl_outstream, "\r\n");
to_free = pre_process_line (rl_line_buffer, 1, 0);
#if defined (BANG_HISTORY)
hist_verify = old_verify;
#endif
if (to_free != rl_line_buffer)
FREE (to_free);
putc ('\r', rl_outstream);
rl_forced_update_display ();
}
/* If NEW_LINE differs from what is in the readline line buffer, add an
undo record to get from the readline line buffer contents to the new
line and make NEW_LINE the current readline line. */
static void
maybe_make_readline_line (new_line)
char *new_line;
{
if (new_line && strcmp (new_line, rl_line_buffer) != 0)
{
rl_point = rl_end;
rl_add_undo (UNDO_BEGIN, 0, 0, 0);
rl_delete_text (0, rl_point);
rl_point = rl_end = rl_mark = 0;
rl_insert_text (new_line);
rl_add_undo (UNDO_END, 0, 0, 0);
}
}
/* Make NEW_LINE be the current readline line. This frees NEW_LINE. */
static void
set_up_new_line (new_line)
char *new_line;
{
int old_point, at_end;
old_point = rl_point;
at_end = rl_point == rl_end;
/* If the line was history and alias expanded, then make that
be one thing to undo. */
maybe_make_readline_line (new_line);
free (new_line);
/* Place rl_point where we think it should go. */
if (at_end)
rl_point = rl_end;
else if (old_point < rl_end)
{
rl_point = old_point;
if (!whitespace (rl_line_buffer[rl_point]))
rl_forward_word (1, 0);
}
}
#if defined (ALIAS)
/* Expand aliases in the current readline line. */
static int
alias_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = alias_expand (rl_line_buffer);
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
#endif
#if defined (BANG_HISTORY)
/* History expand the line. */
static int
history_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = history_expand_line_internal (rl_line_buffer);
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
/* Expand history substitutions in the current line and then insert a
space (hopefully close to where we were before). */
static int
tcsh_magic_space (count, ignore)
int count, ignore;
{
int dist_from_end, old_point;
old_point = rl_point;
dist_from_end = rl_end - rl_point;
if (history_expand_line (count, ignore) == 0)
{
/* Try a simple heuristic from Stephen Gildea <gildea@intouchsys.com>.
This works if all expansions were before rl_point or if no expansions
were performed. */
rl_point = (old_point == 0) ? old_point : rl_end - dist_from_end;
rl_insert (1, ' ');
return (0);
}
else
return (1);
}
#endif /* BANG_HISTORY */
/* History and alias expand the line. */
static int
history_and_alias_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
new_line = 0;
#if defined (BANG_HISTORY)
new_line = history_expand_line_internal (rl_line_buffer);
#endif
#if defined (ALIAS)
if (new_line)
{
char *alias_line;
alias_line = alias_expand (new_line);
free (new_line);
new_line = alias_line;
}
#endif /* ALIAS */
if (new_line)
{
set_up_new_line (new_line);
return (0);
}
else
{
cleanup_expansion_error ();
return (1);
}
}
/* History and alias expand the line, then perform the shell word
expansions by calling expand_string. This can't use set_up_new_line()
because we want the variable expansions as a separate undo'able
set of operations. */
static int
shell_expand_line (count, ignore)
int count, ignore;
{
char *new_line;
WORD_LIST *expanded_string;
WORD_DESC *w;
new_line = 0;
#if defined (BANG_HISTORY)
new_line = history_expand_line_internal (rl_line_buffer);
#endif
#if defined (ALIAS)
if (new_line)
{
char *alias_line;
alias_line = alias_expand (new_line);
free (new_line);
new_line = alias_line;
}
#endif /* ALIAS */
if (new_line)
{
int old_point = rl_point;
int at_end = rl_point == rl_end;
/* If the line was history and alias expanded, then make that
be one thing to undo. */
maybe_make_readline_line (new_line);
free (new_line);
/* If there is variable expansion to perform, do that as a separate
operation to be undone. */
#if 1
w = alloc_word_desc ();
w->word = savestring (rl_line_buffer);
w->flags = rl_explicit_arg ? (W_NOPROCSUB|W_NOCOMSUB) : 0;
expanded_string = expand_word (w, rl_explicit_arg ? Q_HERE_DOCUMENT : 0);
dispose_word (w);
#else
new_line = savestring (rl_line_buffer);
expanded_string = expand_string (new_line, 0);
FREE (new_line);
#endif
if (expanded_string == 0)
{
new_line = (char *)xmalloc (1);
new_line[0] = '\0';
}
else
{
new_line = string_list (expanded_string);
dispose_words (expanded_string);
}
maybe_make_readline_line (new_line);
free (new_line);
/* Place rl_point where we think it should go. */
if (at_end)
rl_point = rl_end;
else if (old_point < rl_end)
{
rl_point = old_point;
if (!whitespace (rl_line_buffer[rl_point]))
rl_forward_word (1, 0);
}
return 0;
}
else
{
cleanup_expansion_error ();
return 1;
}
}
/* If FIGNORE is set, then don't match files with the given suffixes when
completing filenames. If only one of the possibilities has an acceptable
suffix, delete the others, else just return and let the completer
signal an error. It is called by the completer when real
completions are done on filenames by the completer's internal
function, not for completion lists (M-?) and not on "other"
completion types, such as hostnames or commands. */
static struct ignorevar fignore =
{
"FIGNORE",
(struct ign *)0,
0,
(char *)0,
(sh_iv_item_func_t *) 0,
};
static void
_ignore_completion_names (names, name_func)
char **names;
sh_ignore_func_t *name_func;
{
char **newnames;
int idx, nidx;
char **oldnames;
int oidx;
/* If there is only one completion, see if it is acceptable. If it is
not, free it up. In any case, short-circuit and return. This is a
special case because names[0] is not the prefix of the list of names
if there is only one completion; it is the completion itself. */
if (names[1] == (char *)0)
{
if (force_fignore)
if ((*name_func) (names[0]) == 0)
{
free (names[0]);
names[0] = (char *)NULL;
}
return;
}
/* Allocate space for array to hold list of pointers to matching
filenames. The pointers are copied back to NAMES when done. */
for (nidx = 1; names[nidx]; nidx++)
;
newnames = strvec_create (nidx + 1);
if (force_fignore == 0)
{
oldnames = strvec_create (nidx - 1);
oidx = 0;
}
newnames[0] = names[0];
for (idx = nidx = 1; names[idx]; idx++)
{
if ((*name_func) (names[idx]))
newnames[nidx++] = names[idx];
else if (force_fignore == 0)
oldnames[oidx++] = names[idx];
else
free (names[idx]);
}
newnames[nidx] = (char *)NULL;
/* If none are acceptable then let the completer handle it. */
if (nidx == 1)
{
if (force_fignore)
{
free (names[0]);
names[0] = (char *)NULL;
}
else
free (oldnames);
free (newnames);
return;
}
if (force_fignore == 0)
{
while (oidx)
free (oldnames[--oidx]);
free (oldnames);
}
/* If only one is acceptable, copy it to names[0] and return. */
if (nidx == 2)
{
free (names[0]);
names[0] = newnames[1];
names[1] = (char *)NULL;
free (newnames);
return;
}
/* Copy the acceptable names back to NAMES, set the new array end,
and return. */
for (nidx = 1; newnames[nidx]; nidx++)
names[nidx] = newnames[nidx];
names[nidx] = (char *)NULL;
free (newnames);
}
static int
name_is_acceptable (name)
const char *name;
{
struct ign *p;
int nlen;
for (nlen = strlen (name), p = fignore.ignores; p->val; p++)
{
if (nlen > p->len && p->len > 0 && STREQ (p->val, &name[nlen - p->len]))
return (0);
}
return (1);
}
#if 0
static int
ignore_dot_names (name)
char *name;
{
return (name[0] != '.');
}
#endif
static int
filename_completion_ignore (names)
char **names;
{
#if 0
if (glob_dot_filenames == 0)
_ignore_completion_names (names, ignore_dot_names);
#endif
setup_ignore_patterns (&fignore);
if (fignore.num_ignores == 0)
return 0;
_ignore_completion_names (names, name_is_acceptable);
return 0;
}
/* Return 1 if NAME is a directory. NAME undergoes tilde expansion. */
static int
test_for_directory (name)
const char *name;
{
char *fn;
int r;
fn = bash_tilde_expand (name, 0);
r = file_isdir (fn);
free (fn);
return (r);
}
static int
test_for_canon_directory (name)
const char *name;
{
char *fn;
int r;
fn = (*name == '~') ? bash_tilde_expand (name, 0) : savestring (name);
bash_filename_stat_hook (&fn);
r = file_isdir (fn);
free (fn);
return (r);
}
/* Remove files from NAMES, leaving directories. */
static int
bash_ignore_filenames (names)
char **names;
{
_ignore_completion_names (names, test_for_directory);
return 0;
}
static int
bash_progcomp_ignore_filenames (names)
char **names;
{
_ignore_completion_names (names, test_for_canon_directory);
return 0;
}
static int
return_zero (name)
const char *name;
{
return 0;
}
static int
bash_ignore_everything (names)
char **names;
{
_ignore_completion_names (names, return_zero);
return 0;
}
/* Replace a tilde-prefix in VAL with a `~', assuming the user typed it. VAL
is an expanded filename. DIRECTORY_PART is the tilde-prefix portion
of the un-tilde-expanded version of VAL (what the user typed). */
static char *
restore_tilde (val, directory_part)
char *val, *directory_part;
{
int l, vl, dl2, xl;
char *dh2, *expdir, *ret, *v;
vl = strlen (val);
/* We need to duplicate the expansions readline performs on the directory
portion before passing it to our completion function. */
dh2 = directory_part ? bash_dequote_filename (directory_part, 0) : 0;
bash_directory_expansion (&dh2);
dl2 = strlen (dh2);
expdir = bash_tilde_expand (directory_part, 0);
xl = strlen (expdir);
if (*directory_part == '~' && STREQ (directory_part, expdir))
{
/* tilde expansion failed, so what should we return? we use what the
user typed. */
v = mbschr (val, '/');
vl = STRLEN (v);
ret = (char *)xmalloc (xl + vl + 2);
strcpy (ret, directory_part);
if (v && *v)
strcpy (ret + xl, v);
free (dh2);
free (expdir);
return ret;
}
free (expdir);
/*
dh2 = unexpanded but dequoted tilde-prefix
dl2 = length of tilde-prefix
expdir = tilde-expanded tilde-prefix
xl = length of expanded tilde-prefix
l = length of remainder after tilde-prefix
*/
l = (vl - xl) + 1;
if (l <= 0)
{
free (dh2);
return (savestring (val)); /* XXX - just punt */
}
ret = (char *)xmalloc (dl2 + 2 + l);
strcpy (ret, dh2);
strcpy (ret + dl2, val + xl);
free (dh2);
return (ret);
}
static char *
maybe_restore_tilde (val, directory_part)
char *val, *directory_part;
{
rl_icppfunc_t *save;
char *ret;
save = (dircomplete_expand == 0) ? save_directory_hook () : (rl_icppfunc_t *)0;
ret = restore_tilde (val, directory_part);
if (save)
restore_directory_hook (save);
return ret;
}
/* Simulate the expansions that will be performed by
rl_filename_completion_function. This must be called with the address of
a pointer to malloc'd memory. */
static void
bash_directory_expansion (dirname)
char **dirname;
{
char *d, *nd;
d = savestring (*dirname);
if ((rl_directory_rewrite_hook) && (*rl_directory_rewrite_hook) (&d))
{
free (*dirname);
*dirname = d;
}
else if (rl_directory_completion_hook && (*rl_directory_completion_hook) (&d))
{
free (*dirname);
*dirname = d;
}
else if (rl_completion_found_quote)
{
nd = bash_dequote_filename (d, rl_completion_quote_character);
free (*dirname);
free (d);
*dirname = nd;
}
}
/* If necessary, rewrite directory entry */
static char *
bash_filename_rewrite_hook (fname, fnlen)
char *fname;
int fnlen;
{
char *conv;
conv = fnx_fromfs (fname, fnlen);
if (conv != fname)
conv = savestring (conv);
return conv;
}
/* Functions to save and restore the appropriate directory hook */
/* This is not static so the shopt code can call it */
void
set_directory_hook ()
{
if (dircomplete_expand)
{
rl_directory_completion_hook = bash_directory_completion_hook;
rl_directory_rewrite_hook = (rl_icppfunc_t *)0;
}
else
{
rl_directory_rewrite_hook = bash_directory_completion_hook;
rl_directory_completion_hook = (rl_icppfunc_t *)0;
}
}
static rl_icppfunc_t *
save_directory_hook ()
{
rl_icppfunc_t *ret;
if (dircomplete_expand)
{
ret = rl_directory_completion_hook;
rl_directory_completion_hook = (rl_icppfunc_t *)NULL;
}
else
{
ret = rl_directory_rewrite_hook;
rl_directory_rewrite_hook = (rl_icppfunc_t *)NULL;
}
return ret;
}
static void
restore_directory_hook (hookf)
rl_icppfunc_t *hookf;
{
if (dircomplete_expand)
rl_directory_completion_hook = hookf;
else
rl_directory_rewrite_hook = hookf;
}
/* Check whether not DIRNAME, with any trailing slash removed, exists. If
SHOULD_DEQUOTE is non-zero, we dequote the directory name first. */
static int
directory_exists (dirname, should_dequote)
const char *dirname;
int should_dequote;
{
char *new_dirname;
int dirlen, r;
struct stat sb;
/* We save the string and chop the trailing slash because stat/lstat behave
inconsistently if one is present. */
new_dirname = should_dequote ? bash_dequote_filename ((char *)dirname, rl_completion_quote_character) : savestring (dirname);
dirlen = STRLEN (new_dirname);
if (new_dirname[dirlen - 1] == '/')
new_dirname[dirlen - 1] = '\0';
#if defined (HAVE_LSTAT)
r = lstat (new_dirname, &sb) == 0;
#else
r = stat (new_dirname, &sb) == 0;
#endif
free (new_dirname);
return (r);
}
/* Expand a filename before the readline completion code passes it to stat(2).
The filename will already have had tilde expansion performed. */
static int
bash_filename_stat_hook (dirname)
char **dirname;
{
char *local_dirname, *new_dirname, *t;
int should_expand_dirname, return_value;
int global_nounset;
WORD_LIST *wl;
local_dirname = *dirname;
should_expand_dirname = return_value = 0;
if (t = mbschr (local_dirname, '$'))
should_expand_dirname = '$';
else if (t = mbschr (local_dirname, '`')) /* XXX */
should_expand_dirname = '`';
if (should_expand_dirname && directory_exists (local_dirname, 0))
should_expand_dirname = 0;
if (should_expand_dirname)
{
new_dirname = savestring (local_dirname);
/* no error messages, and expand_prompt_string doesn't longjmp so we don't
have to worry about restoring this setting. */
global_nounset = unbound_vars_is_error;
unbound_vars_is_error = 0;
wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
unbound_vars_is_error = global_nounset;
if (wl)
{
free (new_dirname);
new_dirname = string_list (wl);
/* Tell the completer we actually expanded something and change
*dirname only if we expanded to something non-null -- stat
behaves unpredictably when passed null or empty strings */
if (new_dirname && *new_dirname)
{
free (local_dirname); /* XXX */
local_dirname = *dirname = new_dirname;
return_value = STREQ (local_dirname, *dirname) == 0;
}
else
free (new_dirname);
dispose_words (wl);
}
else
free (new_dirname);
}
/* This is very similar to the code in bash_directory_completion_hook below,
but without spelling correction and not worrying about whether or not
we change relative pathnames. */
if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
{
char *temp1, *temp2;
t = get_working_directory ("symlink-hook");
temp1 = make_absolute (local_dirname, t);
free (t);
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
/* If we can't canonicalize, bail. */
if (temp2 == 0)
{
free (temp1);
return return_value;
}
free (local_dirname);
*dirname = temp2;
free (temp1);
}
return (return_value);
}
/* Handle symbolic link references and other directory name
expansions while hacking completion. This should return 1 if it modifies
the DIRNAME argument, 0 otherwise. It should make sure not to modify
DIRNAME if it returns 0. */
static int
bash_directory_completion_hook (dirname)
char **dirname;
{
char *local_dirname, *new_dirname, *t;
int return_value, should_expand_dirname, nextch, closer;
WORD_LIST *wl;
return_value = should_expand_dirname = nextch = closer = 0;
local_dirname = *dirname;
if (t = mbschr (local_dirname, '$'))
{
should_expand_dirname = '$';
nextch = t[1];
/* Deliberately does not handle the deprecated $[...] arithmetic
expansion syntax */
if (nextch == '(')
closer = ')';
else if (nextch == '{')
closer = '}';
else
nextch = 0;
if (closer)
{
int p;
char delims[2];
delims[0] = closer; delims[1] = 0;
p = skip_to_delim (t, 1, delims, SD_NOJMP|SD_COMPLETE);
if (t[p] != closer)
should_expand_dirname = 0;
}
}
else if (local_dirname[0] == '~')
should_expand_dirname = '~';
else
{
t = mbschr (local_dirname, '`');
if (t && unclosed_pair (local_dirname, strlen (local_dirname), "`") == 0)
should_expand_dirname = '`';
}
if (should_expand_dirname && directory_exists (local_dirname, 1))
should_expand_dirname = 0;
if (should_expand_dirname)
{
new_dirname = savestring (local_dirname);
wl = expand_prompt_string (new_dirname, 0, W_NOCOMSUB|W_NOPROCSUB|W_COMPLETE); /* does the right thing */
if (wl)
{
*dirname = string_list (wl);
/* Tell the completer to replace the directory name only if we
actually expanded something. */
return_value = STREQ (local_dirname, *dirname) == 0;
free (local_dirname);
free (new_dirname);
dispose_words (wl);
local_dirname = *dirname;
/* XXX - change rl_filename_quote_characters here based on
should_expand_dirname/nextch/closer. This is the only place
custom_filename_quote_characters is modified. */
if (rl_filename_quote_characters && *rl_filename_quote_characters)
{
int i, j, c;
i = strlen (default_filename_quote_characters);
custom_filename_quote_characters = xrealloc (custom_filename_quote_characters, i+1);
for (i = j = 0; c = default_filename_quote_characters[i]; i++)
{
if (c == should_expand_dirname || c == nextch || c == closer)
continue;
custom_filename_quote_characters[j++] = c;
}
custom_filename_quote_characters[j] = '\0';
rl_filename_quote_characters = custom_filename_quote_characters;
set_filename_bstab (rl_filename_quote_characters);
}
}
else
{
free (new_dirname);
free (local_dirname);
*dirname = (char *)xmalloc (1);
**dirname = '\0';
return 1;
}
}
else
{
/* Dequote the filename even if we don't expand it. */
new_dirname = bash_dequote_filename (local_dirname, rl_completion_quote_character);
return_value = STREQ (local_dirname, new_dirname) == 0;
free (local_dirname);
local_dirname = *dirname = new_dirname;
}
/* no_symbolic_links == 0 -> use (default) logical view of the file system.
local_dirname[0] == '.' && local_dirname[1] == '/' means files in the
current directory (./).
local_dirname[0] == '.' && local_dirname[1] == 0 means relative pathnames
in the current directory (e.g., lib/sh).
XXX - should we do spelling correction on these? */
/* This is test as it was in bash-4.2: skip relative pathnames in current
directory. Change test to
(local_dirname[0] != '.' || (local_dirname[1] && local_dirname[1] != '/'))
if we want to skip paths beginning with ./ also. */
if (no_symbolic_links == 0 && (local_dirname[0] != '.' || local_dirname[1]))
{
char *temp1, *temp2;
int len1, len2;
/* If we have a relative path
(local_dirname[0] != '/' && local_dirname[0] != '.')
that is canonical after appending it to the current directory, then
temp1 = temp2+'/'
That is,
strcmp (temp1, temp2) == 0
after adding a slash to temp2 below. It should be safe to not
change those.
*/
t = get_working_directory ("symlink-hook");
temp1 = make_absolute (local_dirname, t);
free (t);
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
/* Try spelling correction if initial canonicalization fails. Make
sure we are set to replace the directory name with the results so
subsequent directory checks don't fail. */
if (temp2 == 0 && dircomplete_spelling && dircomplete_expand)
{
temp2 = dirspell (temp1);
if (temp2)
{
free (temp1);
temp1 = temp2;
temp2 = sh_canonpath (temp1, PATH_CHECKDOTDOT|PATH_CHECKEXISTS);
return_value |= temp2 != 0;
}
}
/* If we can't canonicalize, bail. */
if (temp2 == 0)
{
free (temp1);
return return_value;
}
len1 = strlen (temp1);
if (temp1[len1 - 1] == '/')
{
len2 = strlen (temp2);
if (len2 > 2) /* don't append `/' to `/' or `//' */
{
temp2 = (char *)xrealloc (temp2, len2 + 2);
temp2[len2] = '/';
temp2[len2 + 1] = '\0';
}
}
/* dircomplete_expand_relpath == 0 means we want to leave relative
pathnames that are unchanged by canonicalization alone.
*local_dirname != '/' && *local_dirname != '.' == relative pathname
(consistent with general.c:absolute_pathname())
temp1 == temp2 (after appending a slash to temp2) means the pathname
is not changed by canonicalization as described above. */
if (dircomplete_expand_relpath || ((local_dirname[0] != '/' && local_dirname[0] != '.') && STREQ (temp1, temp2) == 0))
return_value |= STREQ (local_dirname, temp2) == 0;
free (local_dirname);
*dirname = temp2;
free (temp1);
}
return (return_value);
}
static char **history_completion_array = (char **)NULL;
static int harry_size;
static int harry_len;
static void
build_history_completion_array ()
{
register int i, j;
HIST_ENTRY **hlist;
char **tokens;
/* First, clear out the current dynamic history completion list. */
if (harry_size)
{
strvec_dispose (history_completion_array);
history_completion_array = (char **)NULL;
harry_size = 0;
harry_len = 0;
}
/* Next, grovel each line of history, making each shell-sized token
a separate entry in the history_completion_array. */
hlist = history_list ();
if (hlist)
{
for (i = 0; hlist[i]; i++)
;
for ( --i; i >= 0; i--)
{
/* Separate each token, and place into an array. */
tokens = history_tokenize (hlist[i]->line);
for (j = 0; tokens && tokens[j]; j++)
{
if (harry_len + 2 > harry_size)
history_completion_array = strvec_resize (history_completion_array, harry_size += 10);
history_completion_array[harry_len++] = tokens[j];
history_completion_array[harry_len] = (char *)NULL;
}
free (tokens);
}
/* Sort the complete list of tokens. */
if (dabbrev_expand_active == 0)
qsort (history_completion_array, harry_len, sizeof (char *), (QSFUNC *)strvec_strcmp);
}
}
static char *
history_completion_generator (hint_text, state)
const char *hint_text;
int state;
{
static int local_index, len;
static const char *text;
/* If this is the first call to the generator, then initialize the
list of strings to complete over. */
if (state == 0)
{
if (dabbrev_expand_active) /* This is kind of messy */
rl_completion_suppress_append = 1;
local_index = 0;
build_history_completion_array ();
text = hint_text;
len = strlen (text);
}
while (history_completion_array && history_completion_array[local_index])
{
/* XXX - should this use completion-ignore-case? */
if (strncmp (text, history_completion_array[local_index++], len) == 0)
return (savestring (history_completion_array[local_index - 1]));
}
return ((char *)NULL);
}
static int
dynamic_complete_history (count, key)
int count, key;
{
int r;
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
rl_completion_entry_function = history_completion_generator;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
/* XXX - use rl_completion_mode here? */
if (rl_last_func == dynamic_complete_history)
r = rl_complete_internal ('?');
else
r = rl_complete_internal (TAB);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
return r;
}
static int
bash_dabbrev_expand (count, key)
int count, key;
{
int r, orig_suppress, orig_sort;
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
orig_func = rl_menu_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
orig_suppress = rl_completion_suppress_append;
orig_sort = rl_sort_completion_matches;
rl_menu_completion_entry_function = history_completion_generator;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_filename_completion_desired = 0;
rl_completion_suppress_append = 1;
rl_sort_completion_matches = 0;
/* XXX - use rl_completion_mode here? */
dabbrev_expand_active = 1;
if (rl_last_func == bash_dabbrev_expand)
rl_last_func = rl_menu_complete;
r = rl_menu_complete (count, key);
dabbrev_expand_active = 0;
rl_last_func = bash_dabbrev_expand;
rl_menu_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
rl_completion_suppress_append = orig_suppress;
rl_sort_completion_matches = orig_sort;
return r;
}
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
static int
bash_complete_username (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_username_internal (rl_completion_mode (bash_complete_username));
}
static int
bash_possible_username_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_username_internal ('?');
}
static int
bash_complete_username_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, rl_username_completion_function);
}
static int
bash_complete_filename (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_filename_internal (rl_completion_mode (bash_complete_filename));
}
static int
bash_possible_filename_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_filename_internal ('?');
}
static int
bash_complete_filename_internal (what_to_do)
int what_to_do;
{
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_icppfunc_t *orig_dir_func;
rl_compignore_func_t *orig_ignore_func;
/*const*/ char *orig_rl_completer_word_break_characters;
int r;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
orig_rl_completer_word_break_characters = rl_completer_word_break_characters;
orig_dir_func = save_directory_hook ();
rl_completion_entry_function = rl_filename_completion_function;
rl_attempted_completion_function = (rl_completion_func_t *)NULL;
rl_ignore_some_completions_function = filename_completion_ignore;
rl_completer_word_break_characters = " \t\n\"\'";
r = rl_complete_internal (what_to_do);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
rl_completer_word_break_characters = orig_rl_completer_word_break_characters;
restore_directory_hook (orig_dir_func);
return r;
}
static int
bash_complete_hostname (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_hostname_internal (rl_completion_mode (bash_complete_hostname));
}
static int
bash_possible_hostname_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_hostname_internal ('?');
}
static int
bash_complete_variable (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_variable_internal (rl_completion_mode (bash_complete_variable));
}
static int
bash_possible_variable_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_variable_internal ('?');
}
static int
bash_complete_command (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_command_internal (rl_completion_mode (bash_complete_command));
}
static int
bash_possible_command_completions (ignore, ignore2)
int ignore, ignore2;
{
return bash_complete_command_internal ('?');
}
static int
bash_complete_hostname_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, hostname_completion_function);
}
static int
bash_complete_variable_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, variable_completion_function);
}
static int
bash_complete_command_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, command_word_completion_function);
}
static int
completion_glob_pattern (string)
char *string;
{
register int c;
char *send;
int open;
DECLARE_MBSTATE;
open = 0;
send = string + strlen (string);
while (c = *string++)
{
switch (c)
{
case '?':
case '*':
return (1);
case '[':
open++;
continue;
case ']':
if (open)
return (1);
continue;
case '+':
case '@':
case '!':
if (*string == '(') /*)*/
return (1);
continue;
case '\\':
if (*string++ == 0)
return (0);
}
/* Advance one fewer byte than an entire multibyte character to
account for the auto-increment in the loop above. */
#ifdef HANDLE_MULTIBYTE
string--;
ADVANCE_CHAR_P (string, send - string);
string++;
#else
ADVANCE_CHAR_P (string, send - string);
#endif
}
return (0);
}
static char *globtext;
static char *globorig;
static char *
glob_complete_word (text, state)
const char *text;
int state;
{
static char **matches = (char **)NULL;
static int ind;
int glen;
char *ret, *ttext;
if (state == 0)
{
rl_filename_completion_desired = 1;
FREE (matches);
if (globorig != globtext)
FREE (globorig);
FREE (globtext);
ttext = bash_tilde_expand (text, 0);
if (rl_explicit_arg)
{
globorig = savestring (ttext);
glen = strlen (ttext);
globtext = (char *)xmalloc (glen + 2);
strcpy (globtext, ttext);
globtext[glen] = '*';
globtext[glen+1] = '\0';
}
else
globtext = globorig = savestring (ttext);
if (ttext != text)
free (ttext);
matches = shell_glob_filename (globtext);
if (GLOB_FAILED (matches))
matches = (char **)NULL;
ind = 0;
}
ret = matches ? matches[ind] : (char *)NULL;
ind++;
return ret;
}
static int
bash_glob_completion_internal (what_to_do)
int what_to_do;
{
return bash_specific_completion (what_to_do, glob_complete_word);
}
/* A special quoting function so we don't end up quoting globbing characters
in the word if there are no matches or multiple matches. */
static char *
bash_glob_quote_filename (s, rtype, qcp)
char *s;
int rtype;
char *qcp;
{
if (globorig && qcp && *qcp == '\0' && STREQ (s, globorig))
return (savestring (s));
else
return (bash_quote_filename (s, rtype, qcp));
}
static int
bash_glob_complete_word (count, key)
int count, key;
{
int r;
rl_quote_func_t *orig_quoting_function;
if (rl_editing_mode == EMACS_EDITING_MODE)
rl_explicit_arg = 1; /* force `*' append */
orig_quoting_function = rl_filename_quoting_function;
rl_filename_quoting_function = bash_glob_quote_filename;
r = bash_glob_completion_internal (rl_completion_mode (bash_glob_complete_word));
rl_filename_quoting_function = orig_quoting_function;
return r;
}
static int
bash_glob_expand_word (count, key)
int count, key;
{
return bash_glob_completion_internal ('*');
}
static int
bash_glob_list_expansions (count, key)
int count, key;
{
return bash_glob_completion_internal ('?');
}
static int
bash_specific_completion (what_to_do, generator)
int what_to_do;
rl_compentry_func_t *generator;
{
rl_compentry_func_t *orig_func;
rl_completion_func_t *orig_attempt_func;
rl_compignore_func_t *orig_ignore_func;
int r;
orig_func = rl_completion_entry_function;
orig_attempt_func = rl_attempted_completion_function;
orig_ignore_func = rl_ignore_some_completions_function;
rl_completion_entry_function = generator;
rl_attempted_completion_function = NULL;
rl_ignore_some_completions_function = orig_ignore_func;
r = rl_complete_internal (what_to_do);
rl_completion_entry_function = orig_func;
rl_attempted_completion_function = orig_attempt_func;
rl_ignore_some_completions_function = orig_ignore_func;
return r;
}
#endif /* SPECIFIC_COMPLETION_FUNCTIONS */
#if defined (VI_MODE)
/* Completion, from vi mode's point of view. This is a modified version of
rl_vi_complete which uses the bash globbing code to implement what POSIX
specifies, which is to append a `*' and attempt filename generation (which
has the side effect of expanding any globbing characters in the word). */
static int
bash_vi_complete (count, key)
int count, key;
{
#if defined (SPECIFIC_COMPLETION_FUNCTIONS)
int p, r;
char *t;
if ((rl_point < rl_end) && (!whitespace (rl_line_buffer[rl_point])))
{
if (!whitespace (rl_line_buffer[rl_point + 1]))
rl_vi_end_word (1, 'E');
rl_point++;
}
/* Find boundaries of current word, according to vi definition of a
`bigword'. */
t = 0;
if (rl_point > 0)
{
p = rl_point;
rl_vi_bWord (1, 'B');
r = rl_point;
rl_point = p;
p = r;
t = substring (rl_line_buffer, p, rl_point);
}
if (t && completion_glob_pattern (t) == 0)
rl_explicit_arg = 1; /* XXX - force glob_complete_word to append `*' */
FREE (t);
if (key == '*') /* Expansion and replacement. */
r = bash_glob_expand_word (count, key);
else if (key == '=') /* List possible completions. */
r = bash_glob_list_expansions (count, key);
else if (key == '\\') /* Standard completion */
r = bash_glob_complete_word (count, key);
else
r = rl_complete (0, key);
if (key == '*' || key == '\\')
rl_vi_start_inserting (key, 1, 1);
return (r);
#else
return rl_vi_complete (count, key);
#endif /* !SPECIFIC_COMPLETION_FUNCTIONS */
}
#endif /* VI_MODE */
/* Filename quoting for completion. */
/* A function to strip unquoted quote characters (single quotes, double
quotes, and backslashes). It allows single quotes to appear
within double quotes, and vice versa. It should be smarter. */
static char *
bash_dequote_filename (text, quote_char)
char *text;
int quote_char;
{
char *ret, *p, *r;
int l, quoted;
l = strlen (text);
ret = (char *)xmalloc (l + 1);
for (quoted = quote_char, p = text, r = ret; p && *p; p++)
{
/* Allow backslash-escaped characters to pass through unscathed. */
if (*p == '\\')
{
/* Backslashes are preserved within single quotes. */
if (quoted == '\'')
*r++ = *p;
/* Backslashes are preserved within double quotes unless the
character is one that is defined to be escaped */
else if (quoted == '"' && ((sh_syntaxtab[(unsigned char)p[1]] & CBSDQUOTE) == 0))
*r++ = *p;
*r++ = *++p;
if (*p == '\0')
return ret; /* XXX - was break; */
continue;
}
/* Close quote. */
if (quoted && *p == quoted)
{
quoted = 0;
continue;
}
/* Open quote. */
if (quoted == 0 && (*p == '\'' || *p == '"'))
{
quoted = *p;
continue;
}
*r++ = *p;
}
*r = '\0';
return ret;
}
/* Quote characters that the readline completion code would treat as
word break characters with backslashes. Pass backslash-quoted
characters through without examination. */
static char *
quote_word_break_chars (text)
char *text;
{
char *ret, *r, *s;
int l;
l = strlen (text);
ret = (char *)xmalloc ((2 * l) + 1);
for (s = text, r = ret; *s; s++)
{
/* Pass backslash-quoted characters through, including the backslash. */
if (*s == '\\')
{
*r++ = '\\';
*r++ = *++s;
if (*s == '\0')
break;
continue;
}
/* OK, we have an unquoted character. Check its presence in
rl_completer_word_break_characters. */
if (mbschr (rl_completer_word_break_characters, *s))
*r++ = '\\';
/* XXX -- check for standalone tildes here and backslash-quote them */
if (s == text && *s == '~' && file_exists (text))
*r++ = '\\';
*r++ = *s;
}
*r = '\0';
return ret;
}
/* Use characters in STRING to populate the table of characters that should
be backslash-quoted. The table will be used for sh_backslash_quote from
this file. */
static void
set_filename_bstab (string)
const char *string;
{
const char *s;
memset (filename_bstab, 0, sizeof (filename_bstab));
for (s = string; s && *s; s++)
filename_bstab[*s] = 1;
}
/* Quote a filename using double quotes, single quotes, or backslashes
depending on the value of completion_quoting_style. If we're
completing using backslashes, we need to quote some additional
characters (those that readline treats as word breaks), so we call
quote_word_break_chars on the result. This returns newly-allocated
memory. */
static char *
bash_quote_filename (s, rtype, qcp)
char *s;
int rtype;
char *qcp;
{
char *rtext, *mtext, *ret;
int rlen, cs;
rtext = (char *)NULL;
/* If RTYPE == MULT_MATCH, it means that there is
more than one match. In this case, we do not add
the closing quote or attempt to perform tilde
expansion. If RTYPE == SINGLE_MATCH, we try
to perform tilde expansion, because single and double
quotes inhibit tilde expansion by the shell. */
cs = completion_quoting_style;
/* Might need to modify the default completion style based on *qcp,
since it's set to any user-provided opening quote. We also change
to single-quoting if there is no user-provided opening quote and
the word being completed contains newlines, since those are not
quoted correctly using backslashes (a backslash-newline pair is
special to the shell parser). */
if (*qcp == '\0' && cs == COMPLETE_BSQUOTE && mbschr (s, '\n'))
cs = COMPLETE_SQUOTE;
else if (*qcp == '"')
cs = COMPLETE_DQUOTE;
else if (*qcp == '\'')
cs = COMPLETE_SQUOTE;
#if defined (BANG_HISTORY)
else if (*qcp == '\0' && history_expansion && cs == COMPLETE_DQUOTE &&
history_expansion_inhibited == 0 && mbschr (s, '!'))
cs = COMPLETE_BSQUOTE;
if (*qcp == '"' && history_expansion && cs == COMPLETE_DQUOTE &&
history_expansion_inhibited == 0 && mbschr (s, '!'))
{
cs = COMPLETE_BSQUOTE;
*qcp = '\0';
}
#endif
/* Don't tilde-expand backslash-quoted filenames, since only single and
double quotes inhibit tilde expansion. */
mtext = s;
if (mtext[0] == '~' && rtype == SINGLE_MATCH && cs != COMPLETE_BSQUOTE)
mtext = bash_tilde_expand (s, 0);
switch (cs)
{
case COMPLETE_DQUOTE:
rtext = sh_double_quote (mtext);
break;
case COMPLETE_SQUOTE:
rtext = sh_single_quote (mtext);
break;
case COMPLETE_BSQUOTE:
rtext = sh_backslash_quote (mtext, complete_fullquote ? 0 : filename_bstab, 0);
break;
}
if (mtext != s)
free (mtext);
/* We may need to quote additional characters: those that readline treats
as word breaks that are not quoted by backslash_quote. */
if (rtext && cs == COMPLETE_BSQUOTE)
{
mtext = quote_word_break_chars (rtext);
free (rtext);
rtext = mtext;
}
/* Leave the opening quote intact. The readline completion code takes
care of avoiding doubled opening quotes. */
if (rtext)
{
rlen = strlen (rtext);
ret = (char *)xmalloc (rlen + 1);
strcpy (ret, rtext);
}
else
{
ret = (char *)xmalloc (rlen = 1);
ret[0] = '\0';
}
/* If there are multiple matches, cut off the closing quote. */
if (rtype == MULT_MATCH && cs != COMPLETE_BSQUOTE)
ret[rlen - 1] = '\0';
free (rtext);
return ret;
}
/* Support for binding readline key sequences to Unix commands. Each editing
mode has a separate Unix command keymap. */
static Keymap emacs_std_cmd_xmap;
#if defined (VI_MODE)
static Keymap vi_insert_cmd_xmap;
static Keymap vi_movement_cmd_xmap;
#endif
#ifdef _MINIX
static void
#else
static int
#endif
putx(c)
int c;
{
int x;
x = putc (c, rl_outstream);
#ifndef _MINIX
return x;
#endif
}
static int
bash_execute_unix_command (count, key)
int count; /* ignored */
int key;
{
int type;
register int i, r;
intmax_t mi;
sh_parser_state_t ps;
char *cmd, *value, *ce, old_ch;
SHELL_VAR *v;
char ibuf[INT_STRLEN_BOUND(int) + 1];
Keymap cmd_xmap;
/* First, we need to find the right command to execute. This is tricky,
because we might have already indirected into another keymap, so we
have to walk cmd_xmap using the entire key sequence. */
cmd_xmap = get_cmd_xmap_from_keymap (rl_get_keymap ());
cmd = (char *)rl_function_of_keyseq_len (rl_executing_keyseq, rl_key_sequence_length, cmd_xmap, &type);
if (cmd == 0 || type != ISMACR)
{
rl_crlf ();
internal_error (_("bash_execute_unix_command: cannot find keymap for command"));
rl_forced_update_display ();
return 1;
}
ce = rl_get_termcap ("ce");
if (ce) /* clear current line */
{
#if 0
fprintf (rl_outstream, "\r");
tputs (ce, 1, putx);
#else
rl_clear_visible_line ();
#endif
fflush (rl_outstream);
}
else
rl_crlf (); /* move to a new line */
v = bind_variable ("READLINE_LINE", rl_line_buffer, 0);
if (v)
VSETATTR (v, att_exported);
i = rl_point;
#if defined (HANDLE_MULTIBYTE)
if (MB_CUR_MAX > 1)
{
old_ch = rl_line_buffer[rl_point];
rl_line_buffer[rl_point] = '\0';
i = MB_STRLEN (rl_line_buffer);
rl_line_buffer[rl_point] = old_ch;
}
#endif
value = inttostr (i, ibuf, sizeof (ibuf));
v = bind_int_variable ("READLINE_POINT", value, 0);
if (v)
VSETATTR (v, att_exported);
array_needs_making = 1;
save_parser_state (&ps);
r = parse_and_execute (savestring (cmd), "bash_execute_unix_command", SEVAL_NOHIST|SEVAL_NOFREE);
restore_parser_state (&ps);
v = find_variable ("READLINE_LINE");
maybe_make_readline_line (v ? value_cell (v) : 0);
v = find_variable ("READLINE_POINT");
if (v && legal_number (value_cell (v), &mi))
{
i = mi;
#if defined (HANDLE_MULTIBYTE)
if (i > 0 && MB_CUR_MAX > 1)
i = _rl_find_next_mbchar (rl_line_buffer, 0, i, 0);
#endif
if (i != rl_point)
{
rl_point = i;
if (rl_point > rl_end)
rl_point = rl_end;
else if (rl_point < 0)
rl_point = 0;
}
}
check_unbind_variable ("READLINE_LINE");
check_unbind_variable ("READLINE_POINT");
array_needs_making = 1;
/* and restore the readline buffer and display after command execution. */
/* If we clear the last line of the prompt above, redraw only that last
line. If the command returns 124, we redraw unconditionally as in
previous versions. */
if (ce && r != 124)
rl_redraw_prompt_last_line ();
else
rl_forced_update_display ();
return 0;
}
int
print_unix_command_map ()
{
Keymap save, cmd_xmap;
save = rl_get_keymap ();
cmd_xmap = get_cmd_xmap_from_keymap (save);
rl_set_keymap (cmd_xmap);
rl_macro_dumper (1);
rl_set_keymap (save);
return 0;
}
static void
init_unix_command_map ()
{
emacs_std_cmd_xmap = rl_make_bare_keymap ();
emacs_std_cmd_xmap[CTRL('X')].type = ISKMAP;
emacs_std_cmd_xmap[CTRL('X')].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
emacs_std_cmd_xmap[ESC].type = ISKMAP;
emacs_std_cmd_xmap[ESC].function = KEYMAP_TO_FUNCTION (rl_make_bare_keymap ());
#if defined (VI_MODE)
vi_insert_cmd_xmap = rl_make_bare_keymap ();
vi_movement_cmd_xmap = rl_make_bare_keymap ();
#endif
}
static Keymap
get_cmd_xmap_from_edit_mode ()
{
if (emacs_std_cmd_xmap == 0)
init_unix_command_map ();
switch (rl_editing_mode)
{
case EMACS_EDITING_MODE:
return emacs_std_cmd_xmap;
#if defined (VI_MODE)
case VI_EDITING_MODE:
return (get_cmd_xmap_from_keymap (rl_get_keymap ()));
#endif
default:
return (Keymap)NULL;
}
}
static Keymap
get_cmd_xmap_from_keymap (kmap)
Keymap kmap;
{
if (emacs_std_cmd_xmap == 0)
init_unix_command_map ();
if (kmap == emacs_standard_keymap)
return emacs_std_cmd_xmap;
else if (kmap == emacs_meta_keymap)
return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, ESC));
else if (kmap == emacs_ctlx_keymap)
return (FUNCTION_TO_KEYMAP (emacs_std_cmd_xmap, CTRL('X')));
#if defined (VI_MODE)
else if (kmap == vi_insertion_keymap)
return vi_insert_cmd_xmap;
else if (kmap == vi_movement_keymap)
return vi_movement_cmd_xmap;
#endif
else
return (Keymap)NULL;
}
static int
isolate_sequence (string, ind, need_dquote, startp)
char *string;
int ind, need_dquote, *startp;
{
register int i;
int c, passc, delim;
for (i = ind; string[i] && whitespace (string[i]); i++)
;
/* NEED_DQUOTE means that the first non-white character *must* be `"'. */
if (need_dquote && string[i] != '"')
{
builtin_error (_("%s: first non-whitespace character is not `\"'"), string);
return -1;
}
/* We can have delimited strings even if NEED_DQUOTE == 0, like the command
string to bind the key sequence to. */
delim = (string[i] == '"' || string[i] == '\'') ? string[i] : 0;
if (startp)
*startp = delim ? ++i : i;
for (passc = 0; c = string[i]; i++)
{
if (passc)
{
passc = 0;
continue;
}
if (c == '\\')
{
passc++;
continue;
}
if (c == delim)
break;
}
if (delim && string[i] != delim)
{
builtin_error (_("no closing `%c' in %s"), delim, string);
return -1;
}
return i;
}
int
bind_keyseq_to_unix_command (line)
char *line;
{
Keymap kmap, cmd_xmap;
char *kseq, *value;
int i, kstart;
kmap = rl_get_keymap ();
/* We duplicate some of the work done by rl_parse_and_bind here, but
this code only has to handle `"keyseq": ["]command["]' and can
generate an error for anything else. */
i = isolate_sequence (line, 0, 1, &kstart);
if (i < 0)
return -1;
/* Create the key sequence string to pass to rl_generic_bind */
kseq = substring (line, kstart, i);
for ( ; line[i] && line[i] != ':'; i++)
;
if (line[i] != ':')
{
builtin_error (_("%s: missing colon separator"), line);
FREE (kseq);
return -1;
}
i = isolate_sequence (line, i + 1, 0, &kstart);
if (i < 0)
{
FREE (kseq);
return -1;
}
/* Create the value string containing the command to execute. */
value = substring (line, kstart, i);
/* Save the command to execute and the key sequence in the CMD_XMAP */
cmd_xmap = get_cmd_xmap_from_keymap (kmap);
rl_generic_bind (ISMACR, kseq, value, cmd_xmap);
/* and bind the key sequence in the current keymap to a function that
understands how to execute from CMD_XMAP */
rl_bind_keyseq_in_map (kseq, bash_execute_unix_command, kmap);
free (kseq);
return 0;
}
/* Used by the programmable completion code. Complete TEXT as a filename,
but return only directories as matches. Dequotes the filename before
attempting to find matches. */
char **
bash_directory_completion_matches (text)
const char *text;
{
char **m1;
char *dfn;
int qc;
qc = rl_dispatching ? rl_completion_quote_character : 0;
/* If rl_completion_found_quote != 0, rl_completion_matches will call the
filename dequoting function, causing the directory name to be dequoted
twice. */
if (rl_dispatching && rl_completion_found_quote == 0)
dfn = bash_dequote_filename ((char *)text, qc);
else
dfn = (char *)text;
m1 = rl_completion_matches (dfn, rl_filename_completion_function);
if (dfn != text)
free (dfn);
if (m1 == 0 || m1[0] == 0)
return m1;
/* We don't bother recomputing the lcd of the matches, because it will just
get thrown away by the programmable completion code and recomputed
later. */
(void)bash_progcomp_ignore_filenames (m1);
return m1;
}
char *
bash_dequote_text (text)
const char *text;
{
char *dtxt;
int qc;
qc = (text[0] == '"' || text[0] == '\'') ? text[0] : 0;
dtxt = bash_dequote_filename ((char *)text, qc);
return (dtxt);
}
/* This event hook is designed to be called after readline receives a signal
that interrupts read(2). It gives reasonable responsiveness to interrupts
and fatal signals without executing too much code in a signal handler
context. */
static int
bash_event_hook ()
{
/* If we're going to longjmp to top_level, make sure we clean up readline.
check_signals will call QUIT, which will eventually longjmp to top_level,
calling run_interrupt_trap along the way. The check for sigalrm_seen is
to clean up the read builtin's state. */
if (terminating_signal || interrupt_state || sigalrm_seen)
rl_cleanup_after_signal ();
bashline_reset_event_hook ();
check_signals_and_traps (); /* XXX */
return 0;
}
#endif /* READLINE */
| ./CrossVul/dataset_final_sorted/CWE-273/c/bad_1198_2 |
crossvul-cpp_data_good_3963_0 | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2015, Atmel 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:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "common.h"
#include "secure.h"
#include "aes.h"
#include "debug.h"
#include "string.h"
#include "autoconf.h"
static unsigned int cipher_key[8] = {
CONFIG_AES_CIPHER_KEY_WORD0,
CONFIG_AES_CIPHER_KEY_WORD1,
CONFIG_AES_CIPHER_KEY_WORD2,
CONFIG_AES_CIPHER_KEY_WORD3,
#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)
CONFIG_AES_CIPHER_KEY_WORD4,
CONFIG_AES_CIPHER_KEY_WORD5,
#endif
#if defined(CONFIG_AES_KEY_SIZE_256)
CONFIG_AES_CIPHER_KEY_WORD6,
CONFIG_AES_CIPHER_KEY_WORD7,
#endif
};
static unsigned int cmac_key[8] = {
CONFIG_AES_CMAC_KEY_WORD0,
CONFIG_AES_CMAC_KEY_WORD1,
CONFIG_AES_CMAC_KEY_WORD2,
CONFIG_AES_CMAC_KEY_WORD3,
#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)
CONFIG_AES_CMAC_KEY_WORD4,
CONFIG_AES_CMAC_KEY_WORD5,
#endif
#if defined(CONFIG_AES_KEY_SIZE_256)
CONFIG_AES_CMAC_KEY_WORD6,
CONFIG_AES_CMAC_KEY_WORD7,
#endif
};
static unsigned int iv[AT91_AES_IV_SIZE_WORD] = {
CONFIG_AES_IV_WORD0,
CONFIG_AES_IV_WORD1,
CONFIG_AES_IV_WORD2,
CONFIG_AES_IV_WORD3,
};
static int secure_decrypt(void *data, unsigned int data_length, int is_signed)
{
at91_aes_key_size_t key_size;
unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];
unsigned int fixed_length;
const unsigned int *cmac;
int rc = -1;
#if defined(CONFIG_AES_KEY_SIZE_128)
key_size = AT91_AES_KEY_SIZE_128;
#elif defined(CONFIG_AES_KEY_SIZE_192)
key_size = AT91_AES_KEY_SIZE_192;
#elif defined(CONFIG_AES_KEY_SIZE_256)
key_size = AT91_AES_KEY_SIZE_256;
#else
#error "bad AES key size"
#endif
/* Init periph */
at91_aes_init();
/* Check signature if required */
if (is_signed) {
/* Compute the CMAC */
if (at91_aes_cmac(data_length, data, computed_cmac,
key_size, cmac_key))
goto exit;
/* Check the CMAC */
fixed_length = at91_aes_roundup(data_length);
cmac = (const unsigned int *)((char *)data + fixed_length);
if (!consttime_memequal(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))
goto exit;
}
/* Decrypt the whole file */
if (at91_aes_cbc(data_length, data, data, 0,
key_size, cipher_key, iv))
goto exit;
rc = 0;
exit:
/* Reset periph */
at91_aes_cleanup();
return rc;
}
static void wipe_keys()
{
/* Reset keys */
memset(cmac_key, 0, sizeof(cmac_key));
memset(cipher_key, 0, sizeof(cipher_key));
memset(iv, 0, sizeof(iv));
}
int secure_check(void *data)
{
const at91_secure_header_t *header;
void *file;
int ret = -1;
if (secure_decrypt(data, sizeof(*header), 0))
goto secure_wipe_keys;
header = (const at91_secure_header_t *)data;
if (header->magic != AT91_SECURE_MAGIC)
goto secure_wipe_keys;
file = (unsigned char *)data + sizeof(*header);
ret = secure_decrypt(file, header->file_size, 1);
secure_wipe_keys:
wipe_keys();
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-326/c/good_3963_0 |
crossvul-cpp_data_good_3970_0 | /* ecc.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* in case user set HAVE_ECC there */
#include <wolfssl/wolfcrypt/settings.h>
/* public ASN interface */
#include <wolfssl/wolfcrypt/asn_public.h>
/*
Possible ECC enable options:
* HAVE_ECC: Overall control of ECC default: on
* HAVE_ECC_ENCRYPT: ECC encrypt/decrypt w/AES and HKDF default: off
* HAVE_ECC_SIGN: ECC sign default: on
* HAVE_ECC_VERIFY: ECC verify default: on
* HAVE_ECC_DHE: ECC build shared secret default: on
* HAVE_ECC_CDH: ECC cofactor DH shared secret default: off
* HAVE_ECC_KEY_IMPORT: ECC Key import default: on
* HAVE_ECC_KEY_EXPORT: ECC Key export default: on
* ECC_SHAMIR: Enables Shamir calc method default: on
* HAVE_COMP_KEY: Enables compressed key default: off
* WOLFSSL_VALIDATE_ECC_IMPORT: Validate ECC key on import default: off
* WOLFSSL_VALIDATE_ECC_KEYGEN: Validate ECC key gen default: off
* WOLFSSL_CUSTOM_CURVES: Allow non-standard curves. default: off
* Includes the curve "a" variable in calculation
* ECC_DUMP_OID: Enables dump of OID encoding and sum default: off
* ECC_CACHE_CURVE: Enables cache of curve info to improve perofrmance
default: off
* FP_ECC: ECC Fixed Point Cache default: off
* USE_ECC_B_PARAM: Enable ECC curve B param default: off
(on for HAVE_COMP_KEY)
* WOLFSSL_ECC_CURVE_STATIC: default off (on for windows)
For the ECC curve paramaters `ecc_set_type` use fixed
array for hex string
*/
/*
ECC Curve Types:
* NO_ECC_SECP Disables SECP curves default: off (not defined)
* HAVE_ECC_SECPR2 Enables SECP R2 curves default: off
* HAVE_ECC_SECPR3 Enables SECP R3 curves default: off
* HAVE_ECC_BRAINPOOL Enables Brainpool curves default: off
* HAVE_ECC_KOBLITZ Enables Koblitz curves default: off
*/
/*
ECC Curve Sizes:
* ECC_USER_CURVES: Allows custom combination of key sizes below
* HAVE_ALL_CURVES: Enable all key sizes (on unless ECC_USER_CURVES is defined)
* HAVE_ECC112: 112 bit key
* HAVE_ECC128: 128 bit key
* HAVE_ECC160: 160 bit key
* HAVE_ECC192: 192 bit key
* HAVE_ECC224: 224 bit key
* HAVE_ECC239: 239 bit key
* NO_ECC256: Disables 256 bit key (on by default)
* HAVE_ECC320: 320 bit key
* HAVE_ECC384: 384 bit key
* HAVE_ECC512: 512 bit key
* HAVE_ECC521: 521 bit key
*/
#ifdef HAVE_ECC
/* Make sure custom curves is enabled for Brainpool or Koblitz curve types */
#if (defined(HAVE_ECC_BRAINPOOL) || defined(HAVE_ECC_KOBLITZ)) &&\
!defined(WOLFSSL_CUSTOM_CURVES)
#error Brainpool and Koblitz curves requires WOLFSSL_CUSTOM_CURVES
#endif
#if defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
/* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
#define FIPS_NO_WRAPPERS
#ifdef USE_WINDOWS_API
#pragma code_seg(".fipsA$f")
#pragma const_seg(".fipsB$f")
#endif
#endif
#include <wolfssl/wolfcrypt/ecc.h>
#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/logging.h>
#include <wolfssl/wolfcrypt/types.h>
#ifdef WOLFSSL_HAVE_SP_ECC
#include <wolfssl/wolfcrypt/sp.h>
#endif
#ifdef HAVE_ECC_ENCRYPT
#include <wolfssl/wolfcrypt/hmac.h>
#include <wolfssl/wolfcrypt/aes.h>
#endif
#ifdef HAVE_X963_KDF
#include <wolfssl/wolfcrypt/hash.h>
#endif
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#if defined(FREESCALE_LTC_ECC)
#include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
#endif
#if defined(WOLFSSL_STM32_PKA)
#include <wolfssl/wolfcrypt/port/st/stm32.h>
#endif
#ifdef WOLFSSL_SP_MATH
#define GEN_MEM_ERR MP_MEM
#elif defined(USE_FAST_MATH)
#define GEN_MEM_ERR FP_MEM
#else
#define GEN_MEM_ERR MP_MEM
#endif
/* internal ECC states */
enum {
ECC_STATE_NONE = 0,
ECC_STATE_SHARED_SEC_GEN,
ECC_STATE_SHARED_SEC_RES,
ECC_STATE_SIGN_DO,
ECC_STATE_SIGN_ENCODE,
ECC_STATE_VERIFY_DECODE,
ECC_STATE_VERIFY_DO,
ECC_STATE_VERIFY_RES,
};
/* map
ptmul -> mulmod
*/
/* 256-bit curve on by default whether user curves or not */
#if defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES)
#define ECC112
#endif
#if defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES)
#define ECC128
#endif
#if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
#define ECC160
#endif
#if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
#define ECC192
#endif
#if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
#define ECC224
#endif
#if defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES)
#define ECC239
#endif
#if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
#define ECC256
#endif
#if defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES)
#define ECC320
#endif
#if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
#define ECC384
#endif
#if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
#define ECC512
#endif
#if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
#define ECC521
#endif
/* The encoded OID's for ECC curves */
#ifdef ECC112
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP112R1 {1,3,132,0,6}
#define CODED_SECP112R1_SZ 5
#else
#define CODED_SECP112R1 {0x2B,0x81,0x04,0x00,0x06}
#define CODED_SECP112R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp112r1[] = CODED_SECP112R1;
#else
#define ecc_oid_secp112r1 CODED_SECP112R1
#endif
#define ecc_oid_secp112r1_sz CODED_SECP112R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP112R2 {1,3,132,0,7}
#define CODED_SECP112R2_SZ 5
#else
#define CODED_SECP112R2 {0x2B,0x81,0x04,0x00,0x07}
#define CODED_SECP112R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp112r2[] = CODED_SECP112R2;
#else
#define ecc_oid_secp112r2 CODED_SECP112R2
#endif
#define ecc_oid_secp112r2_sz CODED_SECP112R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC112 */
#ifdef ECC128
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP128R1 {1,3,132,0,28}
#define CODED_SECP128R1_SZ 5
#else
#define CODED_SECP128R1 {0x2B,0x81,0x04,0x00,0x1C}
#define CODED_SECP128R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp128r1[] = CODED_SECP128R1;
#else
#define ecc_oid_secp128r1 CODED_SECP128R1
#endif
#define ecc_oid_secp128r1_sz CODED_SECP128R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP128R2 {1,3,132,0,29}
#define CODED_SECP128R2_SZ 5
#else
#define CODED_SECP128R2 {0x2B,0x81,0x04,0x00,0x1D}
#define CODED_SECP128R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp128r2[] = CODED_SECP128R2;
#else
#define ecc_oid_secp128r2 CODED_SECP128R2
#endif
#define ecc_oid_secp128r2_sz CODED_SECP128R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC128 */
#ifdef ECC160
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160R1 {1,3,132,0,8}
#define CODED_SECP160R1_SZ 5
#else
#define CODED_SECP160R1 {0x2B,0x81,0x04,0x00,0x08}
#define CODED_SECP160R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160r1[] = CODED_SECP160R1;
#else
#define ecc_oid_secp160r1 CODED_SECP160R1
#endif
#define ecc_oid_secp160r1_sz CODED_SECP160R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160R2 {1,3,132,0,30}
#define CODED_SECP160R2_SZ 5
#else
#define CODED_SECP160R2 {0x2B,0x81,0x04,0x00,0x1E}
#define CODED_SECP160R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160r2[] = CODED_SECP160R2;
#else
#define ecc_oid_secp160r2 CODED_SECP160R2
#endif
#define ecc_oid_secp160r2_sz CODED_SECP160R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160K1 {1,3,132,0,9}
#define CODED_SECP160K1_SZ 5
#else
#define CODED_SECP160K1 {0x2B,0x81,0x04,0x00,0x09}
#define CODED_SECP160K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160k1[] = CODED_SECP160K1;
#else
#define ecc_oid_secp160k1 CODED_SECP160K1
#endif
#define ecc_oid_secp160k1_sz CODED_SECP160K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP160R1 {1,3,36,3,3,2,8,1,1,1}
#define CODED_BRAINPOOLP160R1_SZ 10
#else
#define CODED_BRAINPOOLP160R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01}
#define CODED_BRAINPOOLP160R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp160r1[] = CODED_BRAINPOOLP160R1;
#else
#define ecc_oid_brainpoolp160r1 CODED_BRAINPOOLP160R1
#endif
#define ecc_oid_brainpoolp160r1_sz CODED_BRAINPOOLP160R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC160 */
#ifdef ECC192
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP192R1 {1,2,840,10045,3,1,1}
#define CODED_SECP192R1_SZ 7
#else
#define CODED_SECP192R1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x01}
#define CODED_SECP192R1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp192r1[] = CODED_SECP192R1;
#else
#define ecc_oid_secp192r1 CODED_SECP192R1
#endif
#define ecc_oid_secp192r1_sz CODED_SECP192R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME192V2 {1,2,840,10045,3,1,2}
#define CODED_PRIME192V2_SZ 7
#else
#define CODED_PRIME192V2 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x02}
#define CODED_PRIME192V2_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime192v2[] = CODED_PRIME192V2;
#else
#define ecc_oid_prime192v2 CODED_PRIME192V2
#endif
#define ecc_oid_prime192v2_sz CODED_PRIME192V2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME192V3 {1,2,840,10045,3,1,3}
#define CODED_PRIME192V3_SZ 7
#else
#define CODED_PRIME192V3 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x03}
#define CODED_PRIME192V3_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime192v3[] = CODED_PRIME192V3;
#else
#define ecc_oid_prime192v3 CODED_PRIME192V3
#endif
#define ecc_oid_prime192v3_sz CODED_PRIME192V3_SZ
#endif /* HAVE_ECC_SECPR3 */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP192K1 {1,3,132,0,31}
#define CODED_SECP192K1_SZ 5
#else
#define CODED_SECP192K1 {0x2B,0x81,0x04,0x00,0x1F}
#define CODED_SECP192K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp192k1[] = CODED_SECP192K1;
#else
#define ecc_oid_secp192k1 CODED_SECP192K1
#endif
#define ecc_oid_secp192k1_sz CODED_SECP192K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP192R1 {1,3,36,3,3,2,8,1,1,3}
#define CODED_BRAINPOOLP192R1_SZ 10
#else
#define CODED_BRAINPOOLP192R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03}
#define CODED_BRAINPOOLP192R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp192r1[] = CODED_BRAINPOOLP192R1;
#else
#define ecc_oid_brainpoolp192r1 CODED_BRAINPOOLP192R1
#endif
#define ecc_oid_brainpoolp192r1_sz CODED_BRAINPOOLP192R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC192 */
#ifdef ECC224
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP224R1 {1,3,132,0,33}
#define CODED_SECP224R1_SZ 5
#else
#define CODED_SECP224R1 {0x2B,0x81,0x04,0x00,0x21}
#define CODED_SECP224R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp224r1[] = CODED_SECP224R1;
#else
#define ecc_oid_secp224r1 CODED_SECP224R1
#endif
#define ecc_oid_secp224r1_sz CODED_SECP224R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP224K1 {1,3,132,0,32}
#define CODED_SECP224K1_SZ 5
#else
#define CODED_SECP224K1 {0x2B,0x81,0x04,0x00,0x20}
#define CODED_SECP224K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp224k1[] = CODED_SECP224K1;
#else
#define ecc_oid_secp224k1 CODED_SECP224K1
#endif
#define ecc_oid_secp224k1_sz CODED_SECP224K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP224R1 {1,3,36,3,3,2,8,1,1,5}
#define CODED_BRAINPOOLP224R1_SZ 10
#else
#define CODED_BRAINPOOLP224R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05}
#define CODED_BRAINPOOLP224R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp224r1[] = CODED_BRAINPOOLP224R1;
#else
#define ecc_oid_brainpoolp224r1 CODED_BRAINPOOLP224R1
#endif
#define ecc_oid_brainpoolp224r1_sz CODED_BRAINPOOLP224R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC224 */
#ifdef ECC239
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V1 {1,2,840,10045,3,1,4}
#define CODED_PRIME239V1_SZ 7
#else
#define CODED_PRIME239V1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x04}
#define CODED_PRIME239V1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v1[] = CODED_PRIME239V1;
#else
#define ecc_oid_prime239v1 CODED_PRIME239V1
#endif
#define ecc_oid_prime239v1_sz CODED_PRIME239V1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V2 {1,2,840,10045,3,1,5}
#define CODED_PRIME239V2_SZ 7
#else
#define CODED_PRIME239V2 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x05}
#define CODED_PRIME239V2_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v2[] = CODED_PRIME239V2;
#else
#define ecc_oid_prime239v2 CODED_PRIME239V2
#endif
#define ecc_oid_prime239v2_sz CODED_PRIME239V2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V3 {1,2,840,10045,3,1,6}
#define CODED_PRIME239V3_SZ 7
#else
#define CODED_PRIME239V3 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x06}
#define CODED_PRIME239V3_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v3[] = CODED_PRIME239V3;
#else
#define ecc_oid_prime239v3 CODED_PRIME239V3
#endif
#define ecc_oid_prime239v3_sz CODED_PRIME239V3_SZ
#endif /* HAVE_ECC_SECPR3 */
#endif /* ECC239 */
#ifdef ECC256
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP256R1 {1,2,840,10045,3,1,7}
#define CODED_SECP256R1_SZ 7
#else
#define CODED_SECP256R1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07}
#define CODED_SECP256R1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp256r1[] = CODED_SECP256R1;
#else
#define ecc_oid_secp256r1 CODED_SECP256R1
#endif
#define ecc_oid_secp256r1_sz CODED_SECP256R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP256K1 {1,3,132,0,10}
#define CODED_SECP256K1_SZ 5
#else
#define CODED_SECP256K1 {0x2B,0x81,0x04,0x00,0x0A}
#define CODED_SECP256K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp256k1[] = CODED_SECP256K1;
#else
#define ecc_oid_secp256k1 CODED_SECP256K1
#endif
#define ecc_oid_secp256k1_sz CODED_SECP256K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP256R1 {1,3,36,3,3,2,8,1,1,7}
#define CODED_BRAINPOOLP256R1_SZ 10
#else
#define CODED_BRAINPOOLP256R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07}
#define CODED_BRAINPOOLP256R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp256r1[] = CODED_BRAINPOOLP256R1;
#else
#define ecc_oid_brainpoolp256r1 CODED_BRAINPOOLP256R1
#endif
#define ecc_oid_brainpoolp256r1_sz CODED_BRAINPOOLP256R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC256 */
#ifdef ECC320
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP320R1 {1,3,36,3,3,2,8,1,1,9}
#define CODED_BRAINPOOLP320R1_SZ 10
#else
#define CODED_BRAINPOOLP320R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09}
#define CODED_BRAINPOOLP320R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp320r1[] = CODED_BRAINPOOLP320R1;
#else
#define ecc_oid_brainpoolp320r1 CODED_BRAINPOOLP320R1
#endif
#define ecc_oid_brainpoolp320r1_sz CODED_BRAINPOOLP320R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC320 */
#ifdef ECC384
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP384R1 {1,3,132,0,34}
#define CODED_SECP384R1_SZ 5
#else
#define CODED_SECP384R1 {0x2B,0x81,0x04,0x00,0x22}
#define CODED_SECP384R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp384r1[] = CODED_SECP384R1;
#define CODED_SECP384R1_OID ecc_oid_secp384r1
#else
#define ecc_oid_secp384r1 CODED_SECP384R1
#endif
#define ecc_oid_secp384r1_sz CODED_SECP384R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP384R1 {1,3,36,3,3,2,8,1,1,11}
#define CODED_BRAINPOOLP384R1_SZ 10
#else
#define CODED_BRAINPOOLP384R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0B}
#define CODED_BRAINPOOLP384R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp384r1[] = CODED_BRAINPOOLP384R1;
#else
#define ecc_oid_brainpoolp384r1 CODED_BRAINPOOLP384R1
#endif
#define ecc_oid_brainpoolp384r1_sz CODED_BRAINPOOLP384R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC384 */
#ifdef ECC512
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP512R1 {1,3,36,3,3,2,8,1,1,13}
#define CODED_BRAINPOOLP512R1_SZ 10
#else
#define CODED_BRAINPOOLP512R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0D}
#define CODED_BRAINPOOLP512R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp512r1[] = CODED_BRAINPOOLP512R1;
#else
#define ecc_oid_brainpoolp512r1 CODED_BRAINPOOLP512R1
#endif
#define ecc_oid_brainpoolp512r1_sz CODED_BRAINPOOLP512R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC512 */
#ifdef ECC521
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP521R1 {1,3,132,0,35}
#define CODED_SECP521R1_SZ 5
#else
#define CODED_SECP521R1 {0x2B,0x81,0x04,0x00,0x23}
#define CODED_SECP521R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp521r1[] = CODED_SECP521R1;
#else
#define ecc_oid_secp521r1 CODED_SECP521R1
#endif
#define ecc_oid_secp521r1_sz CODED_SECP521R1_SZ
#endif /* !NO_ECC_SECP */
#endif /* ECC521 */
/* This holds the key settings.
***MUST*** be organized by size from smallest to largest. */
const ecc_set_type ecc_sets[] = {
#ifdef ECC112
#ifndef NO_ECC_SECP
{
14, /* size/bytes */
ECC_SECP112R1, /* ID */
"SECP112R1", /* curve name */
"DB7C2ABF62E35E668076BEAD208B", /* prime */
"DB7C2ABF62E35E668076BEAD2088", /* A */
"659EF8BA043916EEDE8911702B22", /* B */
"DB7C2ABF62E35E7628DFAC6561C5", /* order */
"9487239995A5EE76B55F9C2F098", /* Gx */
"A89CE5AF8724C0A23E0E0FF77500", /* Gy */
ecc_oid_secp112r1, /* oid/oidSz */
ecc_oid_secp112r1_sz,
ECC_SECP112R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
14, /* size/bytes */
ECC_SECP112R2, /* ID */
"SECP112R2", /* curve name */
"DB7C2ABF62E35E668076BEAD208B", /* prime */
"6127C24C05F38A0AAAF65C0EF02C", /* A */
"51DEF1815DB5ED74FCC34C85D709", /* B */
"36DF0AAFD8B8D7597CA10520D04B", /* order */
"4BA30AB5E892B4E1649DD0928643", /* Gx */
"ADCD46F5882E3747DEF36E956E97", /* Gy */
ecc_oid_secp112r2, /* oid/oidSz */
ecc_oid_secp112r2_sz,
ECC_SECP112R2_OID, /* oid sum */
4, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC112 */
#ifdef ECC128
#ifndef NO_ECC_SECP
{
16, /* size/bytes */
ECC_SECP128R1, /* ID */
"SECP128R1", /* curve name */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"E87579C11079F43DD824993C2CEE5ED3", /* B */
"FFFFFFFE0000000075A30D1B9038A115", /* order */
"161FF7528B899B2D0C28607CA52C5B86", /* Gx */
"CF5AC8395BAFEB13C02DA292DDED7A83", /* Gy */
ecc_oid_secp128r1, /* oid/oidSz */
ecc_oid_secp128r1_sz,
ECC_SECP128R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
16, /* size/bytes */
ECC_SECP128R2, /* ID */
"SECP128R2", /* curve name */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"D6031998D1B3BBFEBF59CC9BBFF9AEE1", /* A */
"5EEEFCA380D02919DC2C6558BB6D8A5D", /* B */
"3FFFFFFF7FFFFFFFBE0024720613B5A3", /* order */
"7B6AA5D85E572983E6FB32A7CDEBC140", /* Gx */
"27B6916A894D3AEE7106FE805FC34B44", /* Gy */
ecc_oid_secp128r2, /* oid/oidSz */
ecc_oid_secp128r2_sz,
ECC_SECP128R2_OID, /* oid sum */
4, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC128 */
#ifdef ECC160
#ifndef NO_ECC_SECP
{
20, /* size/bytes */
ECC_SECP160R1, /* ID */
"SECP160R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", /* A */
"1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", /* B */
"100000000000000000001F4C8F927AED3CA752257",/* order */
"4A96B5688EF573284664698968C38BB913CBFC82", /* Gx */
"23A628553168947D59DCC912042351377AC5FB32", /* Gy */
ecc_oid_secp160r1, /* oid/oidSz */
ecc_oid_secp160r1_sz,
ECC_SECP160R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
20, /* size/bytes */
ECC_SECP160R2, /* ID */
"SECP160R2", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70", /* A */
"B4E134D3FB59EB8BAB57274904664D5AF50388BA", /* B */
"100000000000000000000351EE786A818F3A1A16B",/* order */
"52DCB034293A117E1F4FF11B30F7199D3144CE6D", /* Gx */
"FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E", /* Gy */
ecc_oid_secp160r2, /* oid/oidSz */
ecc_oid_secp160r2_sz,
ECC_SECP160R2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_KOBLITZ
{
20, /* size/bytes */
ECC_SECP160K1, /* ID */
"SECP160K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */
"0000000000000000000000000000000000000000", /* A */
"0000000000000000000000000000000000000007", /* B */
"100000000000000000001B8FA16DFAB9ACA16B6B3",/* order */
"3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", /* Gx */
"938CF935318FDCED6BC28286531733C3F03C4FEE", /* Gy */
ecc_oid_secp160k1, /* oid/oidSz */
ecc_oid_secp160k1_sz,
ECC_SECP160K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
20, /* size/bytes */
ECC_BRAINPOOLP160R1, /* ID */
"BRAINPOOLP160R1", /* curve name */
"E95E4A5F737059DC60DFC7AD95B3D8139515620F", /* prime */
"340E7BE2A280EB74E2BE61BADA745D97E8F7C300", /* A */
"1E589A8595423412134FAA2DBDEC95C8D8675E58", /* B */
"E95E4A5F737059DC60DF5991D45029409E60FC09", /* order */
"BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC3", /* Gx */
"1667CB477A1A8EC338F94741669C976316DA6321", /* Gy */
ecc_oid_brainpoolp160r1, /* oid/oidSz */
ecc_oid_brainpoolp160r1_sz,
ECC_BRAINPOOLP160R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC160 */
#ifdef ECC192
#ifndef NO_ECC_SECP
{
24, /* size/bytes */
ECC_SECP192R1, /* ID */
"SECP192R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", /* order */
"188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", /* Gx */
"7192B95FFC8DA78631011ED6B24CDD573F977A11E794811", /* Gy */
ecc_oid_secp192r1, /* oid/oidSz */
ecc_oid_secp192r1_sz,
ECC_SECP192R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
24, /* size/bytes */
ECC_PRIME192V2, /* ID */
"PRIME192V2", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"CC22D6DFB95C6B25E49C0D6364A4E5980C393AA21668D953", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFE5FB1A724DC80418648D8DD31", /* order */
"EEA2BAE7E1497842F2DE7769CFE9C989C072AD696F48034A", /* Gx */
"6574D11D69B6EC7A672BB82A083DF2F2B0847DE970B2DE15", /* Gy */
ecc_oid_prime192v2, /* oid/oidSz */
ecc_oid_prime192v2_sz,
ECC_PRIME192V2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
{
24, /* size/bytes */
ECC_PRIME192V3, /* ID */
"PRIME192V3", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"22123DC2395A05CAA7423DAECCC94760A7D462256BD56916", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFF7A62D031C83F4294F640EC13", /* order */
"7D29778100C65A1DA1783716588DCE2B8B4AEE8E228F1896", /* Gx */
"38A90F22637337334B49DCB66A6DC8F9978ACA7648A943B0", /* Gy */
ecc_oid_prime192v3, /* oid/oidSz */
ecc_oid_prime192v3_sz,
ECC_PRIME192V3_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR3 */
#ifdef HAVE_ECC_KOBLITZ
{
24, /* size/bytes */
ECC_SECP192K1, /* ID */
"SECP192K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", /* prime */
"000000000000000000000000000000000000000000000000", /* A */
"000000000000000000000000000000000000000000000003", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", /* order */
"DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", /* Gx */
"9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", /* Gy */
ecc_oid_secp192k1, /* oid/oidSz */
ecc_oid_secp192k1_sz,
ECC_SECP192K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
24, /* size/bytes */
ECC_BRAINPOOLP192R1, /* ID */
"BRAINPOOLP192R1", /* curve name */
"C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", /* prime */
"6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", /* A */
"469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", /* B */
"C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", /* order */
"C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD6", /* Gx */
"14B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F", /* Gy */
ecc_oid_brainpoolp192r1, /* oid/oidSz */
ecc_oid_brainpoolp192r1_sz,
ECC_BRAINPOOLP192R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC192 */
#ifdef ECC224
#ifndef NO_ECC_SECP
{
28, /* size/bytes */
ECC_SECP224R1, /* ID */
"SECP224R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", /* A */
"B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", /* order */
"B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", /* Gx */
"BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", /* Gy */
ecc_oid_secp224r1, /* oid/oidSz */
ecc_oid_secp224r1_sz,
ECC_SECP224R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
{
28, /* size/bytes */
ECC_SECP224K1, /* ID */
"SECP224K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", /* prime */
"00000000000000000000000000000000000000000000000000000000", /* A */
"00000000000000000000000000000000000000000000000000000005", /* B */
"10000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7",/* order */
"A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", /* Gx */
"7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", /* Gy */
ecc_oid_secp224k1, /* oid/oidSz */
ecc_oid_secp224k1_sz,
ECC_SECP224K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
28, /* size/bytes */
ECC_BRAINPOOLP224R1, /* ID */
"BRAINPOOLP224R1", /* curve name */
"D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", /* prime */
"68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", /* A */
"2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", /* B */
"D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", /* order */
"0D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D", /* Gx */
"58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD", /* Gy */
ecc_oid_brainpoolp224r1, /* oid/oidSz */
ecc_oid_brainpoolp224r1_sz,
ECC_BRAINPOOLP224R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC224 */
#ifdef ECC239
#ifndef NO_ECC_SECP
{
30, /* size/bytes */
ECC_PRIME239V1, /* ID */
"PRIME239V1", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"6B016C3BDCF18941D0D654921475CA71A9DB2FB27D1D37796185C2942C0A", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF9E5E9A9F5D9071FBD1522688909D0B", /* order */
"0FFA963CDCA8816CCC33B8642BEDF905C3D358573D3F27FBBD3B3CB9AAAF", /* Gx */
"7DEBE8E4E90A5DAE6E4054CA530BA04654B36818CE226B39FCCB7B02F1AE", /* Gy */
ecc_oid_prime239v1, /* oid/oidSz */
ecc_oid_prime239v1_sz,
ECC_PRIME239V1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
30, /* size/bytes */
ECC_PRIME239V2, /* ID */
"PRIME239V2", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"617FAB6832576CBBFED50D99F0249C3FEE58B94BA0038C7AE84C8C832F2C", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF800000CFA7E8594377D414C03821BC582063", /* order */
"38AF09D98727705120C921BB5E9E26296A3CDCF2F35757A0EAFD87B830E7", /* Gx */
"5B0125E4DBEA0EC7206DA0FC01D9B081329FB555DE6EF460237DFF8BE4BA", /* Gy */
ecc_oid_prime239v2, /* oid/oidSz */
ecc_oid_prime239v2_sz,
ECC_PRIME239V2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
{
30, /* size/bytes */
ECC_PRIME239V3, /* ID */
"PRIME239V3", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"255705FA2A306654B1F4CB03D6A750A30C250102D4988717D9BA15AB6D3E", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF975DEB41B3A6057C3C432146526551", /* order */
"6768AE8E18BB92CFCF005C949AA2C6D94853D0E660BBF854B1C9505FE95A", /* Gx */
"1607E6898F390C06BC1D552BAD226F3B6FCFE48B6E818499AF18E3ED6CF3", /* Gy */
ecc_oid_prime239v3, /* oid/oidSz */
ecc_oid_prime239v3_sz,
ECC_PRIME239V3_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR3 */
#endif /* ECC239 */
#ifdef ECC256
#ifndef NO_ECC_SECP
{
32, /* size/bytes */
ECC_SECP256R1, /* ID */
"SECP256R1", /* curve name */
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", /* B */
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", /* order */
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", /* Gx */
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", /* Gy */
ecc_oid_secp256r1, /* oid/oidSz */
ecc_oid_secp256r1_sz,
ECC_SECP256R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
{
32, /* size/bytes */
ECC_SECP256K1, /* ID */
"SECP256K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", /* prime */
"0000000000000000000000000000000000000000000000000000000000000000", /* A */
"0000000000000000000000000000000000000000000000000000000000000007", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", /* order */
"79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", /* Gx */
"483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", /* Gy */
ecc_oid_secp256k1, /* oid/oidSz */
ecc_oid_secp256k1_sz,
ECC_SECP256K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
32, /* size/bytes */
ECC_BRAINPOOLP256R1, /* ID */
"BRAINPOOLP256R1", /* curve name */
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", /* prime */
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", /* A */
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", /* B */
"A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", /* order */
"8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", /* Gx */
"547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", /* Gy */
ecc_oid_brainpoolp256r1, /* oid/oidSz */
ecc_oid_brainpoolp256r1_sz,
ECC_BRAINPOOLP256R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC256 */
#ifdef ECC320
#ifdef HAVE_ECC_BRAINPOOL
{
40, /* size/bytes */
ECC_BRAINPOOLP320R1, /* ID */
"BRAINPOOLP320R1", /* curve name */
"D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", /* prime */
"3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", /* A */
"520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", /* B */
"D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", /* order */
"43BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E20611", /* Gx */
"14FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1", /* Gy */
ecc_oid_brainpoolp320r1, ecc_oid_brainpoolp320r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP320R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC320 */
#ifdef ECC384
#ifndef NO_ECC_SECP
{
48, /* size/bytes */
ECC_SECP384R1, /* ID */
"SECP384R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", /* A */
"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", /* order */
"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", /* Gx */
"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", /* Gy */
ecc_oid_secp384r1, ecc_oid_secp384r1_sz, /* oid/oidSz */
ECC_SECP384R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_BRAINPOOL
{
48, /* size/bytes */
ECC_BRAINPOOLP384R1, /* ID */
"BRAINPOOLP384R1", /* curve name */
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", /* prime */
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", /* A */
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", /* B */
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", /* order */
"1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", /* Gx */
"8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", /* Gy */
ecc_oid_brainpoolp384r1, ecc_oid_brainpoolp384r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP384R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC384 */
#ifdef ECC512
#ifdef HAVE_ECC_BRAINPOOL
{
64, /* size/bytes */
ECC_BRAINPOOLP512R1, /* ID */
"BRAINPOOLP512R1", /* curve name */
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", /* prime */
"7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", /* A */
"3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", /* B */
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", /* order */
"81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", /* Gx */
"7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", /* Gy */
ecc_oid_brainpoolp512r1, ecc_oid_brainpoolp512r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP512R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC512 */
#ifdef ECC521
#ifndef NO_ECC_SECP
{
66, /* size/bytes */
ECC_SECP521R1, /* ID */
"SECP521R1", /* curve name */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"51953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", /* B */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", /* order */
"C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", /* Gx */
"11839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", /* Gy */
ecc_oid_secp521r1, ecc_oid_secp521r1_sz, /* oid/oidSz */
ECC_SECP521R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#endif /* ECC521 */
#if defined(WOLFSSL_CUSTOM_CURVES) && defined(ECC_CACHE_CURVE)
/* place holder for custom curve index for cache */
{
1, /* non-zero */
ECC_CURVE_CUSTOM,
#ifndef WOLFSSL_ECC_CURVE_STATIC
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
#else
{0},{0},{0},{0},{0},{0},{0},{0},
#endif
0, 0, 0
},
#endif
{
0,
ECC_CURVE_INVALID,
#ifndef WOLFSSL_ECC_CURVE_STATIC
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
#else
{0},{0},{0},{0},{0},{0},{0},{0},
#endif
0, 0, 0
}
};
#define ECC_SET_COUNT (sizeof(ecc_sets)/sizeof(ecc_set_type))
#ifdef HAVE_OID_ENCODING
/* encoded OID cache */
typedef struct {
word32 oidSz;
byte oid[ECC_MAX_OID_LEN];
} oid_cache_t;
static oid_cache_t ecc_oid_cache[ECC_SET_COUNT];
#endif
#ifdef HAVE_COMP_KEY
static int wc_ecc_export_x963_compressed(ecc_key*, byte* out, word32* outLen);
#endif
#if (defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH)) && \
!defined(WOLFSSL_ATECC508A)
static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a,
mp_int* prime, mp_int* order);
#endif
int mp_jacobi(mp_int* a, mp_int* n, int* c);
int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret);
/* Curve Specs */
typedef struct ecc_curve_spec {
const ecc_set_type* dp;
mp_int* prime;
mp_int* Af;
#ifdef USE_ECC_B_PARAM
mp_int* Bf;
#endif
mp_int* order;
mp_int* Gx;
mp_int* Gy;
#ifdef ECC_CACHE_CURVE
mp_int prime_lcl;
mp_int Af_lcl;
#ifdef USE_ECC_B_PARAM
mp_int Bf_lcl;
#endif
mp_int order_lcl;
mp_int Gx_lcl;
mp_int Gy_lcl;
#else
mp_int* spec_ints;
word32 spec_count;
word32 spec_use;
#endif
byte load_mask;
} ecc_curve_spec;
enum ecc_curve_load_mask {
ECC_CURVE_FIELD_NONE = 0x00,
ECC_CURVE_FIELD_PRIME = 0x01,
ECC_CURVE_FIELD_AF = 0x02,
#ifdef USE_ECC_B_PARAM
ECC_CURVE_FIELD_BF = 0x04,
#endif
ECC_CURVE_FIELD_ORDER = 0x08,
ECC_CURVE_FIELD_GX = 0x10,
ECC_CURVE_FIELD_GY = 0x20,
#ifdef USE_ECC_B_PARAM
ECC_CURVE_FIELD_ALL = 0x3F,
ECC_CURVE_FIELD_COUNT = 6,
#else
ECC_CURVE_FIELD_ALL = 0x3B,
ECC_CURVE_FIELD_COUNT = 5,
#endif
};
#ifdef ECC_CACHE_CURVE
/* cache (mp_int) of the curve parameters */
static ecc_curve_spec* ecc_curve_spec_cache[ECC_SET_COUNT];
#ifndef SINGLE_THREADED
static wolfSSL_Mutex ecc_curve_cache_mutex;
#endif
#define DECLARE_CURVE_SPECS(curve, intcount) ecc_curve_spec* curve = NULL
#define ALLOC_CURVE_SPECS(intcount)
#define FREE_CURVE_SPECS()
#elif defined(WOLFSSL_SMALL_STACK)
#define DECLARE_CURVE_SPECS(curve, intcount) \
mp_int* spec_ints = NULL; \
ecc_curve_spec curve_lcl; \
ecc_curve_spec* curve = &curve_lcl; \
XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \
curve->spec_count = intcount
#define ALLOC_CURVE_SPECS(intcount) \
spec_ints = (mp_int*)XMALLOC(sizeof(mp_int) * (intcount), NULL, \
DYNAMIC_TYPE_ECC); \
if (spec_ints == NULL) \
return MEMORY_E; \
curve->spec_ints = spec_ints
#define FREE_CURVE_SPECS() \
XFREE(spec_ints, NULL, DYNAMIC_TYPE_ECC)
#else
#define DECLARE_CURVE_SPECS(curve, intcount) \
mp_int spec_ints[(intcount)]; \
ecc_curve_spec curve_lcl; \
ecc_curve_spec* curve = &curve_lcl; \
XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \
curve->spec_ints = spec_ints; \
curve->spec_count = intcount
#define ALLOC_CURVE_SPECS(intcount)
#define FREE_CURVE_SPECS()
#endif /* ECC_CACHE_CURVE */
static void _wc_ecc_curve_free(ecc_curve_spec* curve)
{
if (curve == NULL) {
return;
}
if (curve->load_mask & ECC_CURVE_FIELD_PRIME)
mp_clear(curve->prime);
if (curve->load_mask & ECC_CURVE_FIELD_AF)
mp_clear(curve->Af);
#ifdef USE_ECC_B_PARAM
if (curve->load_mask & ECC_CURVE_FIELD_BF)
mp_clear(curve->Bf);
#endif
if (curve->load_mask & ECC_CURVE_FIELD_ORDER)
mp_clear(curve->order);
if (curve->load_mask & ECC_CURVE_FIELD_GX)
mp_clear(curve->Gx);
if (curve->load_mask & ECC_CURVE_FIELD_GY)
mp_clear(curve->Gy);
curve->load_mask = 0;
}
static void wc_ecc_curve_free(ecc_curve_spec* curve)
{
/* don't free cached curves */
#ifndef ECC_CACHE_CURVE
_wc_ecc_curve_free(curve);
#endif
(void)curve;
}
static int wc_ecc_curve_load_item(const char* src, mp_int** dst,
ecc_curve_spec* curve, byte mask)
{
int err;
#ifndef ECC_CACHE_CURVE
/* get mp_int from temp */
if (curve->spec_use >= curve->spec_count) {
WOLFSSL_MSG("Invalid DECLARE_CURVE_SPECS count");
return ECC_BAD_ARG_E;
}
*dst = &curve->spec_ints[curve->spec_use++];
#endif
err = mp_init(*dst);
if (err == MP_OKAY) {
curve->load_mask |= mask;
err = mp_read_radix(*dst, src, MP_RADIX_HEX);
#ifdef HAVE_WOLF_BIGINT
if (err == MP_OKAY)
err = wc_mp_to_bigint(*dst, &(*dst)->raw);
#endif
}
return err;
}
static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve,
byte load_mask)
{
int ret = 0, x;
ecc_curve_spec* curve;
byte load_items = 0; /* mask of items to load */
if (dp == NULL || pCurve == NULL)
return BAD_FUNC_ARG;
#ifdef ECC_CACHE_CURVE
x = wc_ecc_get_curve_idx(dp->id);
if (x == ECC_CURVE_INVALID)
return ECC_BAD_ARG_E;
#if !defined(SINGLE_THREADED)
ret = wc_LockMutex(&ecc_curve_cache_mutex);
if (ret != 0) {
return ret;
}
#endif
/* make sure cache has been allocated */
if (ecc_curve_spec_cache[x] == NULL) {
ecc_curve_spec_cache[x] = (ecc_curve_spec*)XMALLOC(
sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC);
if (ecc_curve_spec_cache[x] == NULL) {
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_UnLockMutex(&ecc_curve_cache_mutex);
#endif
return MEMORY_E;
}
XMEMSET(ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec));
}
/* set curve pointer to cache */
*pCurve = ecc_curve_spec_cache[x];
#endif /* ECC_CACHE_CURVE */
curve = *pCurve;
/* make sure the curve is initialized */
if (curve->dp != dp) {
curve->load_mask = 0;
#ifdef ECC_CACHE_CURVE
curve->prime = &curve->prime_lcl;
curve->Af = &curve->Af_lcl;
#ifdef USE_ECC_B_PARAM
curve->Bf = &curve->Bf_lcl;
#endif
curve->order = &curve->order_lcl;
curve->Gx = &curve->Gx_lcl;
curve->Gy = &curve->Gy_lcl;
#endif
}
curve->dp = dp; /* set dp info */
/* determine items to load */
load_items = (((byte)~(word32)curve->load_mask) & load_mask);
curve->load_mask |= load_items;
/* load items */
x = 0;
if (load_items & ECC_CURVE_FIELD_PRIME)
x += wc_ecc_curve_load_item(dp->prime, &curve->prime, curve,
ECC_CURVE_FIELD_PRIME);
if (load_items & ECC_CURVE_FIELD_AF)
x += wc_ecc_curve_load_item(dp->Af, &curve->Af, curve,
ECC_CURVE_FIELD_AF);
#ifdef USE_ECC_B_PARAM
if (load_items & ECC_CURVE_FIELD_BF)
x += wc_ecc_curve_load_item(dp->Bf, &curve->Bf, curve,
ECC_CURVE_FIELD_BF);
#endif
if (load_items & ECC_CURVE_FIELD_ORDER)
x += wc_ecc_curve_load_item(dp->order, &curve->order, curve,
ECC_CURVE_FIELD_ORDER);
if (load_items & ECC_CURVE_FIELD_GX)
x += wc_ecc_curve_load_item(dp->Gx, &curve->Gx, curve,
ECC_CURVE_FIELD_GX);
if (load_items & ECC_CURVE_FIELD_GY)
x += wc_ecc_curve_load_item(dp->Gy, &curve->Gy, curve,
ECC_CURVE_FIELD_GY);
/* check for error */
if (x != 0) {
wc_ecc_curve_free(curve);
ret = MP_READ_E;
}
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_UnLockMutex(&ecc_curve_cache_mutex);
#endif
return ret;
}
#ifdef ECC_CACHE_CURVE
int wc_ecc_curve_cache_init(void)
{
int ret = 0;
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
ret = wc_InitMutex(&ecc_curve_cache_mutex);
#endif
return ret;
}
void wc_ecc_curve_cache_free(void)
{
int x;
/* free all ECC curve caches */
for (x = 0; x < (int)ECC_SET_COUNT; x++) {
if (ecc_curve_spec_cache[x]) {
_wc_ecc_curve_free(ecc_curve_spec_cache[x]);
XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC);
ecc_curve_spec_cache[x] = NULL;
}
}
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_FreeMutex(&ecc_curve_cache_mutex);
#endif
}
#endif /* ECC_CACHE_CURVE */
/* Retrieve the curve name for the ECC curve id.
*
* curve_id The id of the curve.
* returns the name stored from the curve if available, otherwise NULL.
*/
const char* wc_ecc_get_name(int curve_id)
{
int curve_idx = wc_ecc_get_curve_idx(curve_id);
if (curve_idx == ECC_CURVE_INVALID)
return NULL;
return ecc_sets[curve_idx].name;
}
int wc_ecc_set_curve(ecc_key* key, int keysize, int curve_id)
{
if (keysize <= 0 && curve_id < 0) {
return BAD_FUNC_ARG;
}
if (keysize > ECC_MAXSIZE) {
return ECC_BAD_ARG_E;
}
/* handle custom case */
if (key->idx != ECC_CUSTOM_IDX) {
int x;
/* default values */
key->idx = 0;
key->dp = NULL;
/* find ecc_set based on curve_id or key size */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (curve_id > ECC_CURVE_DEF) {
if (curve_id == ecc_sets[x].id)
break;
}
else if (keysize <= ecc_sets[x].size) {
break;
}
}
if (ecc_sets[x].size == 0) {
WOLFSSL_MSG("ECC Curve not found");
return ECC_CURVE_OID_E;
}
key->idx = x;
key->dp = &ecc_sets[x];
}
return 0;
}
#ifdef ALT_ECC_SIZE
static void alt_fp_init(mp_int* a)
{
a->size = FP_SIZE_ECC;
mp_zero(a);
}
#endif /* ALT_ECC_SIZE */
#ifndef WOLFSSL_ATECC508A
#if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_PUBLIC_ECC_ADD_DBL)
/**
Add two ECC points
P The point to add
Q The point to add
R [out] The destination of the double
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
return MP_OKAY on success
*/
int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R,
mp_int* a, mp_int* modulus, mp_digit mp)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif
mp_int *x, *y, *z;
int err;
if (P == NULL || Q == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* if Q == R then swap P and Q, so we don't require a local x,y,z */
if (Q == R) {
ecc_point* tPt = P;
P = Q;
Q = tPt;
}
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key != NULL) {
t1 = R->key->t1;
t2 = R->key->t2;
#ifdef ALT_ECC_SIZE
rx = R->key->x;
ry = R->key->y;
rz = R->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif /* WOLFSSL_SMALL_STACK */
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
/* should we dbl instead? */
if (err == MP_OKAY)
err = mp_sub(modulus, Q->y, t1);
if (err == MP_OKAY) {
if ( (mp_cmp(P->x, Q->x) == MP_EQ) &&
(get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) &&
(mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, t1) == MP_EQ)) {
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return ecc_projective_dbl_point(P, R, a, modulus, mp);
}
}
if (err != MP_OKAY) {
goto done;
}
/* If use ALT_ECC_SIZE we need to use local stack variable since
ecc_point x,y,z is reduced size */
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
goto done;
}
#else
/* Use destination directly */
x = R->x;
y = R->y;
z = R->z;
#endif
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
/* if Z is one then these are no-operations */
if (err == MP_OKAY) {
if (!mp_iszero(Q->z)) {
/* T1 = Z' * Z' */
err = mp_sqr(Q->z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = X * T1 */
if (err == MP_OKAY)
err = mp_mul(t1, x, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* T1 = Z' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->z, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Y = Y * T1 */
if (err == MP_OKAY)
err = mp_mul(t1, y, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
}
}
/* T1 = Z*Z */
if (err == MP_OKAY)
err = mp_sqr(z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* T2 = X' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->x, t1, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = Z * T1 */
if (err == MP_OKAY)
err = mp_mul(z, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* T1 = Y' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->y, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Y = Y - T1 */
if (err == MP_OKAY)
err = mp_sub(y, t1, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* T1 = 2T1 */
if (err == MP_OKAY)
err = mp_add(t1, t1, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = Y + T1 */
if (err == MP_OKAY)
err = mp_add(t1, y, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* X = X - T2 */
if (err == MP_OKAY)
err = mp_sub(x, t2, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* T2 = 2T2 */
if (err == MP_OKAY)
err = mp_add(t2, t2, t2);
if (err == MP_OKAY) {
if (mp_cmp(t2, modulus) != MP_LT)
err = mp_sub(t2, modulus, t2);
}
/* T2 = X + T2 */
if (err == MP_OKAY)
err = mp_add(t2, x, t2);
if (err == MP_OKAY) {
if (mp_cmp(t2, modulus) != MP_LT)
err = mp_sub(t2, modulus, t2);
}
if (err == MP_OKAY) {
if (!mp_iszero(Q->z)) {
/* Z = Z * Z' */
err = mp_mul(z, Q->z, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
}
}
/* Z = Z * X */
if (err == MP_OKAY)
err = mp_mul(z, x, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
/* T1 = T1 * X */
if (err == MP_OKAY)
err = mp_mul(t1, x, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = X * X */
if (err == MP_OKAY)
err = mp_sqr(x, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* T2 = T2 * x */
if (err == MP_OKAY)
err = mp_mul(t2, x, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T1 * X */
if (err == MP_OKAY)
err = mp_mul(t1, x, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = Y*Y */
if (err == MP_OKAY)
err = mp_sqr(y, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* X = X - T2 */
if (err == MP_OKAY)
err = mp_sub(x, t2, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* T2 = T2 - X */
if (err == MP_OKAY)
err = mp_sub(t2, x, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T2 = T2 - X */
if (err == MP_OKAY)
err = mp_sub(t2, x, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T2 = T2 * Y */
if (err == MP_OKAY)
err = mp_mul(t2, y, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* Y = T2 - T1 */
if (err == MP_OKAY)
err = mp_sub(t2, t1, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* Y = Y/2 */
if (err == MP_OKAY) {
if (mp_isodd(y) == MP_YES)
err = mp_add(y, modulus, y);
}
if (err == MP_OKAY)
err = mp_div_2(y, y);
#ifdef ALT_ECC_SIZE
if (err == MP_OKAY)
err = mp_copy(x, R->x);
if (err == MP_OKAY)
err = mp_copy(y, R->y);
if (err == MP_OKAY)
err = mp_copy(z, R->z);
#endif
done:
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || Q == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
(void)a;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_proj_add_point_256(P->x, P->y, P->z, Q->x, Q->y, Q->z,
R->x, R->y, R->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_proj_add_point_384(P->x, P->y, P->z, Q->x, Q->y, Q->z,
R->x, R->y, R->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
/* ### Point doubling in Jacobian coordinate system ###
*
* let us have a curve: y^2 = x^3 + a*x + b
* in Jacobian coordinates it becomes: y^2 = x^3 + a*x*z^4 + b*z^6
*
* The doubling of P = (Xp, Yp, Zp) is given by R = (Xr, Yr, Zr) where:
* Xr = M^2 - 2*S
* Yr = M * (S - Xr) - 8*T
* Zr = 2 * Yp * Zp
*
* M = 3 * Xp^2 + a*Zp^4
* T = Yp^4
* S = 4 * Xp * Yp^2
*
* SPECIAL CASE: when a == 3 we can compute M as
* M = 3 * (Xp^2 - Zp^4) = 3 * (Xp + Zp^2) * (Xp - Zp^2)
*/
/**
Double an ECC point
P The point to double
R [out] The destination of the double
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
return MP_OKAY on success
*/
int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif
mp_int *x, *y, *z;
int err;
if (P == NULL || R == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key != NULL) {
t1 = R->key->t1;
t2 = R->key->t2;
#ifdef ALT_ECC_SIZE
rx = R->key->x;
ry = R->key->y;
rz = R->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
/* If use ALT_ECC_SIZE we need to use local stack variable since
ecc_point x,y,z is reduced size */
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
#else
/* Use destination directly */
x = R->x;
y = R->y;
z = R->z;
#endif
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
/* T1 = Z * Z */
if (err == MP_OKAY)
err = mp_sqr(z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Z = Y * Z */
if (err == MP_OKAY)
err = mp_mul(z, y, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
/* Z = 2Z */
if (err == MP_OKAY)
err = mp_add(z, z, z);
if (err == MP_OKAY) {
if (mp_cmp(z, modulus) != MP_LT)
err = mp_sub(z, modulus, z);
}
/* Determine if curve "a" should be used in calc */
#ifdef WOLFSSL_CUSTOM_CURVES
if (err == MP_OKAY) {
/* Use a and prime to determine if a == 3 */
err = mp_submod(modulus, a, modulus, t2);
}
if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
/* use "a" in calc */
/* T2 = T1 * T1 */
if (err == MP_OKAY)
err = mp_sqr(t1, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T2 * a */
if (err == MP_OKAY)
err = mp_mulmod(t2, a, modulus, t1);
/* T2 = X * X */
if (err == MP_OKAY)
err = mp_sqr(x, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
}
else
#endif /* WOLFSSL_CUSTOM_CURVES */
{
/* assumes "a" == 3 */
(void)a;
/* T2 = X - T1 */
if (err == MP_OKAY)
err = mp_sub(x, t1, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T1 = X + T1 */
if (err == MP_OKAY)
err = mp_add(t1, x, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T2 = T1 * T2 */
if (err == MP_OKAY)
err = mp_mul(t1, t2, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = 2T2 */
if (err == MP_OKAY)
err = mp_add(t2, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T1 + T2 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
}
/* Y = 2Y */
if (err == MP_OKAY)
err = mp_add(y, y, y);
if (err == MP_OKAY) {
if (mp_cmp(y, modulus) != MP_LT)
err = mp_sub(y, modulus, y);
}
/* Y = Y * Y */
if (err == MP_OKAY)
err = mp_sqr(y, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* T2 = Y * Y */
if (err == MP_OKAY)
err = mp_sqr(y, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T2 = T2/2 */
if (err == MP_OKAY) {
if (mp_isodd(t2) == MP_YES)
err = mp_add(t2, modulus, t2);
}
if (err == MP_OKAY)
err = mp_div_2(t2, t2);
/* Y = Y * X */
if (err == MP_OKAY)
err = mp_mul(y, x, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* X = T1 * T1 */
if (err == MP_OKAY)
err = mp_sqr(t1, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* X = X - Y */
if (err == MP_OKAY)
err = mp_sub(x, y, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* X = X - Y */
if (err == MP_OKAY)
err = mp_sub(x, y, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* Y = Y - X */
if (err == MP_OKAY)
err = mp_sub(y, x, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* Y = Y * T1 */
if (err == MP_OKAY)
err = mp_mul(y, t1, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* Y = Y - T2 */
if (err == MP_OKAY)
err = mp_sub(y, t2, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
#ifdef ALT_ECC_SIZE
if (err == MP_OKAY)
err = mp_copy(x, R->x);
if (err == MP_OKAY)
err = mp_copy(y, R->y);
if (err == MP_OKAY)
err = mp_copy(z, R->z);
#endif
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || R == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
(void)a;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_proj_dbl_point_256(P->x, P->y, P->z, R->x, R->y, R->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_proj_dbl_point_384(P->x, P->y, P->z, R->x, R->y, R->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
/**
Map a projective Jacobian point back to affine space
P [in/out] The point to map
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
ct Operation should be constant time.
return MP_OKAY on success
*/
int ecc_map_ex(ecc_point* P, mp_int* modulus, mp_digit mp, int ct)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif /* WOLFSSL_SMALL_STACK */
mp_int *x, *y, *z;
int err;
(void)ct;
if (P == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
/* special case for point at infinity */
if (mp_cmp_d(P->z, 0) == MP_EQ) {
err = mp_set(P->x, 0);
if (err == MP_OKAY)
err = mp_set(P->y, 0);
if (err == MP_OKAY)
err = mp_set(P->z, 1);
return err;
}
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key != NULL) {
t1 = P->key->t1;
t2 = P->key->t2;
#ifdef ALT_ECC_SIZE
rx = P->key->x;
ry = P->key->y;
rz = P->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif /* WOLFSSL_SMALL_STACK */
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
goto done;
}
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
if (err != MP_OKAY) {
goto done;
}
#else
/* Use destination directly */
x = P->x;
y = P->y;
z = P->z;
#endif
/* get 1/z */
if (err == MP_OKAY) {
#if defined(ECC_TIMING_RESISTANT) && defined(USE_FAST_MATH)
if (ct) {
err = mp_invmod_mont_ct(z, modulus, t1, mp);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
}
else
#endif
{
/* first map z back to normal */
err = mp_montgomery_reduce(z, modulus, mp);
if (err == MP_OKAY)
err = mp_invmod(z, modulus, t1);
}
}
/* get 1/z^2 and 1/z^3 */
if (err == MP_OKAY)
err = mp_sqr(t1, t2);
if (err == MP_OKAY)
err = mp_mod(t2, modulus, t2);
if (err == MP_OKAY)
err = mp_mul(t1, t2, t1);
if (err == MP_OKAY)
err = mp_mod(t1, modulus, t1);
/* multiply against x/y */
if (err == MP_OKAY)
err = mp_mul(x, t2, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
if (err == MP_OKAY)
err = mp_mul(y, t1, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
if (err == MP_OKAY)
err = mp_set(z, 1);
#ifdef ALT_ECC_SIZE
/* return result */
if (err == MP_OKAY)
err = mp_copy(x, P->x);
if (err == MP_OKAY)
err = mp_copy(y, P->y);
if (err == MP_OKAY)
err = mp_copy(z, P->z);
done:
#endif
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_map_256(P->x, P->y, P->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_map_384(P->x, P->y, P->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
int ecc_map(ecc_point* P, mp_int* modulus, mp_digit mp)
{
return ecc_map_ex(P, modulus, mp, 0);
}
#endif /* !WOLFSSL_SP_MATH || WOLFSSL_PUBLIC_ECC_ADD_DBL */
#if !defined(FREESCALE_LTC_ECC) && !defined(WOLFSSL_STM32_PKA)
#if !defined(FP_ECC) || !defined(WOLFSSL_SP_MATH)
/**
Perform a point multiplication
k The scalar to multiply by
G The base point
R [out] Destination for kG
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
map Boolean whether to map back to affine or not
(1==map, 0 == leave in projective)
return MP_OKAY on success
*/
#ifdef FP_ECC
static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R,
mp_int* a, mp_int* modulus, int map,
void* heap)
#else
int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R,
mp_int* a, mp_int* modulus, int map,
void* heap)
#endif
{
#ifndef WOLFSSL_SP_MATH
#ifndef ECC_TIMING_RESISTANT
/* size of sliding window, don't change this! */
#define WINSIZE 4
#define M_POINTS 8
int first = 1, bitbuf = 0, bitcpy = 0, j;
#else
#define M_POINTS 4
#endif
ecc_point *tG, *M[M_POINTS];
int i, err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* mu = NULL;
#ifdef WOLFSSL_SMALL_STACK_CACHE
ecc_key key;
#endif
#else
mp_int mu[1];
#endif
mp_digit mp;
mp_digit buf;
int bitcnt = 0, mode = 0, digidx = 0;
if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* init variables */
tG = NULL;
XMEMSET(M, 0, sizeof(M));
#ifdef WOLFSSL_SMALL_STACK
mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
if (mu == NULL)
return MEMORY_E;
#endif
#ifdef WOLFSSL_SMALL_STACK_CACHE
key.t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#ifdef ALT_ECC_SIZE
key.x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#endif
if (key.t1 == NULL || key.t2 == NULL
#ifdef ALT_ECC_SIZE
|| key.x == NULL || key.y == NULL || key.z == NULL
#endif
) {
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif /* WOLFSSL_SMALL_STACK_CACHE */
/* init montgomery reduction */
if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if ((err = mp_init(mu)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if ((err = mp_montgomery_calc_normalization(mu, modulus)) != MP_OKAY) {
mp_clear(mu);
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* alloc ram for window temps */
for (i = 0; i < M_POINTS; i++) {
M[i] = wc_ecc_new_point_h(heap);
if (M[i] == NULL) {
mp_clear(mu);
err = MEMORY_E; goto exit;
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
M[i]->key = &key;
#endif
}
/* make a copy of G in case R==G */
tG = wc_ecc_new_point_h(heap);
if (tG == NULL)
err = MEMORY_E;
/* tG = G and convert to montgomery */
if (err == MP_OKAY) {
if (mp_cmp_d(mu, 1) == MP_EQ) {
err = mp_copy(G->x, tG->x);
if (err == MP_OKAY)
err = mp_copy(G->y, tG->y);
if (err == MP_OKAY)
err = mp_copy(G->z, tG->z);
} else {
err = mp_mulmod(G->x, mu, modulus, tG->x);
if (err == MP_OKAY)
err = mp_mulmod(G->y, mu, modulus, tG->y);
if (err == MP_OKAY)
err = mp_mulmod(G->z, mu, modulus, tG->z);
}
}
/* done with mu */
mp_clear(mu);
#ifdef WOLFSSL_SMALL_STACK_CACHE
R->key = &key;
#endif
#ifndef ECC_TIMING_RESISTANT
/* calc the M tab, which holds kG for k==8..15 */
/* M[0] == 8G */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(tG, M[0], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
/* now find (8+k)G for k=1..7 */
if (err == MP_OKAY)
for (j = 9; j < 16; j++) {
err = ecc_projective_add_point(M[j-9], tG, M[j-M_POINTS], a, modulus,
mp);
if (err != MP_OKAY) break;
}
/* setup sliding window */
if (err == MP_OKAY) {
mode = 0;
bitcnt = 1;
buf = 0;
digidx = get_digit_count(k) - 1;
bitcpy = bitbuf = 0;
first = 1;
/* perform ops */
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
if (digidx == -1) {
break;
}
buf = get_digit(k, digidx);
bitcnt = (int) DIGIT_BIT;
--digidx;
}
/* grab the next msb from the ltiplicand */
i = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= 1;
/* skip leading zero bits */
if (mode == 0 && i == 0)
continue;
/* if the bit is zero and mode == 1 then we double */
if (mode == 1 && i == 0) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
continue;
}
/* else we add it to the window */
bitbuf |= (i << (WINSIZE - ++bitcpy));
mode = 2;
if (bitcpy == WINSIZE) {
/* if this is the first window we do a simple copy */
if (first == 1) {
/* R = kG [k = first window] */
err = mp_copy(M[bitbuf-M_POINTS]->x, R->x);
if (err != MP_OKAY) break;
err = mp_copy(M[bitbuf-M_POINTS]->y, R->y);
if (err != MP_OKAY) break;
err = mp_copy(M[bitbuf-M_POINTS]->z, R->z);
first = 0;
} else {
/* normal window */
/* ok window is filled so double as required and add */
/* double first */
for (j = 0; j < WINSIZE; j++) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
if (err != MP_OKAY) break; /* out of first for(;;) */
/* then add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */
err = ecc_projective_add_point(R, M[bitbuf-M_POINTS], R, a,
modulus, mp);
}
if (err != MP_OKAY) break;
/* empty window and reset */
bitcpy = bitbuf = 0;
mode = 1;
}
}
}
/* if bits remain then double/add */
if (err == MP_OKAY) {
if (mode == 2 && bitcpy > 0) {
/* double then add */
for (j = 0; j < bitcpy; j++) {
/* only double if we have had at least one add first */
if (first == 0) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
bitbuf <<= 1;
if ((bitbuf & (1 << WINSIZE)) != 0) {
if (first == 1) {
/* first add, so copy */
err = mp_copy(tG->x, R->x);
if (err != MP_OKAY) break;
err = mp_copy(tG->y, R->y);
if (err != MP_OKAY) break;
err = mp_copy(tG->z, R->z);
if (err != MP_OKAY) break;
first = 0;
} else {
/* then add */
err = ecc_projective_add_point(R, tG, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
}
}
}
}
#undef WINSIZE
#else /* ECC_TIMING_RESISTANT */
/* calc the M tab */
/* M[0] == G */
if (err == MP_OKAY)
err = mp_copy(tG->x, M[0]->x);
if (err == MP_OKAY)
err = mp_copy(tG->y, M[0]->y);
if (err == MP_OKAY)
err = mp_copy(tG->z, M[0]->z);
/* M[1] == 2G */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(tG, M[1], a, modulus, mp);
#ifdef WC_NO_CACHE_RESISTANT
if (err == MP_OKAY)
err = wc_ecc_copy_point(M[0], M[2]);
#endif
/* setup sliding window */
mode = 0;
bitcnt = 1;
buf = 0;
digidx = get_digit_count(modulus) - 1;
/* The order MAY be 1 bit longer than the modulus. */
digidx += (modulus->dp[digidx] >> (DIGIT_BIT-1));
/* perform ops */
if (err == MP_OKAY) {
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
if (digidx == -1) {
break;
}
buf = get_digit(k, digidx);
bitcnt = (int)DIGIT_BIT;
--digidx;
}
/* grab the next msb from the multiplicand */
i = (buf >> (DIGIT_BIT - 1)) & 1;
buf <<= 1;
#ifdef WC_NO_CACHE_RESISTANT
if (mode == 0) {
/* timing resistant - dummy operations */
if (err == MP_OKAY)
err = ecc_projective_add_point(M[1], M[2], M[2], a, modulus,
mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[2], M[3], a, modulus, mp);
}
else {
if (err == MP_OKAY)
err = ecc_projective_add_point(M[0], M[1], M[i^1], a,
modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[i], M[i], a, modulus, mp);
}
mode |= i;
#else
if (err == MP_OKAY)
err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus,
mp);
if (err == MP_OKAY)
err = mp_copy(M[2]->x,
(mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->x & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->x & wc_off_on_addr[mode^1])) );
if (err == MP_OKAY)
err = mp_copy(M[2]->y,
(mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->y & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->y & wc_off_on_addr[mode^1])) );
if (err == MP_OKAY)
err = mp_copy(M[2]->z,
(mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->z & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->z & wc_off_on_addr[mode^1])) );
/* instead of using M[i] for double, which leaks key bit to cache
* monitor, use M[2] as temp, make sure address calc is constant,
* keep M[0] and M[1] in cache */
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[i^1]) +
((size_t)M[1]->x & wc_off_on_addr[i])),
M[2]->x);
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[i^1]) +
((size_t)M[1]->y & wc_off_on_addr[i])),
M[2]->y);
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[i^1]) +
((size_t)M[1]->z & wc_off_on_addr[i])),
M[2]->z);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[2], M[3], a, modulus, mp);
/* copy M[2] back to M[i] */
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->x & wc_off_on_addr[mode^1]) +
((size_t)M[3]->x & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[i^1]) +
((size_t)M[1]->x & wc_off_on_addr[i])) );
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->y & wc_off_on_addr[mode^1]) +
((size_t)M[3]->y & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[i^1]) +
((size_t)M[1]->y & wc_off_on_addr[i])) );
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->z & wc_off_on_addr[mode^1]) +
((size_t)M[3]->z & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[i^1]) +
((size_t)M[1]->z & wc_off_on_addr[i])) );
if (err != MP_OKAY)
break;
mode |= i;
#endif /* WC_NO_CACHE_RESISTANT */
} /* end for */
}
/* copy result out */
if (err == MP_OKAY)
err = mp_copy(M[0]->x, R->x);
if (err == MP_OKAY)
err = mp_copy(M[0]->y, R->y);
if (err == MP_OKAY)
err = mp_copy(M[0]->z, R->z);
#endif /* ECC_TIMING_RESISTANT */
/* map R back from projective space */
if (err == MP_OKAY && map)
err = ecc_map(R, modulus, mp);
exit:
/* done */
wc_ecc_del_point_h(tG, heap);
for (i = 0; i < M_POINTS; i++) {
wc_ecc_del_point_h(M[i], heap);
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
R->key = NULL;
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
#else
if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
(void)a;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_mulmod_256(k, G, R, map, heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_mulmod_384(k, G, R, map, heap);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
#endif /* !FP_ECC || !WOLFSSL_SP_MATH */
#endif /* !FREESCALE_LTC_ECC && !WOLFSSL_STM32_PKA */
/** ECC Fixed Point mulmod global
k The multiplicand
G Base point to multiply
R [out] Destination of product
a ECC curve parameter a
modulus The modulus for the curve
map [boolean] If non-zero maps the point back to affine coordinates,
otherwise it's left in jacobian-montgomery form
return MP_OKAY if successful
*/
int wc_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
mp_int* modulus, int map)
{
return wc_ecc_mulmod_ex(k, G, R, a, modulus, map, NULL);
}
#endif /* !WOLFSSL_ATECC508A */
/**
* use a heap hint when creating new ecc_point
* return an allocated point on success or NULL on failure
*/
ecc_point* wc_ecc_new_point_h(void* heap)
{
ecc_point* p;
(void)heap;
p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC);
if (p == NULL) {
return NULL;
}
XMEMSET(p, 0, sizeof(ecc_point));
#ifndef ALT_ECC_SIZE
if (mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL) != MP_OKAY) {
XFREE(p, heap, DYNAMIC_TYPE_ECC);
return NULL;
}
#else
p->x = (mp_int*)&p->xyz[0];
p->y = (mp_int*)&p->xyz[1];
p->z = (mp_int*)&p->xyz[2];
alt_fp_init(p->x);
alt_fp_init(p->y);
alt_fp_init(p->z);
#endif
return p;
}
/**
Allocate a new ECC point
return A newly allocated point or NULL on error
*/
ecc_point* wc_ecc_new_point(void)
{
return wc_ecc_new_point_h(NULL);
}
void wc_ecc_del_point_h(ecc_point* p, void* heap)
{
/* prevents free'ing null arguments */
if (p != NULL) {
mp_clear(p->x);
mp_clear(p->y);
mp_clear(p->z);
XFREE(p, heap, DYNAMIC_TYPE_ECC);
}
(void)heap;
}
/** Free an ECC point from memory
p The point to free
*/
void wc_ecc_del_point(ecc_point* p)
{
wc_ecc_del_point_h(p, NULL);
}
/** Copy the value of a point to an other one
p The point to copy
r The created point
*/
int wc_ecc_copy_point(ecc_point* p, ecc_point *r)
{
int ret;
/* prevents null arguments */
if (p == NULL || r == NULL)
return ECC_BAD_ARG_E;
ret = mp_copy(p->x, r->x);
if (ret != MP_OKAY)
return ret;
ret = mp_copy(p->y, r->y);
if (ret != MP_OKAY)
return ret;
ret = mp_copy(p->z, r->z);
if (ret != MP_OKAY)
return ret;
return MP_OKAY;
}
/** Compare the value of a point with an other one
a The point to compare
b The other point to compare
return MP_EQ if equal, MP_LT/MP_GT if not, < 0 in case of error
*/
int wc_ecc_cmp_point(ecc_point* a, ecc_point *b)
{
int ret;
/* prevents null arguments */
if (a == NULL || b == NULL)
return BAD_FUNC_ARG;
ret = mp_cmp(a->x, b->x);
if (ret != MP_EQ)
return ret;
ret = mp_cmp(a->y, b->y);
if (ret != MP_EQ)
return ret;
ret = mp_cmp(a->z, b->z);
if (ret != MP_EQ)
return ret;
return MP_EQ;
}
/** Returns whether an ECC idx is valid or not
n The idx number to check
return 1 if valid, 0 if not
*/
int wc_ecc_is_valid_idx(int n)
{
int x;
for (x = 0; ecc_sets[x].size != 0; x++)
;
/* -1 is a valid index --- indicating that the domain params
were supplied by the user */
if ((n >= ECC_CUSTOM_IDX) && (n < x)) {
return 1;
}
return 0;
}
int wc_ecc_get_curve_idx(int curve_id)
{
int curve_idx;
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (curve_id == ecc_sets[curve_idx].id)
break;
}
if (ecc_sets[curve_idx].size == 0) {
return ECC_CURVE_INVALID;
}
return curve_idx;
}
int wc_ecc_get_curve_id(int curve_idx)
{
if (wc_ecc_is_valid_idx(curve_idx)) {
return ecc_sets[curve_idx].id;
}
return ECC_CURVE_INVALID;
}
/* Returns the curve size that corresponds to a given ecc_curve_id identifier
*
* id curve id, from ecc_curve_id enum in ecc.h
* return curve size, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_size_from_id(int curve_id)
{
int curve_idx = wc_ecc_get_curve_idx(curve_id);
if (curve_idx == ECC_CURVE_INVALID)
return ECC_BAD_ARG_E;
return ecc_sets[curve_idx].size;
}
/* Returns the curve index that corresponds to a given curve name in
* ecc_sets[] of ecc.c
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve index in ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_idx_from_name(const char* curveName)
{
int curve_idx;
word32 len;
if (curveName == NULL)
return BAD_FUNC_ARG;
len = (word32)XSTRLEN(curveName);
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (
#ifndef WOLFSSL_ECC_CURVE_STATIC
ecc_sets[curve_idx].name &&
#endif
XSTRNCASECMP(ecc_sets[curve_idx].name, curveName, len) == 0) {
break;
}
}
if (ecc_sets[curve_idx].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
return ECC_CURVE_INVALID;
}
return curve_idx;
}
/* Returns the curve size that corresponds to a given curve name,
* as listed in ecc_sets[] of ecc.c.
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve size, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_size_from_name(const char* curveName)
{
int curve_idx;
if (curveName == NULL)
return BAD_FUNC_ARG;
curve_idx = wc_ecc_get_curve_idx_from_name(curveName);
if (curve_idx < 0)
return curve_idx;
return ecc_sets[curve_idx].size;
}
/* Returns the curve id that corresponds to a given curve name,
* as listed in ecc_sets[] of ecc.c.
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_name(const char* curveName)
{
int curve_idx;
if (curveName == NULL)
return BAD_FUNC_ARG;
curve_idx = wc_ecc_get_curve_idx_from_name(curveName);
if (curve_idx < 0)
return curve_idx;
return ecc_sets[curve_idx].id;
}
/* Compares a curve parameter (hex, from ecc_sets[]) to given input
* parameter for equality.
* encType is WC_TYPE_UNSIGNED_BIN or WC_TYPE_HEX_STR
* Returns MP_EQ on success, negative on error */
static int wc_ecc_cmp_param(const char* curveParam,
const byte* param, word32 paramSz, int encType)
{
int err = MP_OKAY;
#ifdef WOLFSSL_SMALL_STACK
mp_int* a = NULL;
mp_int* b = NULL;
#else
mp_int a[1], b[1];
#endif
if (param == NULL || curveParam == NULL)
return BAD_FUNC_ARG;
if (encType == WC_TYPE_HEX_STR)
return XSTRNCMP(curveParam, (char*) param, paramSz);
#ifdef WOLFSSL_SMALL_STACK
a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (a == NULL)
return MEMORY_E;
b = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (b == NULL) {
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
if ((err = mp_init_multi(a, b, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
XFREE(b, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if (err == MP_OKAY) {
err = mp_read_unsigned_bin(a, param, paramSz);
}
if (err == MP_OKAY)
err = mp_read_radix(b, curveParam, MP_RADIX_HEX);
if (err == MP_OKAY) {
if (mp_cmp(a, b) != MP_EQ) {
err = -1;
} else {
err = MP_EQ;
}
}
mp_clear(a);
mp_clear(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_ECC);
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* Returns the curve id in ecc_sets[] that corresponds to a given set of
* curve parameters.
*
* fieldSize the field size in bits
* prime prime of the finite field
* primeSz size of prime in octets
* Af first coefficient a of the curve
* AfSz size of Af in octets
* Bf second coefficient b of the curve
* BfSz size of Bf in octets
* order curve order
* orderSz size of curve in octets
* Gx affine x coordinate of base point
* GxSz size of Gx in octets
* Gy affine y coordinate of base point
* GySz size of Gy in octets
* cofactor curve cofactor
*
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_params(int fieldSize,
const byte* prime, word32 primeSz, const byte* Af, word32 AfSz,
const byte* Bf, word32 BfSz, const byte* order, word32 orderSz,
const byte* Gx, word32 GxSz, const byte* Gy, word32 GySz, int cofactor)
{
int idx;
int curveSz;
if (prime == NULL || Af == NULL || Bf == NULL || order == NULL ||
Gx == NULL || Gy == NULL)
return BAD_FUNC_ARG;
curveSz = (fieldSize + 1) / 8; /* round up */
for (idx = 0; ecc_sets[idx].size != 0; idx++) {
if (curveSz == ecc_sets[idx].size) {
if ((wc_ecc_cmp_param(ecc_sets[idx].prime, prime,
primeSz, WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Af, Af, AfSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Bf, Bf, BfSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].order, order,
orderSz, WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gx, Gx, GxSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gy, Gy, GySz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(cofactor == ecc_sets[idx].cofactor)) {
break;
}
}
}
if (ecc_sets[idx].size == 0)
return ECC_CURVE_INVALID;
return ecc_sets[idx].id;
}
/* Returns the curve id in ecc_sets[] that corresponds
* to a given domain parameters pointer.
*
* dp domain parameters pointer
*
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_dp_params(const ecc_set_type* dp)
{
int idx;
if (dp == NULL
#ifndef WOLFSSL_ECC_CURVE_STATIC
|| dp->prime == NULL || dp->Af == NULL ||
dp->Bf == NULL || dp->order == NULL || dp->Gx == NULL || dp->Gy == NULL
#endif
) {
return BAD_FUNC_ARG;
}
for (idx = 0; ecc_sets[idx].size != 0; idx++) {
if (dp->size == ecc_sets[idx].size) {
if ((wc_ecc_cmp_param(ecc_sets[idx].prime, (const byte*)dp->prime,
(word32)XSTRLEN(dp->prime), WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Af, (const byte*)dp->Af,
(word32)XSTRLEN(dp->Af),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Bf, (const byte*)dp->Bf,
(word32)XSTRLEN(dp->Bf),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].order, (const byte*)dp->order,
(word32)XSTRLEN(dp->order),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gx, (const byte*)dp->Gx,
(word32)XSTRLEN(dp->Gx),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gy, (const byte*)dp->Gy,
(word32)XSTRLEN(dp->Gy),WC_TYPE_HEX_STR) == MP_EQ) &&
(dp->cofactor == ecc_sets[idx].cofactor)) {
break;
}
}
}
if (ecc_sets[idx].size == 0)
return ECC_CURVE_INVALID;
return ecc_sets[idx].id;
}
/* Returns the curve id that corresponds to a given OID,
* as listed in ecc_sets[] of ecc.c.
*
* oid OID, from ecc_sets[].name in ecc.c
* len OID len, from ecc_sets[].name in ecc.c
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_oid(const byte* oid, word32 len)
{
int curve_idx;
if (oid == NULL)
return BAD_FUNC_ARG;
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (
#ifndef WOLFSSL_ECC_CURVE_STATIC
ecc_sets[curve_idx].oid &&
#endif
ecc_sets[curve_idx].oidSz == len &&
XMEMCMP(ecc_sets[curve_idx].oid, oid, len) == 0) {
break;
}
}
if (ecc_sets[curve_idx].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
return ECC_CURVE_INVALID;
}
return ecc_sets[curve_idx].id;
}
/* Get curve parameters using curve index */
const ecc_set_type* wc_ecc_get_curve_params(int curve_idx)
{
const ecc_set_type* ecc_set = NULL;
if (curve_idx >= 0 && curve_idx < (int)ECC_SET_COUNT) {
ecc_set = &ecc_sets[curve_idx];
}
return ecc_set;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static WC_INLINE int wc_ecc_alloc_mpint(ecc_key* key, mp_int** mp)
{
if (key == NULL || mp == NULL)
return BAD_FUNC_ARG;
if (*mp == NULL) {
*mp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_BIGINT);
if (*mp == NULL) {
return MEMORY_E;
}
XMEMSET(*mp, 0, sizeof(mp_int));
}
return 0;
}
static WC_INLINE void wc_ecc_free_mpint(ecc_key* key, mp_int** mp)
{
if (key && mp && *mp) {
mp_clear(*mp);
XFREE(*mp, key->heap, DYNAMIC_TYPE_BIGINT);
*mp = NULL;
}
}
static int wc_ecc_alloc_async(ecc_key* key)
{
int err = wc_ecc_alloc_mpint(key, &key->r);
if (err == 0)
err = wc_ecc_alloc_mpint(key, &key->s);
return err;
}
static void wc_ecc_free_async(ecc_key* key)
{
wc_ecc_free_mpint(key, &key->r);
wc_ecc_free_mpint(key, &key->s);
#ifdef HAVE_CAVIUM_V
wc_ecc_free_mpint(key, &key->e);
wc_ecc_free_mpint(key, &key->signK);
#endif /* HAVE_CAVIUM_V */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef HAVE_ECC_DHE
/**
Create an ECC shared secret between two keys
private_key The private ECC key (heap hint based off of private key)
public_key The public key
out [out] Destination of the shared secret
Conforms to EC-DH from ANSI X9.63
outlen [in/out] The max size and resulting size of the shared secret
return MP_OKAY if successful
*/
int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out,
word32* outlen)
{
int err;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
CRYS_ECDH_TempData_t tempBuff;
#endif
if (private_key == NULL || public_key == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
#ifdef WOLF_CRYPTO_CB
if (private_key->devId != INVALID_DEVID) {
err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
/* type valid? */
if (private_key->type != ECC_PRIVATEKEY &&
private_key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* Verify domain params supplied */
if (wc_ecc_is_valid_idx(private_key->idx) == 0 ||
wc_ecc_is_valid_idx(public_key->idx) == 0) {
return ECC_BAD_ARG_E;
}
/* Verify curve id matches */
if (private_key->dp->id != public_key->dp->id) {
return ECC_BAD_ARG_E;
}
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 use hardware */
if (private_key->dp->id == ECC_SECP256R1) {
err = atmel_ecc_create_pms(private_key->slot, public_key->pubkey_raw, out);
*outlen = private_key->dp->size;
}
else {
err = NOT_COMPILED_IN;
}
#elif defined(WOLFSSL_CRYPTOCELL)
/* generate a secret*/
err = CRYS_ECDH_SVDP_DH(&public_key->ctx.pubKey,
&private_key->ctx.privKey,
out,
outlen,
&tempBuff);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECDH_SVDP_DH for secret failed");
return err;
}
#else
err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen);
#endif /* WOLFSSL_ATECC508A */
return err;
}
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point,
byte* out, word32* outlen, ecc_curve_spec* curve)
{
int err;
#ifndef WOLFSSL_SP_MATH
ecc_point* result = NULL;
word32 x = 0;
#endif
mp_int* k = &private_key->k;
#ifdef HAVE_ECC_CDH
mp_int k_lcl;
/* if cofactor flag has been set */
if (private_key->flags & WC_ECC_FLAG_COFACTOR) {
mp_digit cofactor = (mp_digit)private_key->dp->cofactor;
/* only perform cofactor calc if not equal to 1 */
if (cofactor != 1) {
k = &k_lcl;
if (mp_init(k) != MP_OKAY)
return MEMORY_E;
/* multiply cofactor times private key "k" */
err = mp_mul_d(&private_key->k, cofactor, k);
if (err != MP_OKAY) {
mp_clear(k);
return err;
}
}
}
#endif
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (private_key->idx != ECC_CUSTOM_IDX &&
ecc_sets[private_key->idx].id == ECC_SECP256R1) {
err = sp_ecc_secret_gen_256(k, point, out, outlen, private_key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (private_key->idx != ECC_CUSTOM_IDX &&
ecc_sets[private_key->idx].id == ECC_SECP384R1) {
err = sp_ecc_secret_gen_384(k, point, out, outlen, private_key->heap);
}
else
#endif
#endif
#ifdef WOLFSSL_SP_MATH
{
err = WC_KEY_SIZE_E;
(void)curve;
}
#else
{
mp_digit mp = 0;
/* make new point */
result = wc_ecc_new_point_h(private_key->heap);
if (result == NULL) {
#ifdef HAVE_ECC_CDH
if (k == &k_lcl)
mp_clear(k);
#endif
return MEMORY_E;
}
/* Map in a separate call as this should be constant time */
err = wc_ecc_mulmod_ex(k, point, result, curve->Af, curve->prime, 0,
private_key->heap);
if (err == MP_OKAY) {
err = mp_montgomery_setup(curve->prime, &mp);
}
if (err == MP_OKAY) {
/* Use constant time map if compiled in */
err = ecc_map_ex(result, curve->prime, mp, 1);
}
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(curve->prime);
if (*outlen < x || (int)x < mp_unsigned_bin_size(result->x)) {
err = BUFFER_E;
}
}
if (err == MP_OKAY) {
XMEMSET(out, 0, x);
err = mp_to_unsigned_bin(result->x,out +
(x - mp_unsigned_bin_size(result->x)));
}
*outlen = x;
wc_ecc_del_point_h(result, private_key->heap);
}
#endif
#ifdef HAVE_ECC_CDH
if (k == &k_lcl)
mp_clear(k);
#endif
return err;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static int wc_ecc_shared_secret_gen_async(ecc_key* private_key,
ecc_point* point, byte* out, word32 *outlen,
ecc_curve_spec* curve)
{
int err;
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
/* verify the curve is supported by hardware */
if (NitroxEccIsCurveSupported(private_key))
#endif
{
word32 keySz = private_key->dp->size;
/* sync public key x/y */
err = wc_mp_to_bigint_sz(&private_key->k, &private_key->k.raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(point->y, &point->y->raw, keySz);
#ifdef HAVE_CAVIUM_V
/* allocate buffer for output */
if (err == MP_OKAY)
err = wc_ecc_alloc_mpint(private_key, &private_key->e);
if (err == MP_OKAY)
err = wc_bigint_alloc(&private_key->e->raw,
NitroxEccGetSize(private_key)*2);
if (err == MP_OKAY)
err = NitroxEcdh(private_key,
&private_key->k.raw, &point->x->raw, &point->y->raw,
private_key->e->raw.buf, &private_key->e->raw.len,
&curve->prime->raw);
#else
if (err == MP_OKAY)
err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF);
if (err == MP_OKAY)
err = IntelQaEcdh(&private_key->asyncDev,
&private_key->k.raw, &point->x->raw, &point->y->raw,
out, outlen,
&curve->Af->raw, &curve->Bf->raw, &curve->prime->raw,
private_key->dp->cofactor);
#endif
return err;
}
#elif defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (wc_AsyncTestInit(&private_key->asyncDev, ASYNC_TEST_ECC_SHARED_SEC)) {
WC_ASYNC_TEST* testDev = &private_key->asyncDev.test;
testDev->eccSharedSec.private_key = private_key;
testDev->eccSharedSec.public_point = point;
testDev->eccSharedSec.out = out;
testDev->eccSharedSec.outLen = outlen;
return WC_PENDING_E;
}
#endif
/* use sync in other cases */
err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve);
return err;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
int wc_ecc_shared_secret_gen(ecc_key* private_key, ecc_point* point,
byte* out, word32 *outlen)
{
int err;
DECLARE_CURVE_SPECS(curve, 2);
if (private_key == NULL || point == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
/* load curve info */
ALLOC_CURVE_SPECS(2);
err = wc_ecc_curve_load(private_key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
if (err != MP_OKAY) {
FREE_CURVE_SPECS();
return err;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
err = wc_ecc_shared_secret_gen_async(private_key, point,
out, outlen, curve);
}
else
#endif
{
err = wc_ecc_shared_secret_gen_sync(private_key, point,
out, outlen, curve);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
/**
Create an ECC shared secret between private key and public point
private_key The private ECC key (heap hint based on private key)
point The point to use (public key)
out [out] Destination of the shared secret
Conforms to EC-DH from ANSI X9.63
outlen [in/out] The max size and resulting size of the shared secret
return MP_OKAY if successful
*/
int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point,
byte* out, word32 *outlen)
{
int err;
if (private_key == NULL || point == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
/* type valid? */
if (private_key->type != ECC_PRIVATEKEY &&
private_key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* Verify domain params supplied */
if (wc_ecc_is_valid_idx(private_key->idx) == 0)
return ECC_BAD_ARG_E;
switch(private_key->state) {
case ECC_STATE_NONE:
case ECC_STATE_SHARED_SEC_GEN:
private_key->state = ECC_STATE_SHARED_SEC_GEN;
err = wc_ecc_shared_secret_gen(private_key, point, out, outlen);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_SHARED_SEC_RES:
private_key->state = ECC_STATE_SHARED_SEC_RES;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM_V
/* verify the curve is supported by hardware */
if (NitroxEccIsCurveSupported(private_key)) {
/* copy output */
*outlen = private_key->dp->size;
XMEMCPY(out, private_key->e->raw.buf, *outlen);
}
#endif /* HAVE_CAVIUM_V */
}
#endif /* WOLFSSL_ASYNC_CRYPT */
err = 0;
break;
default:
err = BAD_STATE_E;
} /* switch */
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
private_key->state++;
return err;
}
/* cleanup */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
wc_ecc_free_async(private_key);
#endif
private_key->state = ECC_STATE_NONE;
return err;
}
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
#endif /* HAVE_ECC_DHE */
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/* return 1 if point is at infinity, 0 if not, < 0 on error */
int wc_ecc_point_is_at_infinity(ecc_point* p)
{
if (p == NULL)
return BAD_FUNC_ARG;
if (get_digit_count(p->x) == 0 && get_digit_count(p->y) == 0)
return 1;
return 0;
}
/* generate random and ensure its greater than 0 and less than order */
int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
#ifndef WC_NO_RNG
int err;
byte buf[ECC_MAXSIZE_GEN];
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
ForceZero(buf, ECC_MAXSIZE);
return err;
#else
(void)rng;
(void)size;
(void)k;
(void)order;
return NOT_COMPILED_IN;
#endif /* !WC_NO_RNG */
}
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
static WC_INLINE void wc_ecc_reset(ecc_key* key)
{
/* make sure required key variables are reset */
key->state = ECC_STATE_NONE;
}
/* create the public ECC key from a private key
*
* key an initialized private key to generate public part from
* curveIn [in]curve for key, can be NULL
* pubOut [out]ecc_point holding the public key, if NULL then public key part
* is cached in key instead.
*
* Note this function is local to the file because of the argument type
* ecc_curve_spec. Having this argument allows for not having to load the
* curve type multiple times when generating a key with wc_ecc_make_key().
*
* returns MP_OKAY on success
*/
static int wc_ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn,
ecc_point* pubOut)
{
int err = MP_OKAY;
#ifndef WOLFSSL_ATECC508A
#ifndef WOLFSSL_SP_MATH
ecc_point* base = NULL;
#endif
ecc_point* pub;
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif /* !WOLFSSL_ATECC508A */
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifndef WOLFSSL_ATECC508A
/* if ecc_point passed in then use it as output for public key point */
if (pubOut != NULL) {
pub = pubOut;
}
else {
/* caching public key making it a ECC_PRIVATEKEY instead of
ECC_PRIVATEKEY_ONLY */
pub = &key->pubkey;
key->type = ECC_PRIVATEKEY_ONLY;
}
/* avoid loading the curve unless it is not passed in */
if (curveIn != NULL) {
curve = curveIn;
}
else {
/* load curve info */
if (err == MP_OKAY) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
}
if (err == MP_OKAY) {
#ifndef ALT_ECC_SIZE
err = mp_init_multi(pub->x, pub->y, pub->z, NULL, NULL, NULL);
#else
pub->x = (mp_int*)&pub->xyz[0];
pub->y = (mp_int*)&pub->xyz[1];
pub->z = (mp_int*)&pub->xyz[2];
alt_fp_init(pub->x);
alt_fp_init(pub->y);
alt_fp_init(pub->z);
#endif
}
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
if (err == MP_OKAY)
err = sp_ecc_mulmod_base_256(&key->k, pub, 1, key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
if (err == MP_OKAY)
err = sp_ecc_mulmod_base_384(&key->k, pub, 1, key->heap);
}
else
#endif
#endif
#ifdef WOLFSSL_SP_MATH
err = WC_KEY_SIZE_E;
#else
{
mp_digit mp;
if (err == MP_OKAY) {
base = wc_ecc_new_point_h(key->heap);
if (base == NULL)
err = MEMORY_E;
}
/* read in the x/y for this key */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, base->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, base->y);
if (err == MP_OKAY)
err = mp_set(base->z, 1);
/* make the public key */
if (err == MP_OKAY) {
/* Map in a separate call as this should be constant time */
err = wc_ecc_mulmod_ex(&key->k, base, pub, curve->Af, curve->prime,
0, key->heap);
if (err == MP_MEM) {
err = MEMORY_E;
}
}
if (err == MP_OKAY) {
err = mp_montgomery_setup(curve->prime, &mp);
}
if (err == MP_OKAY) {
/* Use constant time map if compiled in */
err = ecc_map_ex(pub, curve->prime, mp, 1);
}
wc_ecc_del_point_h(base, key->heap);
}
#endif
#ifdef WOLFSSL_VALIDATE_ECC_KEYGEN
/* validate the public key, order * pubkey = point at infinity */
if (err == MP_OKAY)
err = ecc_check_pubkey_order(key, pub, curve->Af, curve->prime,
curve->order);
#endif /* WOLFSSL_VALIDATE_KEYGEN */
if (err != MP_OKAY) {
/* clean up if failed */
#ifndef ALT_ECC_SIZE
mp_clear(pub->x);
mp_clear(pub->y);
mp_clear(pub->z);
#endif
}
/* free up local curve */
if (curveIn == NULL) {
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
}
#else
(void)curveIn;
err = NOT_COMPILED_IN;
#endif /* WOLFSSL_ATECC508A */
/* change key state if public part is cached */
if (key->type == ECC_PRIVATEKEY_ONLY && pubOut == NULL) {
key->type = ECC_PRIVATEKEY;
}
return err;
}
/* create the public ECC key from a private key
*
* key an initialized private key to generate public part from
* pubOut [out]ecc_point holding the public key, if NULL then public key part
* is cached in key instead.
*
*
* returns MP_OKAY on success
*/
int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut)
{
WOLFSSL_ENTER("wc_ecc_make_pub");
return wc_ecc_make_pub_ex(key, NULL, pubOut);
}
WOLFSSL_ABI
int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id)
{
int err;
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifndef WOLFSSL_SP_MATH
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif
#endif /* !WOLFSSL_ATECC508A */
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_KG_TempData_t tempBuff;
CRYS_ECPKI_KG_FipsContext_t fipsCtx;
byte ucompressed_key[ECC_MAX_CRYPTO_HW_SIZE*2 + 1];
word32 raw_size = 0;
#endif
if (key == NULL || rng == NULL) {
return BAD_FUNC_ARG;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
err = wc_ecc_set_curve(key, keysize, curve_id);
if (err != 0) {
return err;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM
/* TODO: Not implemented */
#elif defined(HAVE_INTEL_QA)
/* TODO: Not implemented */
#else
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_MAKE)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccMake.rng = rng;
testDev->eccMake.key = key;
testDev->eccMake.size = keysize;
testDev->eccMake.curve_id = curve_id;
return WC_PENDING_E;
}
#endif
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_ATECC508A
if (key->dp->id == ECC_SECP256R1) {
key->type = ECC_PRIVATEKEY;
key->slot = atmel_ecc_alloc(ATMEL_SLOT_ECDHE);
err = atmel_ecc_create_key(key->slot, key->pubkey_raw);
/* populate key->pubkey */
if (err == 0
#ifdef ALT_ECC_SIZE
&& key->pubkey.x
#endif
) {
err = mp_read_unsigned_bin(key->pubkey.x, key->pubkey_raw,
ECC_MAX_CRYPTO_HW_SIZE);
}
if (err == 0
#ifdef ALT_ECC_SIZE
&& key->pubkey.y
#endif
) {
err = mp_read_unsigned_bin(key->pubkey.y,
key->pubkey_raw + ECC_MAX_CRYPTO_HW_SIZE,
ECC_MAX_CRYPTO_HW_SIZE);
}
}
else {
err = NOT_COMPILED_IN;
}
#elif defined(WOLFSSL_CRYPTOCELL)
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
raw_size = (word32)(key->dp->size)*2 + 1;
/* generate first key pair */
err = CRYS_ECPKI_GenKeyPair(&wc_rndState,
wc_rndGenVectFunc,
pDomain,
&key->ctx.privKey,
&key->ctx.pubKey,
&tempBuff,
&fipsCtx);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_GenKeyPair for key pair failed");
return err;
}
key->type = ECC_PRIVATEKEY;
err = CRYS_ECPKI_ExportPublKey(&key->ctx.pubKey,
CRYS_EC_PointUncompressed,
&ucompressed_key[0],
&raw_size);
if (err == SA_SILIB_RET_OK && key->pubkey.x && key->pubkey.y) {
err = mp_read_unsigned_bin(key->pubkey.x,
&ucompressed_key[1], key->dp->size);
if (err == MP_OKAY) {
err = mp_read_unsigned_bin(key->pubkey.y,
&ucompressed_key[1+key->dp->size],key->dp->size);
}
}
raw_size = key->dp->size;
if (err == MP_OKAY) {
err = CRYS_ECPKI_ExportPrivKey(&key->ctx.privKey,
ucompressed_key,
&raw_size);
}
if (err == SA_SILIB_RET_OK) {
err = mp_read_unsigned_bin(&key->k, ucompressed_key, raw_size);
}
#else
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap);
if (err == MP_OKAY) {
key->type = ECC_PRIVATEKEY;
}
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_make_key_384(rng, &key->k, &key->pubkey, key->heap);
if (err == MP_OKAY) {
key->type = ECC_PRIVATEKEY;
}
}
else
#endif
#endif /* WOLFSSL_HAVE_SP_ECC */
{ /* software key gen */
#ifdef WOLFSSL_SP_MATH
err = WC_KEY_SIZE_E;
#else
/* setup the key variables */
err = mp_init(&key->k);
/* load curve info */
if (err == MP_OKAY) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
/* generate k */
if (err == MP_OKAY)
err = wc_ecc_gen_k(rng, key->dp->size, &key->k, curve->order);
/* generate public key from k */
if (err == MP_OKAY)
err = wc_ecc_make_pub_ex(key, curve, NULL);
if (err == MP_OKAY)
key->type = ECC_PRIVATEKEY;
/* cleanup these on failure case only */
if (err != MP_OKAY) {
/* clean up */
mp_forcezero(&key->k);
}
/* cleanup allocations */
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
}
#ifdef HAVE_WOLF_BIGINT
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->k, &key->k.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.x, &key->pubkey.x->raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.y, &key->pubkey.y->raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.z, &key->pubkey.z->raw);
#endif
#endif /* WOLFSSL_ATECC508A */
return err;
}
#ifdef ECC_DUMP_OID
/* Optional dump of encoded OID for adding new curves */
static int mOidDumpDone;
static void wc_ecc_dump_oids(void)
{
int x;
if (mOidDumpDone) {
return;
}
/* find matching OID sum (based on encoded value) */
for (x = 0; ecc_sets[x].size != 0; x++) {
int i;
byte* oid;
word32 oidSz, sum = 0;
printf("ECC %s (%d):\n", ecc_sets[x].name, x);
#ifdef HAVE_OID_ENCODING
byte oidEnc[ECC_MAX_OID_LEN];
oid = oidEnc;
oidSz = ECC_MAX_OID_LEN;
printf("OID: ");
for (i = 0; i < (int)ecc_sets[x].oidSz; i++) {
printf("%d.", ecc_sets[x].oid[i]);
}
printf("\n");
EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, oidEnc, &oidSz);
#else
oid = (byte*)ecc_sets[x].oid;
oidSz = ecc_sets[x].oidSz;
#endif
printf("OID Encoded: ");
for (i = 0; i < (int)oidSz; i++) {
printf("0x%02X,", oid[i]);
}
printf("\n");
for (i = 0; i < (int)oidSz; i++) {
sum += oid[i];
}
printf("Sum: %d\n", sum);
/* validate sum */
if (ecc_sets[x].oidSum != sum) {
printf(" Sum %d Not Valid!\n", ecc_sets[x].oidSum);
}
}
mOidDumpDone = 1;
}
#endif /* ECC_DUMP_OID */
WOLFSSL_ABI
ecc_key* wc_ecc_key_new(void* heap)
{
ecc_key* key;
key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC);
if (key) {
if (wc_ecc_init_ex(key, heap, INVALID_DEVID) != 0) {
XFREE(key, heap, DYNAMIC_TYPE_ECC);
key = NULL;
}
}
return key;
}
WOLFSSL_ABI
void wc_ecc_key_free(ecc_key* key)
{
if (key) {
void* heap = key->heap;
wc_ecc_free(key);
ForceZero(key, sizeof(ecc_key));
XFREE(key, heap, DYNAMIC_TYPE_ECC);
(void)heap;
}
}
/**
Make a new ECC key
rng An active RNG state
keysize The keysize for the new key (in octets from 20 to 65 bytes)
key [out] Destination of the newly created key
return MP_OKAY if successful,
upon error all allocated memory will be freed
*/
int wc_ecc_make_key(WC_RNG* rng, int keysize, ecc_key* key)
{
return wc_ecc_make_key_ex(rng, keysize, key, ECC_CURVE_DEF);
}
/* Setup dynamic pointers if using normal math for proper freeing */
WOLFSSL_ABI
int wc_ecc_init_ex(ecc_key* key, void* heap, int devId)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifdef ECC_DUMP_OID
wc_ecc_dump_oids();
#endif
XMEMSET(key, 0, sizeof(ecc_key));
key->state = ECC_STATE_NONE;
#if defined(PLUTON_CRYPTO_ECC) || defined(WOLF_CRYPTO_CB)
key->devId = devId;
#else
(void)devId;
#endif
#ifdef WOLFSSL_ATECC508A
key->slot = ATECC_INVALID_SLOT;
#else
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
ret = mp_init(&key->k);
if (ret != MP_OKAY) {
return MEMORY_E;
}
#else
ret = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z,
NULL, NULL);
if (ret != MP_OKAY) {
return MEMORY_E;
}
#endif /* ALT_ECC_SIZE */
#endif /* WOLFSSL_ATECC508A */
#ifdef WOLFSSL_HEAP_TEST
key->heap = (void*)WOLFSSL_HEAP_TEST;
#else
key->heap = heap;
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
/* handle as async */
ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC,
key->heap, devId);
#endif
#if defined(WOLFSSL_DSP)
key->handle = -1;
#endif
return ret;
}
int wc_ecc_init(ecc_key* key)
{
return wc_ecc_init_ex(key, NULL, INVALID_DEVID);
}
#ifdef HAVE_PKCS11
int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap,
int devId)
{
int ret = 0;
if (key == NULL)
ret = BAD_FUNC_ARG;
if (ret == 0 && (len < 0 || len > ECC_MAX_ID_LEN))
ret = BUFFER_E;
if (ret == 0)
ret = wc_ecc_init_ex(key, heap, devId);
if (ret == 0 && id != NULL && len != 0) {
XMEMCPY(key->id, id, len);
key->idLen = len;
}
return ret;
}
#endif
int wc_ecc_set_flags(ecc_key* key, word32 flags)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
key->flags |= flags;
return 0;
}
static int wc_ecc_get_curve_order_bit_count(const ecc_set_type* dp)
{
int err;
word32 orderBits;
DECLARE_CURVE_SPECS(curve, 1);
ALLOC_CURVE_SPECS(1);
err = wc_ecc_curve_load(dp, &curve, ECC_CURVE_FIELD_ORDER);
if (err != 0) {
FREE_CURVE_SPECS();
return err;
}
orderBits = mp_count_bits(curve->order);
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return (int)orderBits;
}
#ifdef HAVE_ECC_SIGN
#ifndef NO_ASN
#if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || \
defined(WOLFSSL_CRYPTOCELL)
static int wc_ecc_sign_hash_hw(const byte* in, word32 inlen,
mp_int* r, mp_int* s, byte* out, word32 *outlen, WC_RNG* rng,
ecc_key* key)
{
int err;
#ifdef PLUTON_CRYPTO_ECC
if (key->devId != INVALID_DEVID) /* use hardware */
#endif
{
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
CRYS_ECDSA_SignUserContext_t sigCtxTemp;
word32 raw_sig_size = *outlen;
word32 msgLenInBytes = inlen;
CRYS_ECPKI_HASH_OpMode_t hash_mode;
#endif
word32 keysize = (word32)key->dp->size;
word32 orderBits = wc_ecc_get_curve_order_bit_count(key->dp);
/* Check args */
if (keysize > ECC_MAX_CRYPTO_HW_SIZE || *outlen < keysize*2) {
return ECC_BAD_ARG_E;
}
#if defined(WOLFSSL_ATECC508A)
key->slot = atmel_ecc_alloc(ATMEL_SLOT_DEVICE);
if (key->slot == ATECC_INVALID_SLOT) {
return ECC_BAD_ARG_E;
}
/* Sign: Result is 32-bytes of R then 32-bytes of S */
err = atmel_ecc_sign(key->slot, in, out);
if (err != 0) {
return err;
}
#elif defined(PLUTON_CRYPTO_ECC)
{
/* if the input is larger than curve order, we must truncate */
if ((inlen * WOLFSSL_BIT_SIZE) > orderBits) {
inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
}
/* perform ECC sign */
word32 raw_sig_size = *outlen;
err = Crypto_EccSign(in, inlen, out, &raw_sig_size);
if (err != CRYPTO_RES_SUCCESS || raw_sig_size != keysize*2){
return BAD_COND_E;
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
hash_mode = cc310_hashModeECC(msgLenInBytes);
if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
hash_mode = cc310_hashModeECC(keysize);
hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
}
/* truncate if hash is longer than key size */
if (msgLenInBytes > keysize) {
msgLenInBytes = keysize;
}
/* create signature from an input buffer using a private key*/
err = CRYS_ECDSA_Sign(&wc_rndState,
wc_rndGenVectFunc,
&sigCtxTemp,
&key->ctx.privKey,
hash_mode,
(byte*)in,
msgLenInBytes,
out,
&raw_sig_size);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECDSA_Sign failed");
return err;
}
#endif
/* Load R and S */
err = mp_read_unsigned_bin(r, &out[0], keysize);
if (err != MP_OKAY) {
return err;
}
err = mp_read_unsigned_bin(s, &out[keysize], keysize);
if (err != MP_OKAY) {
return err;
}
/* Check for zeros */
if (mp_iszero(r) || mp_iszero(s)) {
return MP_ZERO_E;
}
}
#ifdef PLUTON_CRYPTO_ECC
else {
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
}
#endif
(void)rng;
return err;
}
#endif /* WOLFSSL_ATECC508A || PLUTON_CRYPTO_ECC || WOLFSSL_CRYPTOCELL */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static int wc_ecc_sign_hash_async(const byte* in, word32 inlen, byte* out,
word32 *outlen, WC_RNG* rng, ecc_key* key)
{
int err;
mp_int *r = NULL, *s = NULL;
if (in == NULL || out == NULL || outlen == NULL || key == NULL ||
rng == NULL) {
return ECC_BAD_ARG_E;
}
err = wc_ecc_alloc_async(key);
if (err != 0) {
return err;
}
r = key->r;
s = key->s;
switch(key->state) {
case ECC_STATE_NONE:
case ECC_STATE_SIGN_DO:
key->state = ECC_STATE_SIGN_DO;
if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){
break;
}
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_SIGN_ENCODE:
key->state = ECC_STATE_SIGN_ENCODE;
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM_V
/* Nitrox requires r and s in sep buffer, so split it */
NitroxEccRsSplit(key, &r->raw, &s->raw);
#endif
#ifndef WOLFSSL_ASYNC_CRYPT_TEST
/* only do this if not simulator, since it overwrites result */
wc_bigint_to_mp(&r->raw, r);
wc_bigint_to_mp(&s->raw, s);
#endif
}
/* encoded with DSA header */
err = StoreECC_DSA_Sig(out, outlen, r, s);
/* done with R/S */
mp_clear(r);
mp_clear(s);
break;
default:
err = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
key->state++;
return err;
}
/* cleanup */
wc_ecc_free_async(key);
key->state = ECC_STATE_NONE;
return err;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
/**
Sign a message digest
in The message digest to sign
inlen The length of the digest
out [out] The destination for the signature
outlen [in/out] The max size and resulting size of the signature
key A private ECC key
return MP_OKAY if successful
*/
WOLFSSL_ABI
int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen,
WC_RNG* rng, ecc_key* key)
{
int err;
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC)
#ifdef WOLFSSL_SMALL_STACK
mp_int *r = NULL, *s = NULL;
#else
mp_int r[1], s[1];
#endif
#endif
if (in == NULL || out == NULL || outlen == NULL || key == NULL ||
rng == NULL) {
return ECC_BAD_ARG_E;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
/* handle async cases */
err = wc_ecc_sign_hash_async(in, inlen, out, outlen, rng, key);
#else
#ifdef WOLFSSL_SMALL_STACK
r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (r == NULL)
return MEMORY_E;
s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (s == NULL) {
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
XMEMSET(r, 0, sizeof(mp_int));
XMEMSET(s, 0, sizeof(mp_int));
if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* hardware crypto */
#if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL)
err = wc_ecc_sign_hash_hw(in, inlen, r, s, out, outlen, rng, key);
#else
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
#endif
if (err < 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* encoded with DSA header */
err = StoreECC_DSA_Sig(out, outlen, r, s);
/* cleanup */
mp_clear(r);
mp_clear(s);
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif /* WOLFSSL_ASYNC_CRYPT */
return err;
}
#endif /* !NO_ASN */
#if defined(WOLFSSL_STM32_PKA)
int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng,
ecc_key* key, mp_int *r, mp_int *s)
{
return stm32_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
}
#elif !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/**
Sign a message digest
in The message digest to sign
inlen The length of the digest
key A private ECC key
r [out] The destination for r component of the signature
s [out] The destination for s component of the signature
return MP_OKAY if successful
*/
int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng,
ecc_key* key, mp_int *r, mp_int *s)
{
int err = 0;
#ifndef WOLFSSL_SP_MATH
mp_int* e;
#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)) && \
!defined(WOLFSSL_SMALL_STACK)
mp_int e_lcl;
#endif
#if defined(WOLFSSL_ECDSA_SET_K) || \
(defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
(defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)))
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#else
DECLARE_CURVE_SPECS(curve, 1);
#endif
#endif /* !WOLFSSL_SP_MATH */
if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) {
return ECC_BAD_ARG_E;
}
/* is this a private key? */
if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* is the IDX valid ? */
if (wc_ecc_is_valid_idx(key->idx) != 1) {
return ECC_BAD_ARG_E;
}
#ifdef WOLFSSL_SP_MATH
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL, key->heap);
#else
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL, key->heap);
#else
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
return WC_KEY_SIZE_E;
#else
#ifdef WOLFSSL_HAVE_SP_ECC
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
#endif
{
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL,
key->heap);
#else
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL,
key->heap);
#else
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
}
#endif /* WOLFSSL_HAVE_SP_ECC */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_SIGN)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccSign.in = in;
testDev->eccSign.inSz = inlen;
testDev->eccSign.rng = rng;
testDev->eccSign.key = key;
testDev->eccSign.r = r;
testDev->eccSign.s = s;
return WC_PENDING_E;
}
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)
err = wc_ecc_alloc_mpint(key, &key->e);
if (err != 0) {
return err;
}
e = key->e;
#elif !defined(WOLFSSL_SMALL_STACK)
e = &e_lcl;
#else
e = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (e == NULL) {
return MEMORY_E;
}
#endif
/* get the hash and load it as a bignum into 'e' */
/* init the bignums */
if ((err = mp_init(e)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(e, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* load curve info */
#if defined(WOLFSSL_ECDSA_SET_K)
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
#else
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
(defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA))
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
else
#endif
{
ALLOC_CURVE_SPECS(1);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER);
}
#endif
/* load digest into e */
if (err == MP_OKAY) {
/* we may need to truncate if hash is longer than key size */
word32 orderBits = mp_count_bits(curve->order);
/* truncate down to byte size, may be all that's needed */
if ((WOLFSSL_BIT_SIZE * inlen) > orderBits)
inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
err = mp_read_unsigned_bin(e, (byte*)in, inlen);
/* may still need bit truncation too */
if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits)
mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7));
}
/* make up a key and export the public copy */
if (err == MP_OKAY) {
int loop_check = 0;
#ifdef WOLFSSL_SMALL_STACK
ecc_key* pubkey;
#else
ecc_key pubkey[1];
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
if (NitroxEccIsCurveSupported(key))
#endif
{
word32 keySz = key->dp->size;
mp_int* k;
#ifdef HAVE_CAVIUM_V
err = wc_ecc_alloc_mpint(key, &key->signK);
if (err != 0)
return err;
k = key->signK;
#else
mp_int k_lcl;
k = &k_lcl;
#endif
err = mp_init(k);
/* make sure r and s are allocated */
#ifdef HAVE_CAVIUM_V
/* Nitrox V needs single buffer for R and S */
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2);
/* Nitrox V only needs Prime and Order */
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER));
#else
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->r->raw, key->dp->size);
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
#endif
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->s->raw, key->dp->size);
/* load e and k */
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(e, &e->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz);
if (err == MP_OKAY)
err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(k, &k->raw, keySz);
#ifdef HAVE_CAVIUM_V
if (err == MP_OKAY)
err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw,
&r->raw, &s->raw, &curve->prime->raw, &curve->order->raw);
#else
if (err == MP_OKAY)
err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw,
&k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw,
&curve->prime->raw, &curve->order->raw, &curve->Gx->raw,
&curve->Gy->raw);
#endif
#ifndef HAVE_CAVIUM_V
mp_clear(e);
mp_clear(k);
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
#endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_SMALL_STACK
pubkey = (ecc_key*)XMALLOC(sizeof(ecc_key), key->heap, DYNAMIC_TYPE_ECC);
if (pubkey == NULL)
err = MEMORY_E;
#endif
/* don't use async for key, since we don't support async return here */
if (err == MP_OKAY && (err = wc_ecc_init_ex(pubkey, key->heap,
INVALID_DEVID)) == MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* b = NULL;
#else
mp_int b[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
if (err == MP_OKAY) {
b = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
DYNAMIC_TYPE_ECC);
if (b == NULL)
err = MEMORY_E;
}
#endif
if (err == MP_OKAY) {
err = mp_init(b);
}
#ifdef WOLFSSL_CUSTOM_CURVES
/* if custom curve, apply params to pubkey */
if (err == MP_OKAY && key->idx == ECC_CUSTOM_IDX) {
err = wc_ecc_set_custom_curve(pubkey, key->dp);
}
#endif
if (err == MP_OKAY) {
/* Generate blinding value - non-zero value. */
do {
if (++loop_check > 64) {
err = RNG_FAILURE_E;
break;
}
err = wc_ecc_gen_k(rng, key->dp->size, b, curve->order);
}
while (err == MP_ZERO_E);
loop_check = 0;
}
for (; err == MP_OKAY;) {
if (++loop_check > 64) {
err = RNG_FAILURE_E;
break;
}
#ifdef WOLFSSL_ECDSA_SET_K
if (key->sign_k != NULL) {
if (loop_check > 1) {
err = RNG_FAILURE_E;
break;
}
err = mp_copy(key->sign_k, &pubkey->k);
if (err != MP_OKAY) break;
mp_forcezero(key->sign_k);
mp_free(key->sign_k);
XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC);
key->sign_k = NULL;
err = wc_ecc_make_pub_ex(pubkey, curve, NULL);
}
else
#endif
{
err = wc_ecc_make_key_ex(rng, key->dp->size, pubkey,
key->dp->id);
}
if (err != MP_OKAY) break;
/* find r = x1 mod n */
err = mp_mod(pubkey->pubkey.x, curve->order, r);
if (err != MP_OKAY) break;
if (mp_iszero(r) == MP_YES) {
#ifndef ALT_ECC_SIZE
mp_clear(pubkey->pubkey.x);
mp_clear(pubkey->pubkey.y);
mp_clear(pubkey->pubkey.z);
#endif
mp_forcezero(&pubkey->k);
}
else {
/* find s = (e + xr)/k
= b.(e/k.b + x.r/k.b) */
/* k = k.b */
err = mp_mulmod(&pubkey->k, b, curve->order, &pubkey->k);
if (err != MP_OKAY) break;
/* k = 1/k.b */
err = mp_invmod(&pubkey->k, curve->order, &pubkey->k);
if (err != MP_OKAY) break;
/* s = x.r */
err = mp_mulmod(&key->k, r, curve->order, s);
if (err != MP_OKAY) break;
/* s = x.r/k.b */
err = mp_mulmod(&pubkey->k, s, curve->order, s);
if (err != MP_OKAY) break;
/* e = e/k.b */
err = mp_mulmod(&pubkey->k, e, curve->order, e);
if (err != MP_OKAY) break;
/* s = e/k.b + x.r/k.b
= (e + x.r)/k.b */
err = mp_add(e, s, s);
if (err != MP_OKAY) break;
/* s = b.(e + x.r)/k.b
= (e + x.r)/k */
err = mp_mulmod(s, b, curve->order, s);
if (err != MP_OKAY) break;
/* s = (e + xr)/k */
err = mp_mod(s, curve->order, s);
if (err != MP_OKAY) break;
if (mp_iszero(s) == MP_NO)
break;
}
}
mp_clear(b);
mp_free(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
wc_ecc_free(pubkey);
#ifdef WOLFSSL_SMALL_STACK
XFREE(pubkey, key->heap, DYNAMIC_TYPE_ECC);
#endif
}
}
mp_clear(e);
wc_ecc_curve_free(curve);
#ifdef WOLFSSL_SMALL_STACK
XFREE(e, key->heap, DYNAMIC_TYPE_ECC);
#endif
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
return err;
}
#ifdef WOLFSSL_ECDSA_SET_K
int wc_ecc_sign_set_k(const byte* k, word32 klen, ecc_key* key)
{
int ret = 0;
if (k == NULL || klen == 0 || key == NULL) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (key->sign_k == NULL) {
key->sign_k = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
DYNAMIC_TYPE_ECC);
if (key->sign_k == NULL) {
ret = MEMORY_E;
}
}
}
if (ret == 0) {
ret = mp_init(key->sign_k);
}
if (ret == 0) {
ret = mp_read_unsigned_bin(key->sign_k, k, klen);
}
return ret;
}
#endif /* WOLFSSL_ECDSA_SET_K */
#endif /* WOLFSSL_ATECC508A && WOLFSSL_CRYPTOCELL*/
#endif /* HAVE_ECC_SIGN */
#ifdef WOLFSSL_CUSTOM_CURVES
void wc_ecc_free_curve(const ecc_set_type* curve, void* heap)
{
#ifndef WOLFSSL_ECC_CURVE_STATIC
if (curve->prime != NULL)
XFREE((void*)curve->prime, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Af != NULL)
XFREE((void*)curve->Af, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Bf != NULL)
XFREE((void*)curve->Bf, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->order != NULL)
XFREE((void*)curve->order, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Gx != NULL)
XFREE((void*)curve->Gx, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Gy != NULL)
XFREE((void*)curve->Gy, heap, DYNAMIC_TYPE_ECC_BUFFER);
#endif
XFREE((void*)curve, heap, DYNAMIC_TYPE_ECC_BUFFER);
(void)heap;
}
#endif /* WOLFSSL_CUSTOM_CURVES */
/**
Free an ECC key from memory
key The key you wish to free
*/
WOLFSSL_ABI
int wc_ecc_free(ecc_key* key)
{
if (key == NULL) {
return 0;
}
#ifdef WOLFSSL_ECDSA_SET_K
if (key->sign_k != NULL) {
mp_forcezero(key->sign_k);
mp_free(key->sign_k);
XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC);
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
#ifdef WC_ASYNC_ENABLE_ECC
wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC);
#endif
wc_ecc_free_async(key);
#endif
#ifdef WOLFSSL_ATECC508A
atmel_ecc_free(key->slot);
key->slot = ATECC_INVALID_SLOT;
#endif /* WOLFSSL_ATECC508A */
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_forcezero(&key->k);
#ifdef WOLFSSL_CUSTOM_CURVES
if (key->deallocSet && key->dp != NULL)
wc_ecc_free_curve(key->dp, key->heap);
#endif
return 0;
}
#if !defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifdef ECC_SHAMIR
/** Computes kA*A + kB*B = C using Shamir's Trick
A First point to multiply
kA What to multiple A by
B Second point to multiply
kB What to multiple B by
C [out] Destination point (can overlap with A or B)
a ECC curve parameter a
modulus Modulus for curve
return MP_OKAY on success
*/
#ifdef FP_ECC
static int normal_ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus,
void* heap)
#else
int ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus,
void* heap)
#endif
{
#ifdef WOLFSSL_SMALL_STACK
ecc_point** precomp = NULL;
#ifdef WOLFSSL_SMALL_STACK_CACHE
ecc_key key;
#endif
#else
ecc_point* precomp[SHAMIR_PRECOMP_SZ];
#endif
unsigned bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble;
unsigned char* tA;
unsigned char* tB;
int err = MP_OKAY, first, x, y;
mp_digit mp = 0;
/* argchks */
if (A == NULL || kA == NULL || B == NULL || kB == NULL || C == NULL ||
modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* allocate memory */
tA = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (tA == NULL) {
return GEN_MEM_ERR;
}
tB = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (tB == NULL) {
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return GEN_MEM_ERR;
}
#ifdef WOLFSSL_SMALL_STACK
precomp = (ecc_point**)XMALLOC(sizeof(ecc_point*) * SHAMIR_PRECOMP_SZ, heap,
DYNAMIC_TYPE_ECC_BUFFER);
if (precomp == NULL) {
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return GEN_MEM_ERR;
}
#endif
#ifdef WOLFSSL_SMALL_STACK_CACHE
key.t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#ifdef ALT_ECC_SIZE
key.x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#endif
if (key.t1 == NULL || key.t2 == NULL
#ifdef ALT_ECC_SIZE
|| key.x == NULL || key.y == NULL || key.z == NULL
#endif
) {
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
XFREE(precomp, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
C->key = &key;
#endif /* WOLFSSL_SMALL_STACK_CACHE */
/* init variables */
XMEMSET(tA, 0, ECC_BUFSIZE);
XMEMSET(tB, 0, ECC_BUFSIZE);
#ifndef WOLFSSL_SMALL_STACK
XMEMSET(precomp, 0, sizeof(precomp));
#else
XMEMSET(precomp, 0, sizeof(ecc_point*) * SHAMIR_PRECOMP_SZ);
#endif
/* get sizes */
lenA = mp_unsigned_bin_size(kA);
lenB = mp_unsigned_bin_size(kB);
len = MAX(lenA, lenB);
/* sanity check */
if ((lenA > ECC_BUFSIZE) || (lenB > ECC_BUFSIZE)) {
err = BAD_FUNC_ARG;
}
if (err == MP_OKAY) {
/* extract and justify kA */
err = mp_to_unsigned_bin(kA, (len - lenA) + tA);
/* extract and justify kB */
if (err == MP_OKAY)
err = mp_to_unsigned_bin(kB, (len - lenB) + tB);
/* allocate the table */
if (err == MP_OKAY) {
for (x = 0; x < SHAMIR_PRECOMP_SZ; x++) {
precomp[x] = wc_ecc_new_point_h(heap);
if (precomp[x] == NULL) {
err = GEN_MEM_ERR;
break;
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
precomp[x]->key = &key;
#endif
}
}
}
if (err == MP_OKAY)
/* init montgomery reduction */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* mu;
#else
mp_int mu[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
if (mu == NULL)
err = MEMORY_E;
#endif
if (err == MP_OKAY) {
err = mp_init(mu);
}
if (err == MP_OKAY) {
err = mp_montgomery_calc_normalization(mu, modulus);
if (err == MP_OKAY)
/* copy ones ... */
err = mp_mulmod(A->x, mu, modulus, precomp[1]->x);
if (err == MP_OKAY)
err = mp_mulmod(A->y, mu, modulus, precomp[1]->y);
if (err == MP_OKAY)
err = mp_mulmod(A->z, mu, modulus, precomp[1]->z);
if (err == MP_OKAY)
err = mp_mulmod(B->x, mu, modulus, precomp[1<<2]->x);
if (err == MP_OKAY)
err = mp_mulmod(B->y, mu, modulus, precomp[1<<2]->y);
if (err == MP_OKAY)
err = mp_mulmod(B->z, mu, modulus, precomp[1<<2]->z);
/* done with mu */
mp_clear(mu);
}
#ifdef WOLFSSL_SMALL_STACK
if (mu != NULL) {
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
}
#endif
}
if (err == MP_OKAY)
/* precomp [i,0](A + B) table */
err = ecc_projective_dbl_point(precomp[1], precomp[2], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_add_point(precomp[1], precomp[2], precomp[3],
a, modulus, mp);
if (err == MP_OKAY)
/* precomp [0,i](A + B) table */
err = ecc_projective_dbl_point(precomp[1<<2], precomp[2<<2], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_add_point(precomp[1<<2], precomp[2<<2], precomp[3<<2],
a, modulus, mp);
if (err == MP_OKAY) {
/* precomp [i,j](A + B) table (i != 0, j != 0) */
for (x = 1; x < 4; x++) {
for (y = 1; y < 4; y++) {
if (err == MP_OKAY) {
err = ecc_projective_add_point(precomp[x], precomp[(y<<2)],
precomp[x+(y<<2)], a, modulus, mp);
}
}
}
}
if (err == MP_OKAY) {
nibble = 3;
first = 1;
bitbufA = tA[0];
bitbufB = tB[0];
/* for every byte of the multiplicands */
for (x = 0;; ) {
/* grab a nibble */
if (++nibble == 4) {
if (x == (int)len) break;
bitbufA = tA[x];
bitbufB = tB[x];
nibble = 0;
x++;
}
/* extract two bits from both, shift/update */
nA = (bitbufA >> 6) & 0x03;
nB = (bitbufB >> 6) & 0x03;
bitbufA = (bitbufA << 2) & 0xFF;
bitbufB = (bitbufB << 2) & 0xFF;
/* if both zero, if first, continue */
if ((nA == 0) && (nB == 0) && (first == 1)) {
continue;
}
/* double twice, only if this isn't the first */
if (first == 0) {
/* double twice */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(C, C, a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(C, C, a, modulus, mp);
else
break;
}
/* if not both zero */
if ((nA != 0) || (nB != 0)) {
if (first == 1) {
/* if first, copy from table */
first = 0;
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->x, C->x);
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->y, C->y);
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->z, C->z);
else
break;
} else {
/* if not first, add from table */
if (err == MP_OKAY)
err = ecc_projective_add_point(C, precomp[nA + (nB<<2)], C,
a, modulus, mp);
if (err != MP_OKAY)
break;
if (mp_iszero(C->z)) {
/* When all zero then should have done an add */
if (mp_iszero(C->x) && mp_iszero(C->y)) {
err = ecc_projective_dbl_point(precomp[nA + (nB<<2)], C,
a, modulus, mp);
if (err != MP_OKAY)
break;
}
/* When only Z zero then result is infinity */
else {
err = mp_set(C->x, 0);
if (err != MP_OKAY)
break;
err = mp_set(C->y, 0);
if (err != MP_OKAY)
break;
err = mp_set(C->z, 1);
if (err != MP_OKAY)
break;
first = 1;
}
}
}
}
}
}
/* reduce to affine */
if (err == MP_OKAY)
err = ecc_map(C, modulus, mp);
/* clean up */
for (x = 0; x < SHAMIR_PRECOMP_SZ; x++) {
wc_ecc_del_point_h(precomp[x], heap);
}
ForceZero(tA, ECC_BUFSIZE);
ForceZero(tB, ECC_BUFSIZE);
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
C->key = NULL;
#endif
#ifdef WOLFSSL_SMALL_STACK
XFREE(precomp, heap, DYNAMIC_TYPE_ECC_BUFFER);
#endif
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return err;
}
#endif /* ECC_SHAMIR */
#endif /* !WOLFSSL_SP_MATH && !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCEL*/
#ifdef HAVE_ECC_VERIFY
#ifndef NO_ASN
/* verify
*
* w = s^-1 mod n
* u1 = xw
* u2 = rw
* X = u1*G + u2*Q
* v = X_x1 mod n
* accept if v == r
*/
/**
Verify an ECC signature
sig The signature to verify
siglen The length of the signature (octets)
hash The hash (message digest) that was signed
hashlen The length of the hash (octets)
res Result of signature, 1==valid, 0==invalid
key The corresponding public ECC key
return MP_OKAY if successful (even if the signature is not valid)
*/
int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash,
word32 hashlen, int* res, ecc_key* key)
{
int err;
mp_int *r = NULL, *s = NULL;
#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC)) && \
!defined(WOLFSSL_SMALL_STACK)
mp_int r_lcl, s_lcl;
#endif
if (sig == NULL || hash == NULL || res == NULL || key == NULL) {
return ECC_BAD_ARG_E;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
err = wc_ecc_alloc_async(key);
if (err != 0)
return err;
r = key->r;
s = key->s;
#else
#ifndef WOLFSSL_SMALL_STACK
r = &r_lcl;
s = &s_lcl;
#else
r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (r == NULL)
return MEMORY_E;
s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (s == NULL) {
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
XMEMSET(r, 0, sizeof(mp_int));
XMEMSET(s, 0, sizeof(mp_int));
#endif /* WOLFSSL_ASYNC_CRYPT */
switch (key->state) {
case ECC_STATE_NONE:
case ECC_STATE_VERIFY_DECODE:
key->state = ECC_STATE_VERIFY_DECODE;
/* default to invalid signature */
*res = 0;
/* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s.
* If either of those don't allocate correctly, none of
* the rest of this function will execute, and everything
* gets cleaned up at the end. */
/* decode DSA header */
err = DecodeECC_DSA_Sig(sig, siglen, r, s);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_VERIFY_DO:
key->state = ECC_STATE_VERIFY_DO;
err = wc_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
#ifndef WOLFSSL_ASYNC_CRYPT
/* done with R/S */
mp_clear(r);
mp_clear(s);
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
r = NULL;
s = NULL;
#endif
#endif
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_VERIFY_RES:
key->state = ECC_STATE_VERIFY_RES;
err = 0;
break;
default:
err = BAD_STATE_E;
}
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
key->state++;
return err;
}
/* cleanup */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
wc_ecc_free_async(key);
#elif defined(WOLFSSL_SMALL_STACK)
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
r = NULL;
s = NULL;
#endif
key->state = ECC_STATE_NONE;
return err;
}
#endif /* !NO_ASN */
/**
Verify an ECC signature
r The signature R component to verify
s The signature S component to verify
hash The hash (message digest) that was signed
hashlen The length of the hash (octets)
res Result of signature, 1==valid, 0==invalid
key The corresponding public ECC key
return MP_OKAY if successful (even if the signature is not valid)
*/
int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash,
word32 hashlen, int* res, ecc_key* key)
#if defined(WOLFSSL_STM32_PKA)
{
return stm32_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
}
#else
{
int err;
word32 keySz;
#ifdef WOLFSSL_ATECC508A
byte sigRS[ATECC_KEY_SIZE*2];
#elif defined(WOLFSSL_CRYPTOCELL)
byte sigRS[ECC_MAX_CRYPTO_HW_SIZE*2];
CRYS_ECDSA_VerifyUserContext_t sigCtxTemp;
word32 msgLenInBytes = hashlen;
CRYS_ECPKI_HASH_OpMode_t hash_mode;
#elif !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC)
int did_init = 0;
ecc_point *mG = NULL, *mQ = NULL;
#ifdef WOLFSSL_SMALL_STACK
mp_int* v = NULL;
mp_int* w = NULL;
mp_int* u1 = NULL;
mp_int* u2 = NULL;
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
mp_int* e_lcl = NULL;
#endif
#else /* WOLFSSL_SMALL_STACK */
mp_int v[1];
mp_int w[1];
mp_int u1[1];
mp_int u2[1];
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
mp_int e_lcl[1];
#endif
#endif /* WOLFSSL_SMALL_STACK */
mp_int* e;
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif
if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL)
return ECC_BAD_ARG_E;
/* default to invalid signature */
*res = 0;
/* is the IDX valid ? */
if (wc_ecc_is_valid_idx(key->idx) != 1) {
return ECC_BAD_ARG_E;
}
keySz = key->dp->size;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_VERIFY)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccVerify.r = r;
testDev->eccVerify.s = s;
testDev->eccVerify.hash = hash;
testDev->eccVerify.hashlen = hashlen;
testDev->eccVerify.stat = res;
testDev->eccVerify.key = key;
return WC_PENDING_E;
}
}
#endif
#ifdef WOLFSSL_ATECC508A
/* Extract R and S */
err = mp_to_unsigned_bin(r, &sigRS[0]);
if (err != MP_OKAY) {
return err;
}
err = mp_to_unsigned_bin(s, &sigRS[keySz]);
if (err != MP_OKAY) {
return err;
}
err = atmel_ecc_verify(hash, sigRS, key->pubkey_raw, res);
if (err != 0) {
return err;
}
(void)hashlen;
#elif defined(WOLFSSL_CRYPTOCELL)
/* Extract R and S */
err = mp_to_unsigned_bin(r, &sigRS[0]);
if (err != MP_OKAY) {
return err;
}
err = mp_to_unsigned_bin(s, &sigRS[keySz]);
if (err != MP_OKAY) {
return err;
}
hash_mode = cc310_hashModeECC(msgLenInBytes);
if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
/* hash_mode = */ cc310_hashModeECC(keySz);
hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
}
/* truncate if hash is longer than key size */
if (msgLenInBytes > keySz) {
msgLenInBytes = keySz;
}
/* verify the signature using the public key */
err = CRYS_ECDSA_Verify(&sigCtxTemp,
&key->ctx.pubKey,
hash_mode,
&sigRS[0],
keySz*2,
(byte*)hash,
msgLenInBytes);
if (err != SA_SILIB_RET_OK) {
WOLFSSL_MSG("CRYS_ECDSA_Verify failed");
return err;
}
/* valid signature if we get to this point */
*res = 1;
#else
/* checking if private key with no public part */
if (key->type == ECC_PRIVATEKEY_ONLY) {
WOLFSSL_MSG("Verify called with private key, generating public part");
err = wc_ecc_make_pub_ex(key, NULL, NULL);
if (err != MP_OKAY) {
WOLFSSL_MSG("Unable to extract public key");
return err;
}
}
#if defined(WOLFSSL_DSP) && !defined(FREESCALE_LTC_ECC)
if (key->handle != -1) {
return sp_dsp_ecc_verify_256(key->handle, hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
if (wolfSSL_GetHandleCbSet() == 1) {
return sp_dsp_ecc_verify_256(0, hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
#if defined(WOLFSSL_SP_MATH) && !defined(FREESCALE_LTC_ECC)
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
return sp_ecc_verify_384(hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
return WC_KEY_SIZE_E;
#else
#if defined WOLFSSL_HAVE_SP_ECC && !defined(FREESCALE_LTC_ECC)
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
#endif
{
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
return sp_ecc_verify_256(hash, hashlen, key->pubkey.x,
key->pubkey.y, key->pubkey.z,r, s, res,
key->heap);
}
#endif /* WOLFSSL_SP_NO_256 */
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
return sp_ecc_verify_384(hash, hashlen, key->pubkey.x,
key->pubkey.y, key->pubkey.z,r, s, res,
key->heap);
}
#endif /* WOLFSSL_SP_384 */
}
#endif /* WOLFSSL_HAVE_SP_ECC */
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)
err = wc_ecc_alloc_mpint(key, &key->e);
if (err != 0) {
FREE_CURVE_SPECS();
return err;
}
e = key->e;
#else
#ifdef WOLFSSL_SMALL_STACK
e_lcl = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (e_lcl == NULL) {
FREE_CURVE_SPECS();
return MEMORY_E;
}
#endif
e = e_lcl;
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_CAVIUM_V */
err = mp_init(e);
if (err != MP_OKAY)
return MEMORY_E;
/* read in the specs for this curve */
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
/* check for zero */
if (err == MP_OKAY) {
if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES ||
mp_cmp(r, curve->order) != MP_LT ||
mp_cmp(s, curve->order) != MP_LT) {
err = MP_ZERO_E;
}
}
/* read hash */
if (err == MP_OKAY) {
/* we may need to truncate if hash is longer than key size */
unsigned int orderBits = mp_count_bits(curve->order);
/* truncate down to byte size, may be all that's needed */
if ( (WOLFSSL_BIT_SIZE * hashlen) > orderBits)
hashlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
err = mp_read_unsigned_bin(e, hash, hashlen);
/* may still need bit truncation too */
if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * hashlen) > orderBits)
mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7));
}
/* check for async hardware acceleration */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
if (NitroxEccIsCurveSupported(key))
#endif
{
err = wc_mp_to_bigint_sz(e, &e->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(key->pubkey.x, &key->pubkey.x->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(key->pubkey.y, &key->pubkey.y->raw, keySz);
if (err == MP_OKAY)
#ifdef HAVE_CAVIUM_V
err = NitroxEcdsaVerify(key, &e->raw, &key->pubkey.x->raw,
&key->pubkey.y->raw, &r->raw, &s->raw,
&curve->prime->raw, &curve->order->raw, res);
#else
err = IntelQaEcdsaVerify(&key->asyncDev, &e->raw, &key->pubkey.x->raw,
&key->pubkey.y->raw, &r->raw, &s->raw, &curve->Af->raw,
&curve->Bf->raw, &curve->prime->raw, &curve->order->raw,
&curve->Gx->raw, &curve->Gy->raw, res);
#endif
#ifndef HAVE_CAVIUM_V
mp_clear(e);
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
#endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_SMALL_STACK
if (err == MP_OKAY) {
v = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (v == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
w = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (w == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
u1 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (u1 == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
u2 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (u2 == NULL)
err = MEMORY_E;
}
#endif
/* allocate ints */
if (err == MP_OKAY) {
if ((err = mp_init_multi(v, w, u1, u2, NULL, NULL)) != MP_OKAY) {
err = MEMORY_E;
}
did_init = 1;
}
/* allocate points */
if (err == MP_OKAY) {
mG = wc_ecc_new_point_h(key->heap);
mQ = wc_ecc_new_point_h(key->heap);
if (mQ == NULL || mG == NULL)
err = MEMORY_E;
}
/* w = s^-1 mod n */
if (err == MP_OKAY)
err = mp_invmod(s, curve->order, w);
/* u1 = ew */
if (err == MP_OKAY)
err = mp_mulmod(e, w, curve->order, u1);
/* u2 = rw */
if (err == MP_OKAY)
err = mp_mulmod(r, w, curve->order, u2);
/* find mG and mQ */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, mG->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, mG->y);
if (err == MP_OKAY)
err = mp_set(mG->z, 1);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.x, mQ->x);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.y, mQ->y);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.z, mQ->z);
#if defined(FREESCALE_LTC_ECC)
/* use PKHA to compute u1*mG + u2*mQ */
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0, key->heap);
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap);
if (err == MP_OKAY)
err = wc_ecc_point_add(mG, mQ, mG, curve->prime);
#else
#ifndef ECC_SHAMIR
if (err == MP_OKAY)
{
mp_digit mp = 0;
if (!mp_iszero(u1)) {
/* compute u1*mG + u2*mQ = mG */
err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0,
key->heap);
if (err == MP_OKAY) {
err = wc_ecc_mulmod_ex(u2, mQ, mQ, curve->Af, curve->prime, 0,
key->heap);
}
/* find the montgomery mp */
if (err == MP_OKAY)
err = mp_montgomery_setup(curve->prime, &mp);
/* add them */
if (err == MP_OKAY)
err = ecc_projective_add_point(mQ, mG, mG, curve->Af,
curve->prime, mp);
if (err == MP_OKAY && mp_iszero(mG->z)) {
/* When all zero then should have done an add */
if (mp_iszero(mG->x) && mp_iszero(mG->y)) {
err = ecc_projective_dbl_point(mQ, mG, curve->Af,
curve->prime, mp);
}
/* When only Z zero then result is infinity */
else {
err = mp_set(mG->x, 0);
if (err == MP_OKAY)
err = mp_set(mG->y, 0);
if (err == MP_OKAY)
err = mp_set(mG->z, 1);
}
}
}
else {
/* compute 0*mG + u2*mQ = mG */
err = wc_ecc_mulmod_ex(u2, mQ, mG, curve->Af, curve->prime, 0,
key->heap);
/* find the montgomery mp */
if (err == MP_OKAY)
err = mp_montgomery_setup(curve->prime, &mp);
}
/* reduce */
if (err == MP_OKAY)
err = ecc_map(mG, curve->prime, mp);
}
#else
/* use Shamir's trick to compute u1*mG + u2*mQ using half the doubles */
if (err == MP_OKAY) {
err = ecc_mul2add(mG, u1, mQ, u2, mG, curve->Af, curve->prime,
key->heap);
}
#endif /* ECC_SHAMIR */
#endif /* FREESCALE_LTC_ECC */
/* v = X_x1 mod n */
if (err == MP_OKAY)
err = mp_mod(mG->x, curve->order, v);
/* does v == r */
if (err == MP_OKAY) {
if (mp_cmp(v, r) == MP_EQ)
*res = 1;
}
/* cleanup */
wc_ecc_del_point_h(mG, key->heap);
wc_ecc_del_point_h(mQ, key->heap);
mp_clear(e);
if (did_init) {
mp_clear(v);
mp_clear(w);
mp_clear(u1);
mp_clear(u2);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(u2, key->heap, DYNAMIC_TYPE_ECC);
XFREE(u1, key->heap, DYNAMIC_TYPE_ECC);
XFREE(w, key->heap, DYNAMIC_TYPE_ECC);
XFREE(v, key->heap, DYNAMIC_TYPE_ECC);
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
XFREE(e_lcl, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
#endif /* WOLFSSL_ATECC508A */
(void)keySz;
(void)hashlen;
return err;
}
#endif /* WOLFSSL_STM32_PKA */
#endif /* HAVE_ECC_VERIFY */
#ifdef HAVE_ECC_KEY_IMPORT
/* import point from der */
int wc_ecc_import_point_der(byte* in, word32 inLen, const int curve_idx,
ecc_point* point)
{
int err = 0;
int compressed = 0;
int keysize;
byte pointType;
if (in == NULL || point == NULL || (curve_idx < 0) ||
(wc_ecc_is_valid_idx(curve_idx) == 0))
return ECC_BAD_ARG_E;
/* must be odd */
if ((inLen & 1) == 0) {
return ECC_BAD_ARG_E;
}
/* init point */
#ifdef ALT_ECC_SIZE
point->x = (mp_int*)&point->xyz[0];
point->y = (mp_int*)&point->xyz[1];
point->z = (mp_int*)&point->xyz[2];
alt_fp_init(point->x);
alt_fp_init(point->y);
alt_fp_init(point->z);
#else
err = mp_init_multi(point->x, point->y, point->z, NULL, NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* check for point type (4, 2, or 3) */
pointType = in[0];
if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN &&
pointType != ECC_POINT_COMP_ODD) {
err = ASN_PARSE_E;
}
if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) {
#ifdef HAVE_COMP_KEY
compressed = 1;
#else
err = NOT_COMPILED_IN;
#endif
}
/* adjust to skip first byte */
inLen -= 1;
in += 1;
/* calculate key size based on inLen / 2 */
keysize = inLen>>1;
/* read data */
if (err == MP_OKAY)
err = mp_read_unsigned_bin(point->x, (byte*)in, keysize);
#ifdef HAVE_COMP_KEY
if (err == MP_OKAY && compressed == 1) { /* build y */
#ifndef WOLFSSL_SP_MATH
int did_init = 0;
mp_int t1, t2;
DECLARE_CURVE_SPECS(curve, 3);
ALLOC_CURVE_SPECS(3);
if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
err = MEMORY_E;
else
did_init = 1;
/* load curve info */
if (err == MP_OKAY)
err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
ECC_CURVE_FIELD_BF));
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(point->x, &t1);
if (err == MP_OKAY)
err = mp_mulmod(&t1, point->x, curve->prime, &t1);
/* compute x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(curve->Af, point->x, curve->prime, &t2);
if (err == MP_OKAY)
err = mp_add(&t1, &t2, &t1);
/* compute x^3 + a*x + b */
if (err == MP_OKAY)
err = mp_add(&t1, curve->Bf, &t1);
/* compute sqrt(x^3 + a*x + b) */
if (err == MP_OKAY)
err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
/* adjust y */
if (err == MP_OKAY) {
if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
(mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) {
err = mp_mod(&t2, curve->prime, point->y);
}
else {
err = mp_submod(curve->prime, &t2, curve->prime, point->y);
}
}
if (did_init) {
mp_clear(&t2);
mp_clear(&t1);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#else
#ifndef WOLFSSL_SP_NO_256
if (curve_idx != ECC_CUSTOM_IDX &&
ecc_sets[curve_idx].id == ECC_SECP256R1) {
sp_ecc_uncompress_256(point->x, pointType, point->y);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (curve_idx != ECC_CUSTOM_IDX &&
ecc_sets[curve_idx].id == ECC_SECP384R1) {
sp_ecc_uncompress_384(point->x, pointType, point->y);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
}
#endif
if (err == MP_OKAY && compressed == 0)
err = mp_read_unsigned_bin(point->y, (byte*)in + keysize, keysize);
if (err == MP_OKAY)
err = mp_set(point->z, 1);
if (err != MP_OKAY) {
mp_clear(point->x);
mp_clear(point->y);
mp_clear(point->z);
}
return err;
}
#endif /* HAVE_ECC_KEY_IMPORT */
#ifdef HAVE_ECC_KEY_EXPORT
/* export point to der */
int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out,
word32* outLen)
{
int ret = MP_OKAY;
word32 numlen;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_BUFSIZE];
#endif
if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0))
return ECC_BAD_ARG_E;
/* return length needed only */
if (point != NULL && out == NULL && outLen != NULL) {
numlen = ecc_sets[curve_idx].size;
*outLen = 1 + 2*numlen;
return LENGTH_ONLY_E;
}
if (point == NULL || out == NULL || outLen == NULL)
return ECC_BAD_ARG_E;
numlen = ecc_sets[curve_idx].size;
if (*outLen < (1 + 2*numlen)) {
*outLen = 1 + 2*numlen;
return BUFFER_E;
}
/* store byte point type */
out[0] = ECC_POINT_UNCOMP;
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/* pad and store x */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(point->x, buf +
(numlen - mp_unsigned_bin_size(point->x)));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1, buf, numlen);
/* pad and store y */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(point->y, buf +
(numlen - mp_unsigned_bin_size(point->y)));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1+numlen, buf, numlen);
*outLen = 1 + 2*numlen;
done:
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* export public ECC key in ANSI X9.63 format */
int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen)
{
int ret = MP_OKAY;
word32 numlen;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_BUFSIZE];
#endif
word32 pubxlen, pubylen;
/* return length needed only */
if (key != NULL && out == NULL && outLen != NULL) {
/* if key hasn't been setup assume max bytes for size estimation */
numlen = key->dp ? key->dp->size : MAX_ECC_BYTES;
*outLen = 1 + 2*numlen;
return LENGTH_ONLY_E;
}
if (key == NULL || out == NULL || outLen == NULL)
return ECC_BAD_ARG_E;
if (key->type == ECC_PRIVATEKEY_ONLY)
return ECC_PRIVATEONLY_E;
if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) {
return ECC_BAD_ARG_E;
}
numlen = key->dp->size;
/* verify room in out buffer */
if (*outLen < (1 + 2*numlen)) {
*outLen = 1 + 2*numlen;
return BUFFER_E;
}
/* verify public key length is less than key size */
pubxlen = mp_unsigned_bin_size(key->pubkey.x);
pubylen = mp_unsigned_bin_size(key->pubkey.y);
if ((pubxlen > numlen) || (pubylen > numlen)) {
WOLFSSL_MSG("Public key x/y invalid!");
return BUFFER_E;
}
/* store byte point type */
out[0] = ECC_POINT_UNCOMP;
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/* pad and store x */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - pubxlen));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1, buf, numlen);
/* pad and store y */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - pubylen));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1+numlen, buf, numlen);
*outLen = 1 + 2*numlen;
done:
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* export public ECC key in ANSI X9.63 format, extended with
* compression option */
int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen,
int compressed)
{
if (compressed == 0)
return wc_ecc_export_x963(key, out, outLen);
#ifdef HAVE_COMP_KEY
else
return wc_ecc_export_x963_compressed(key, out, outLen);
#else
return NOT_COMPILED_IN;
#endif
}
#endif /* HAVE_ECC_KEY_EXPORT */
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/* is ecc point on curve described by dp ? */
int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime)
{
#ifndef WOLFSSL_SP_MATH
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1;
mp_int* t2;
#else
mp_int t1[1], t2[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL)
return MEMORY_E;
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t2 == NULL) {
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* compute y^2 */
if (err == MP_OKAY)
err = mp_sqr(ecp->y, t1);
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(ecp->x, t2);
if (err == MP_OKAY)
err = mp_mod(t2, prime, t2);
if (err == MP_OKAY)
err = mp_mul(ecp->x, t2, t2);
/* compute y^2 - x^3 */
if (err == MP_OKAY)
err = mp_sub(t1, t2, t1);
/* Determine if curve "a" should be used in calc */
#ifdef WOLFSSL_CUSTOM_CURVES
if (err == MP_OKAY) {
/* Use a and prime to determine if a == 3 */
err = mp_set(t2, 0);
if (err == MP_OKAY)
err = mp_submod(prime, a, prime, t2);
}
if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
/* compute y^2 - x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(t2, ecp->x, prime, t2);
if (err == MP_OKAY)
err = mp_addmod(t1, t2, prime, t1);
}
else
#endif /* WOLFSSL_CUSTOM_CURVES */
{
/* assumes "a" == 3 */
(void)a;
/* compute y^2 - x^3 + 3x */
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_mod(t1, prime, t1);
}
/* adjust range (0, prime) */
while (err == MP_OKAY && mp_isneg(t1)) {
err = mp_add(t1, prime, t1);
}
while (err == MP_OKAY && mp_cmp(t1, prime) != MP_LT) {
err = mp_sub(t1, prime, t1);
}
/* compare to b */
if (err == MP_OKAY) {
if (mp_cmp(t1, b) != MP_EQ) {
err = MP_VAL;
} else {
err = MP_OKAY;
}
}
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
#else
(void)a;
(void)b;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(prime) == 256) {
return sp_ecc_is_point_256(ecp->x, ecp->y);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(prime) == 384) {
return sp_ecc_is_point_384(ecp->x, ecp->y);
}
#endif
return WC_KEY_SIZE_E;
#endif
}
#ifndef WOLFSSL_SP_MATH
/* validate privkey * generator == pubkey, 0 on success */
static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime)
{
int err = MP_OKAY;
ecc_point* base = NULL;
ecc_point* res = NULL;
DECLARE_CURVE_SPECS(curve, 2);
if (key == NULL)
return BAD_FUNC_ARG;
ALLOC_CURVE_SPECS(2);
res = wc_ecc_new_point_h(key->heap);
if (res == NULL)
err = MEMORY_E;
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
if (err == MP_OKAY) {
err = sp_ecc_mulmod_base_256(&key->k, res, 1, key->heap);
}
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
if (err == MP_OKAY) {
err = sp_ecc_mulmod_base_384(&key->k, res, 1, key->heap);
}
}
else
#endif
#endif
{
base = wc_ecc_new_point_h(key->heap);
if (base == NULL)
err = MEMORY_E;
if (err == MP_OKAY) {
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_GX | ECC_CURVE_FIELD_GY));
}
/* set up base generator */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, base->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, base->y);
if (err == MP_OKAY)
err = mp_set(base->z, 1);
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(&key->k, base, res, a, prime, 1, key->heap);
}
if (err == MP_OKAY) {
/* compare result to public key */
if (mp_cmp(res->x, key->pubkey.x) != MP_EQ ||
mp_cmp(res->y, key->pubkey.y) != MP_EQ ||
mp_cmp(res->z, key->pubkey.z) != MP_EQ) {
/* didn't match */
err = ECC_PRIV_KEY_E;
}
}
wc_ecc_curve_free(curve);
wc_ecc_del_point_h(res, key->heap);
wc_ecc_del_point_h(base, key->heap);
FREE_CURVE_SPECS();
return err;
}
#endif
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
/* check privkey generator helper, creates prime needed */
static int ecc_check_privkey_gen_helper(ecc_key* key)
{
int err;
#ifndef WOLFSSL_ATECC508A
DECLARE_CURVE_SPECS(curve, 2);
#endif
if (key == NULL)
return BAD_FUNC_ARG;
#ifdef WOLFSSL_ATECC508A
/* Hardware based private key, so this operation is not supported */
err = MP_OKAY; /* just report success */
#else
ALLOC_CURVE_SPECS(2);
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
if (err == MP_OKAY)
err = ecc_check_privkey_gen(key, curve->Af, curve->prime);
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_ATECC508A */
return err;
}
#endif /* WOLFSSL_VALIDATE_ECC_IMPORT */
#if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH)
/* validate order * pubkey = point at infinity, 0 on success */
static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a,
mp_int* prime, mp_int* order)
{
ecc_point* inf = NULL;
int err;
if (key == NULL)
return BAD_FUNC_ARG;
inf = wc_ecc_new_point_h(key->heap);
if (inf == NULL)
err = MEMORY_E;
else {
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_mulmod_256(order, pubkey, inf, 1, key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_mulmod_384(order, pubkey, inf, 1, key->heap);
}
else
#endif
#endif
#ifndef WOLFSSL_SP_MATH
err = wc_ecc_mulmod_ex(order, pubkey, inf, a, prime, 1, key->heap);
if (err == MP_OKAY && !wc_ecc_point_is_at_infinity(inf))
err = ECC_INF_E;
#else
(void)a;
(void)prime;
err = WC_KEY_SIZE_E;
#endif
}
wc_ecc_del_point_h(inf, key->heap);
return err;
}
#endif
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL*/
/* perform sanity checks on ecc key validity, 0 on success */
int wc_ecc_check_key(ecc_key* key)
{
int err;
#ifndef WOLFSSL_SP_MATH
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
mp_int* b = NULL;
#ifdef USE_ECC_B_PARAM
DECLARE_CURVE_SPECS(curve, 4);
#else
#ifndef WOLFSSL_SMALL_STACK
mp_int b_lcl;
#endif
DECLARE_CURVE_SPECS(curve, 3);
#endif /* USE_ECC_B_PARAM */
#endif /* WOLFSSL_ATECC508A */
if (key == NULL)
return BAD_FUNC_ARG;
#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_CRYPTOCELL)
err = 0; /* consider key check success on ATECC508A */
#else
#ifdef USE_ECC_B_PARAM
ALLOC_CURVE_SPECS(4);
#else
ALLOC_CURVE_SPECS(3);
#ifndef WOLFSSL_SMALL_STACK
b = &b_lcl;
#else
b = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (b == NULL) {
FREE_CURVE_SPECS();
return MEMORY_E;
}
#endif
XMEMSET(b, 0, sizeof(mp_int));
#endif
/* SP 800-56Ar3, section 5.6.2.3.3, process step 1 */
/* pubkey point cannot be at infinity */
if (wc_ecc_point_is_at_infinity(&key->pubkey)) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
FREE_CURVE_SPECS();
return ECC_INF_E;
}
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME |
ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_ORDER
#ifdef USE_ECC_B_PARAM
| ECC_CURVE_FIELD_BF
#endif
));
#ifndef USE_ECC_B_PARAM
/* load curve b parameter */
if (err == MP_OKAY)
err = mp_init(b);
if (err == MP_OKAY)
err = mp_read_radix(b, key->dp->Bf, MP_RADIX_HEX);
#else
if (err == MP_OKAY)
b = curve->Bf;
#endif
/* SP 800-56Ar3, section 5.6.2.3.3, process step 2 */
/* Qx must be in the range [0, p-1] */
if (err == MP_OKAY) {
if (mp_cmp(key->pubkey.x, curve->prime) != MP_LT)
err = ECC_OUT_OF_RANGE_E;
}
/* Qy must be in the range [0, p-1] */
if (err == MP_OKAY) {
if (mp_cmp(key->pubkey.y, curve->prime) != MP_LT)
err = ECC_OUT_OF_RANGE_E;
}
/* SP 800-56Ar3, section 5.6.2.3.3, process steps 3 */
/* make sure point is actually on curve */
if (err == MP_OKAY)
err = wc_ecc_is_point(&key->pubkey, curve->Af, b, curve->prime);
/* SP 800-56Ar3, section 5.6.2.3.3, process steps 4 */
/* pubkey * order must be at infinity */
if (err == MP_OKAY)
err = ecc_check_pubkey_order(key, &key->pubkey, curve->Af, curve->prime,
curve->order);
/* SP 800-56Ar3, section 5.6.2.1.4, method (b) for ECC */
/* private * base generator must equal pubkey */
if (err == MP_OKAY && key->type == ECC_PRIVATEKEY)
err = ecc_check_privkey_gen(key, curve->Af, curve->prime);
wc_ecc_curve_free(curve);
#ifndef USE_ECC_B_PARAM
mp_clear(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif
FREE_CURVE_SPECS();
#endif /* WOLFSSL_ATECC508A */
#else
if (key == NULL)
return BAD_FUNC_ARG;
/* pubkey point cannot be at infinity */
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, &key->k,
key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y, &key->k,
key->heap);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
return err;
}
#ifdef HAVE_ECC_KEY_IMPORT
/* import public ECC key in ANSI X9.63 format */
int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key,
int curve_id)
{
int err = MP_OKAY;
int compressed = 0;
int keysize = 0;
byte pointType;
if (in == NULL || key == NULL)
return BAD_FUNC_ARG;
/* must be odd */
if ((inLen & 1) == 0) {
return ECC_BAD_ARG_E;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
/* init key */
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
err = mp_init(&key->k);
#else
err = mp_init_multi(&key->k,
key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* check for point type (4, 2, or 3) */
pointType = in[0];
if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN &&
pointType != ECC_POINT_COMP_ODD) {
err = ASN_PARSE_E;
}
if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) {
#ifdef HAVE_COMP_KEY
compressed = 1;
#else
err = NOT_COMPILED_IN;
#endif
}
/* adjust to skip first byte */
inLen -= 1;
in += 1;
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 only save raw public key for hardware */
if (curve_id == ECC_SECP256R1 && !compressed &&
inLen <= sizeof(key->pubkey_raw)) {
XMEMCPY(key->pubkey_raw, (byte*)in, inLen);
}
#endif
if (err == MP_OKAY) {
#ifdef HAVE_COMP_KEY
/* adjust inLen if compressed */
if (compressed)
inLen = inLen*2 + 1; /* used uncompressed len */
#endif
/* determine key size */
keysize = (inLen>>1);
err = wc_ecc_set_curve(key, keysize, curve_id);
key->type = ECC_PUBLICKEY;
}
/* read data */
if (err == MP_OKAY)
err = mp_read_unsigned_bin(key->pubkey.x, (byte*)in, keysize);
#ifdef HAVE_COMP_KEY
if (err == MP_OKAY && compressed == 1) { /* build y */
#ifndef WOLFSSL_SP_MATH
mp_int t1, t2;
int did_init = 0;
DECLARE_CURVE_SPECS(curve, 3);
ALLOC_CURVE_SPECS(3);
if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
err = MEMORY_E;
else
did_init = 1;
/* load curve info */
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
ECC_CURVE_FIELD_BF));
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(key->pubkey.x, &t1);
if (err == MP_OKAY)
err = mp_mulmod(&t1, key->pubkey.x, curve->prime, &t1);
/* compute x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(curve->Af, key->pubkey.x, curve->prime, &t2);
if (err == MP_OKAY)
err = mp_add(&t1, &t2, &t1);
/* compute x^3 + a*x + b */
if (err == MP_OKAY)
err = mp_add(&t1, curve->Bf, &t1);
/* compute sqrt(x^3 + a*x + b) */
if (err == MP_OKAY)
err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
/* adjust y */
if (err == MP_OKAY) {
if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
(mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) {
err = mp_mod(&t2, curve->prime, &t2);
}
else {
err = mp_submod(curve->prime, &t2, curve->prime, &t2);
}
if (err == MP_OKAY)
err = mp_copy(&t2, key->pubkey.y);
}
if (did_init) {
mp_clear(&t2);
mp_clear(&t1);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#else
#ifndef WOLFSSL_SP_NO_256
if (key->dp->id == ECC_SECP256R1) {
sp_ecc_uncompress_256(key->pubkey.x, pointType, key->pubkey.y);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->dp->id == ECC_SECP384R1) {
sp_ecc_uncompress_384(key->pubkey.x, pointType, key->pubkey.y);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
}
#endif /* HAVE_COMP_KEY */
if (err == MP_OKAY && compressed == 0)
err = mp_read_unsigned_bin(key->pubkey.y, (byte*)in + keysize, keysize);
if (err == MP_OKAY)
err = mp_set(key->pubkey.z, 1);
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if (err == MP_OKAY)
err = wc_ecc_check_key(key);
#endif
if (err != MP_OKAY) {
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_clear(&key->k);
}
return err;
}
WOLFSSL_ABI
int wc_ecc_import_x963(const byte* in, word32 inLen, ecc_key* key)
{
return wc_ecc_import_x963_ex(in, inLen, key, ECC_CURVE_DEF);
}
#endif /* HAVE_ECC_KEY_IMPORT */
#ifdef HAVE_ECC_KEY_EXPORT
/* export ecc key to component form, d is optional if only exporting public
* encType is WC_TYPE_UNSIGNED_BIN or WC_TYPE_HEX_STR
* return MP_OKAY on success */
int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen, byte* d, word32* dLen, int encType)
{
int err = 0;
word32 keySz;
if (key == NULL) {
return BAD_FUNC_ARG;
}
if (wc_ecc_is_valid_idx(key->idx) == 0) {
return ECC_BAD_ARG_E;
}
keySz = key->dp->size;
/* private key, d */
if (d != NULL) {
if (dLen == NULL ||
(key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY))
return BAD_FUNC_ARG;
#ifdef WOLFSSL_ATECC508A
/* Hardware cannot export private portion */
return NOT_COMPILED_IN;
#else
err = wc_export_int(&key->k, d, dLen, keySz, encType);
if (err != MP_OKAY)
return err;
#endif
}
/* public x component */
if (qx != NULL) {
if (qxLen == NULL || key->type == ECC_PRIVATEKEY_ONLY)
return BAD_FUNC_ARG;
err = wc_export_int(key->pubkey.x, qx, qxLen, keySz, encType);
if (err != MP_OKAY)
return err;
}
/* public y component */
if (qy != NULL) {
if (qyLen == NULL || key->type == ECC_PRIVATEKEY_ONLY)
return BAD_FUNC_ARG;
err = wc_export_int(key->pubkey.y, qy, qyLen, keySz, encType);
if (err != MP_OKAY)
return err;
}
return err;
}
/* export ecc private key only raw, outLen is in/out size as unsigned bin
return MP_OKAY on success */
int wc_ecc_export_private_only(ecc_key* key, byte* out, word32* outLen)
{
if (out == NULL || outLen == NULL) {
return BAD_FUNC_ARG;
}
return wc_ecc_export_ex(key, NULL, NULL, NULL, NULL, out, outLen,
WC_TYPE_UNSIGNED_BIN);
}
/* export public key to raw elements including public (Qx,Qy) as unsigned bin
* return MP_OKAY on success, negative on error */
int wc_ecc_export_public_raw(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen)
{
if (qx == NULL || qxLen == NULL || qy == NULL || qyLen == NULL) {
return BAD_FUNC_ARG;
}
return wc_ecc_export_ex(key, qx, qxLen, qy, qyLen, NULL, NULL,
WC_TYPE_UNSIGNED_BIN);
}
/* export ecc key to raw elements including public (Qx,Qy) and
* private (d) as unsigned bin
* return MP_OKAY on success, negative on error */
int wc_ecc_export_private_raw(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen, byte* d, word32* dLen)
{
return wc_ecc_export_ex(key, qx, qxLen, qy, qyLen, d, dLen,
WC_TYPE_UNSIGNED_BIN);
}
#endif /* HAVE_ECC_KEY_EXPORT */
#ifndef NO_ASN
#ifdef HAVE_ECC_KEY_IMPORT
/* import private key, public part optional if (pub) passed as NULL */
int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz,
const byte* pub, word32 pubSz, ecc_key* key,
int curve_id)
{
int ret;
word32 idx = 0;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_BUILD_TempData_t tempBuff;
#endif
if (key == NULL || priv == NULL)
return BAD_FUNC_ARG;
/* public optional, NULL if only importing private */
if (pub != NULL) {
ret = wc_ecc_import_x963_ex(pub, pubSz, key, curve_id);
if (ret < 0)
ret = wc_EccPublicKeyDecode(pub, &idx, key, pubSz);
key->type = ECC_PRIVATEKEY;
}
else {
/* make sure required variables are reset */
wc_ecc_reset(key);
/* set key size */
ret = wc_ecc_set_curve(key, privSz, curve_id);
key->type = ECC_PRIVATEKEY_ONLY;
}
if (ret != 0)
return ret;
#ifdef WOLFSSL_ATECC508A
/* Hardware does not support loading private keys */
return NOT_COMPILED_IN;
#elif defined(WOLFSSL_CRYPTOCELL)
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
if (pub != NULL && pub[0] != '\0') {
/* create public key from external key buffer */
ret = CRYS_ECPKI_BuildPublKeyFullCheck(pDomain,
(byte*)pub,
pubSz,
&key->ctx.pubKey,
&tempBuff);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPublKeyFullCheck failed");
return ret;
}
}
/* import private key */
if (priv != NULL && priv[0] != '\0') {
/* Create private key from external key buffer*/
ret = CRYS_ECPKI_BuildPrivKey(pDomain,
priv,
privSz,
&key->ctx.privKey);
if (ret != SA_SILIB_RET_OK) {
WOLFSSL_MSG("CRYS_ECPKI_BuildPrivKey failed");
return ret;
}
ret = mp_read_unsigned_bin(&key->k, priv, privSz);
}
#else
ret = mp_read_unsigned_bin(&key->k, priv, privSz);
#ifdef HAVE_WOLF_BIGINT
if (ret == 0 &&
wc_bigint_from_unsigned_bin(&key->k.raw, priv, privSz) != 0) {
mp_clear(&key->k);
ret = ASN_GETINT_E;
}
#endif /* HAVE_WOLF_BIGINT */
#endif /* WOLFSSL_ATECC508A */
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if ((pub != NULL) && (ret == MP_OKAY))
/* public key needed to perform key validation */
ret = ecc_check_privkey_gen_helper(key);
#endif
return ret;
}
/* ecc private key import, public key in ANSI X9.63 format, private raw */
int wc_ecc_import_private_key(const byte* priv, word32 privSz, const byte* pub,
word32 pubSz, ecc_key* key)
{
return wc_ecc_import_private_key_ex(priv, privSz, pub, pubSz, key,
ECC_CURVE_DEF);
}
#endif /* HAVE_ECC_KEY_IMPORT */
/**
Convert ECC R,S to signature
r R component of signature
s S component of signature
out DER-encoded ECDSA signature
outlen [in/out] output buffer size, output signature size
return MP_OKAY on success
*/
int wc_ecc_rs_to_sig(const char* r, const char* s, byte* out, word32* outlen)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (r == NULL || s == NULL || out == NULL || outlen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = mp_init_multi(rtmp, stmp, NULL, NULL, NULL, NULL);
if (err != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
err = mp_read_radix(rtmp, r, MP_RADIX_HEX);
if (err == MP_OKAY)
err = mp_read_radix(stmp, s, MP_RADIX_HEX);
/* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
if (err == MP_OKAY)
err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
if (err == MP_OKAY) {
if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
err = MP_ZERO_E;
}
mp_clear(rtmp);
mp_clear(stmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/**
Convert ECC R,S raw unsigned bin to signature
r R component of signature
rSz R size
s S component of signature
sSz S size
out DER-encoded ECDSA signature
outlen [in/out] output buffer size, output signature size
return MP_OKAY on success
*/
int wc_ecc_rs_raw_to_sig(const byte* r, word32 rSz, const byte* s, word32 sSz,
byte* out, word32* outlen)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (r == NULL || s == NULL || out == NULL || outlen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = mp_init_multi(rtmp, stmp, NULL, NULL, NULL, NULL);
if (err != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
err = mp_read_unsigned_bin(rtmp, r, rSz);
if (err == MP_OKAY)
err = mp_read_unsigned_bin(stmp, s, sSz);
/* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
if (err == MP_OKAY)
err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
if (err == MP_OKAY) {
if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
err = MP_ZERO_E;
}
mp_clear(rtmp);
mp_clear(stmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/**
Convert ECC signature to R,S
sig DER-encoded ECDSA signature
sigLen length of signature in octets
r R component of signature
rLen [in/out] output "r" buffer size, output "r" size
s S component of signature
sLen [in/out] output "s" buffer size, output "s" size
return MP_OKAY on success, negative on error
*/
int wc_ecc_sig_to_rs(const byte* sig, word32 sigLen, byte* r, word32* rLen,
byte* s, word32* sLen)
{
int err;
int tmp_valid = 0;
word32 x = 0;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (sig == NULL || r == NULL || rLen == NULL || s == NULL || sLen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = DecodeECC_DSA_Sig(sig, sigLen, rtmp, stmp);
/* rtmp and stmp are initialized */
if (err == MP_OKAY) {
tmp_valid = 1;
}
/* extract r */
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(rtmp);
if (*rLen < x)
err = BUFFER_E;
if (err == MP_OKAY) {
*rLen = x;
err = mp_to_unsigned_bin(rtmp, r);
}
}
/* extract s */
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(stmp);
if (*sLen < x)
err = BUFFER_E;
if (err == MP_OKAY) {
*sLen = x;
err = mp_to_unsigned_bin(stmp, s);
}
}
if (tmp_valid) {
mp_clear(rtmp);
mp_clear(stmp);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
#endif /* !NO_ASN */
#ifdef HAVE_ECC_KEY_IMPORT
static int wc_ecc_import_raw_private(ecc_key* key, const char* qx,
const char* qy, const char* d, int curve_id, int encType)
{
int err = MP_OKAY;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_BUILD_TempData_t tempBuff;
byte key_raw[ECC_MAX_CRYPTO_HW_SIZE*2 + 1];
word32 keySz = 0;
#endif
/* if d is NULL, only import as public key using Qx,Qy */
if (key == NULL || qx == NULL || qy == NULL) {
return BAD_FUNC_ARG;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
/* set curve type and index */
err = wc_ecc_set_curve(key, 0, curve_id);
if (err != 0) {
return err;
}
/* init key */
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
err = mp_init(&key->k);
#else
err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z,
NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* read Qx */
if (err == MP_OKAY) {
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx,
key->dp->size);
}
/* read Qy */
if (err == MP_OKAY) {
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy,
key->dp->size);
}
if (err == MP_OKAY)
err = mp_set(key->pubkey.z, 1);
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 only save raw public key for hardware */
if (err == MP_OKAY && curve_id == ECC_SECP256R1) {
word32 keySz = key->dp->size;
err = wc_export_int(key->pubkey.x, key->pubkey_raw,
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
if (err == MP_OKAY)
err = wc_export_int(key->pubkey.y, &key->pubkey_raw[keySz],
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (err == MP_OKAY) {
key_raw[0] = ECC_POINT_UNCOMP;
keySz = (word32)key->dp->size;
err = wc_export_int(key->pubkey.x, &key_raw[1], &keySz, keySz,
WC_TYPE_UNSIGNED_BIN);
if (err == MP_OKAY)
err = wc_export_int(key->pubkey.y, &key_raw[1+keySz],
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
/* create public key from external key buffer */
err = CRYS_ECPKI_BuildPublKeyFullCheck(pDomain,
key_raw,
keySz*2 + 1,
&key->ctx.pubKey,
&tempBuff);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPublKeyFullCheck failed");
return err;
}
}
#endif
/* import private key */
if (err == MP_OKAY) {
if (d != NULL && d[0] != '\0') {
#ifdef WOLFSSL_ATECC508A
/* Hardware doesn't support loading private key */
err = NOT_COMPILED_IN;
#elif defined(WOLFSSL_CRYPTOCELL)
key->type = ECC_PRIVATEKEY;
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(&key->k, d, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(&key->k, (const byte*)d,
key->dp->size);
if (err == MP_OKAY) {
err = wc_export_int(&key->k, &key_raw[0], &keySz, keySz,
WC_TYPE_UNSIGNED_BIN);
}
if (err == MP_OKAY) {
/* Create private key from external key buffer*/
err = CRYS_ECPKI_BuildPrivKey(pDomain,
key_raw,
keySz,
&key->ctx.privKey);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPrivKey failed");
return err;
}
}
#else
key->type = ECC_PRIVATEKEY;
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(&key->k, d, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(&key->k, (const byte*)d,
key->dp->size);
#endif /* WOLFSSL_ATECC508A */
} else {
key->type = ECC_PUBLICKEY;
}
}
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if (err == MP_OKAY)
err = wc_ecc_check_key(key);
#endif
if (err != MP_OKAY) {
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_clear(&key->k);
}
return err;
}
/**
Import raw ECC key
key The destination ecc_key structure
qx x component of the public key, as ASCII hex string
qy y component of the public key, as ASCII hex string
d private key, as ASCII hex string, optional if importing public
key only
dp Custom ecc_set_type
return MP_OKAY on success
*/
int wc_ecc_import_raw_ex(ecc_key* key, const char* qx, const char* qy,
const char* d, int curve_id)
{
return wc_ecc_import_raw_private(key, qx, qy, d, curve_id,
WC_TYPE_HEX_STR);
}
/* Import x, y and optional private (d) as unsigned binary */
int wc_ecc_import_unsigned(ecc_key* key, byte* qx, byte* qy,
byte* d, int curve_id)
{
return wc_ecc_import_raw_private(key, (const char*)qx, (const char*)qy,
(const char*)d, curve_id, WC_TYPE_UNSIGNED_BIN);
}
/**
Import raw ECC key
key The destination ecc_key structure
qx x component of the public key, as ASCII hex string
qy y component of the public key, as ASCII hex string
d private key, as ASCII hex string, optional if importing public
key only
curveName ECC curve name, from ecc_sets[]
return MP_OKAY on success
*/
int wc_ecc_import_raw(ecc_key* key, const char* qx, const char* qy,
const char* d, const char* curveName)
{
int err, x;
/* if d is NULL, only import as public key using Qx,Qy */
if (key == NULL || qx == NULL || qy == NULL || curveName == NULL) {
return BAD_FUNC_ARG;
}
/* set curve type and index */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (XSTRNCMP(ecc_sets[x].name, curveName,
XSTRLEN(curveName)) == 0) {
break;
}
}
if (ecc_sets[x].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
err = ASN_PARSE_E;
} else {
return wc_ecc_import_raw_private(key, qx, qy, d, ecc_sets[x].id,
WC_TYPE_HEX_STR);
}
return err;
}
#endif /* HAVE_ECC_KEY_IMPORT */
/* key size in octets */
int wc_ecc_size(ecc_key* key)
{
if (key == NULL)
return 0;
return key->dp->size;
}
/* maximum signature size based on key size */
int wc_ecc_sig_size_calc(int sz)
{
int maxSigSz = 0;
/* calculate based on key bits */
/* maximum possible signature header size is 7 bytes plus 2 bytes padding */
maxSigSz = (sz * 2) + SIG_HEADER_SZ + ECC_MAX_PAD_SZ;
/* if total length is less than 128 + SEQ(1)+LEN(1) then subtract 1 */
if (maxSigSz < (128 + 2)) {
maxSigSz -= 1;
}
return maxSigSz;
}
/* maximum signature size based on actual key curve */
int wc_ecc_sig_size(ecc_key* key)
{
int maxSigSz;
int orderBits, keySz;
if (key == NULL || key->dp == NULL)
return 0;
/* the signature r and s will always be less than order */
/* if the order MSB (top bit of byte) is set then ASN encoding needs
extra byte for r and s, so add 2 */
keySz = key->dp->size;
orderBits = wc_ecc_get_curve_order_bit_count(key->dp);
if (orderBits > keySz * 8) {
keySz = (orderBits + 7) / 8;
}
/* maximum possible signature header size is 7 bytes */
maxSigSz = (keySz * 2) + SIG_HEADER_SZ;
if ((orderBits % 8) == 0) {
/* MSB can be set, so add 2 */
maxSigSz += ECC_MAX_PAD_SZ;
}
/* if total length is less than 128 + SEQ(1)+LEN(1) then subtract 1 */
if (maxSigSz < (128 + 2)) {
maxSigSz -= 1;
}
return maxSigSz;
}
#ifdef FP_ECC
/* fixed point ECC cache */
/* number of entries in the cache */
#ifndef FP_ENTRIES
#define FP_ENTRIES 15
#endif
/* number of bits in LUT */
#ifndef FP_LUT
#define FP_LUT 8U
#endif
#ifdef ECC_SHAMIR
/* Sharmir requires a bigger LUT, TAO */
#if (FP_LUT > 12) || (FP_LUT < 4)
#error FP_LUT must be between 4 and 12 inclusively
#endif
#else
#if (FP_LUT > 12) || (FP_LUT < 2)
#error FP_LUT must be between 2 and 12 inclusively
#endif
#endif
#ifndef WOLFSSL_SP_MATH
/** Our FP cache */
typedef struct {
ecc_point* g; /* cached COPY of base point */
ecc_point* LUT[1U<<FP_LUT]; /* fixed point lookup */
mp_int mu; /* copy of the montgomery constant */
int lru_count; /* amount of times this entry has been used */
int lock; /* flag to indicate cache eviction */
/* permitted (0) or not (1) */
} fp_cache_t;
/* if HAVE_THREAD_LS this cache is per thread, no locking needed */
static THREAD_LS_T fp_cache_t fp_cache[FP_ENTRIES];
#ifndef HAVE_THREAD_LS
static volatile int initMutex = 0; /* prevent multiple mutex inits */
static wolfSSL_Mutex ecc_fp_lock;
#endif /* HAVE_THREAD_LS */
/* simple table to help direct the generation of the LUT */
static const struct {
int ham, terma, termb;
} lut_orders[] = {
{ 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 2, 1, 2 }, { 1, 0, 0 }, { 2, 1, 4 }, { 2, 2, 4 }, { 3, 3, 4 },
{ 1, 0, 0 }, { 2, 1, 8 }, { 2, 2, 8 }, { 3, 3, 8 }, { 2, 4, 8 }, { 3, 5, 8 }, { 3, 6, 8 }, { 4, 7, 8 },
{ 1, 0, 0 }, { 2, 1, 16 }, { 2, 2, 16 }, { 3, 3, 16 }, { 2, 4, 16 }, { 3, 5, 16 }, { 3, 6, 16 }, { 4, 7, 16 },
{ 2, 8, 16 }, { 3, 9, 16 }, { 3, 10, 16 }, { 4, 11, 16 }, { 3, 12, 16 }, { 4, 13, 16 }, { 4, 14, 16 }, { 5, 15, 16 },
{ 1, 0, 0 }, { 2, 1, 32 }, { 2, 2, 32 }, { 3, 3, 32 }, { 2, 4, 32 }, { 3, 5, 32 }, { 3, 6, 32 }, { 4, 7, 32 },
{ 2, 8, 32 }, { 3, 9, 32 }, { 3, 10, 32 }, { 4, 11, 32 }, { 3, 12, 32 }, { 4, 13, 32 }, { 4, 14, 32 }, { 5, 15, 32 },
{ 2, 16, 32 }, { 3, 17, 32 }, { 3, 18, 32 }, { 4, 19, 32 }, { 3, 20, 32 }, { 4, 21, 32 }, { 4, 22, 32 }, { 5, 23, 32 },
{ 3, 24, 32 }, { 4, 25, 32 }, { 4, 26, 32 }, { 5, 27, 32 }, { 4, 28, 32 }, { 5, 29, 32 }, { 5, 30, 32 }, { 6, 31, 32 },
#if FP_LUT > 6
{ 1, 0, 0 }, { 2, 1, 64 }, { 2, 2, 64 }, { 3, 3, 64 }, { 2, 4, 64 }, { 3, 5, 64 }, { 3, 6, 64 }, { 4, 7, 64 },
{ 2, 8, 64 }, { 3, 9, 64 }, { 3, 10, 64 }, { 4, 11, 64 }, { 3, 12, 64 }, { 4, 13, 64 }, { 4, 14, 64 }, { 5, 15, 64 },
{ 2, 16, 64 }, { 3, 17, 64 }, { 3, 18, 64 }, { 4, 19, 64 }, { 3, 20, 64 }, { 4, 21, 64 }, { 4, 22, 64 }, { 5, 23, 64 },
{ 3, 24, 64 }, { 4, 25, 64 }, { 4, 26, 64 }, { 5, 27, 64 }, { 4, 28, 64 }, { 5, 29, 64 }, { 5, 30, 64 }, { 6, 31, 64 },
{ 2, 32, 64 }, { 3, 33, 64 }, { 3, 34, 64 }, { 4, 35, 64 }, { 3, 36, 64 }, { 4, 37, 64 }, { 4, 38, 64 }, { 5, 39, 64 },
{ 3, 40, 64 }, { 4, 41, 64 }, { 4, 42, 64 }, { 5, 43, 64 }, { 4, 44, 64 }, { 5, 45, 64 }, { 5, 46, 64 }, { 6, 47, 64 },
{ 3, 48, 64 }, { 4, 49, 64 }, { 4, 50, 64 }, { 5, 51, 64 }, { 4, 52, 64 }, { 5, 53, 64 }, { 5, 54, 64 }, { 6, 55, 64 },
{ 4, 56, 64 }, { 5, 57, 64 }, { 5, 58, 64 }, { 6, 59, 64 }, { 5, 60, 64 }, { 6, 61, 64 }, { 6, 62, 64 }, { 7, 63, 64 },
#if FP_LUT > 7
{ 1, 0, 0 }, { 2, 1, 128 }, { 2, 2, 128 }, { 3, 3, 128 }, { 2, 4, 128 }, { 3, 5, 128 }, { 3, 6, 128 }, { 4, 7, 128 },
{ 2, 8, 128 }, { 3, 9, 128 }, { 3, 10, 128 }, { 4, 11, 128 }, { 3, 12, 128 }, { 4, 13, 128 }, { 4, 14, 128 }, { 5, 15, 128 },
{ 2, 16, 128 }, { 3, 17, 128 }, { 3, 18, 128 }, { 4, 19, 128 }, { 3, 20, 128 }, { 4, 21, 128 }, { 4, 22, 128 }, { 5, 23, 128 },
{ 3, 24, 128 }, { 4, 25, 128 }, { 4, 26, 128 }, { 5, 27, 128 }, { 4, 28, 128 }, { 5, 29, 128 }, { 5, 30, 128 }, { 6, 31, 128 },
{ 2, 32, 128 }, { 3, 33, 128 }, { 3, 34, 128 }, { 4, 35, 128 }, { 3, 36, 128 }, { 4, 37, 128 }, { 4, 38, 128 }, { 5, 39, 128 },
{ 3, 40, 128 }, { 4, 41, 128 }, { 4, 42, 128 }, { 5, 43, 128 }, { 4, 44, 128 }, { 5, 45, 128 }, { 5, 46, 128 }, { 6, 47, 128 },
{ 3, 48, 128 }, { 4, 49, 128 }, { 4, 50, 128 }, { 5, 51, 128 }, { 4, 52, 128 }, { 5, 53, 128 }, { 5, 54, 128 }, { 6, 55, 128 },
{ 4, 56, 128 }, { 5, 57, 128 }, { 5, 58, 128 }, { 6, 59, 128 }, { 5, 60, 128 }, { 6, 61, 128 }, { 6, 62, 128 }, { 7, 63, 128 },
{ 2, 64, 128 }, { 3, 65, 128 }, { 3, 66, 128 }, { 4, 67, 128 }, { 3, 68, 128 }, { 4, 69, 128 }, { 4, 70, 128 }, { 5, 71, 128 },
{ 3, 72, 128 }, { 4, 73, 128 }, { 4, 74, 128 }, { 5, 75, 128 }, { 4, 76, 128 }, { 5, 77, 128 }, { 5, 78, 128 }, { 6, 79, 128 },
{ 3, 80, 128 }, { 4, 81, 128 }, { 4, 82, 128 }, { 5, 83, 128 }, { 4, 84, 128 }, { 5, 85, 128 }, { 5, 86, 128 }, { 6, 87, 128 },
{ 4, 88, 128 }, { 5, 89, 128 }, { 5, 90, 128 }, { 6, 91, 128 }, { 5, 92, 128 }, { 6, 93, 128 }, { 6, 94, 128 }, { 7, 95, 128 },
{ 3, 96, 128 }, { 4, 97, 128 }, { 4, 98, 128 }, { 5, 99, 128 }, { 4, 100, 128 }, { 5, 101, 128 }, { 5, 102, 128 }, { 6, 103, 128 },
{ 4, 104, 128 }, { 5, 105, 128 }, { 5, 106, 128 }, { 6, 107, 128 }, { 5, 108, 128 }, { 6, 109, 128 }, { 6, 110, 128 }, { 7, 111, 128 },
{ 4, 112, 128 }, { 5, 113, 128 }, { 5, 114, 128 }, { 6, 115, 128 }, { 5, 116, 128 }, { 6, 117, 128 }, { 6, 118, 128 }, { 7, 119, 128 },
{ 5, 120, 128 }, { 6, 121, 128 }, { 6, 122, 128 }, { 7, 123, 128 }, { 6, 124, 128 }, { 7, 125, 128 }, { 7, 126, 128 }, { 8, 127, 128 },
#if FP_LUT > 8
{ 1, 0, 0 }, { 2, 1, 256 }, { 2, 2, 256 }, { 3, 3, 256 }, { 2, 4, 256 }, { 3, 5, 256 }, { 3, 6, 256 }, { 4, 7, 256 },
{ 2, 8, 256 }, { 3, 9, 256 }, { 3, 10, 256 }, { 4, 11, 256 }, { 3, 12, 256 }, { 4, 13, 256 }, { 4, 14, 256 }, { 5, 15, 256 },
{ 2, 16, 256 }, { 3, 17, 256 }, { 3, 18, 256 }, { 4, 19, 256 }, { 3, 20, 256 }, { 4, 21, 256 }, { 4, 22, 256 }, { 5, 23, 256 },
{ 3, 24, 256 }, { 4, 25, 256 }, { 4, 26, 256 }, { 5, 27, 256 }, { 4, 28, 256 }, { 5, 29, 256 }, { 5, 30, 256 }, { 6, 31, 256 },
{ 2, 32, 256 }, { 3, 33, 256 }, { 3, 34, 256 }, { 4, 35, 256 }, { 3, 36, 256 }, { 4, 37, 256 }, { 4, 38, 256 }, { 5, 39, 256 },
{ 3, 40, 256 }, { 4, 41, 256 }, { 4, 42, 256 }, { 5, 43, 256 }, { 4, 44, 256 }, { 5, 45, 256 }, { 5, 46, 256 }, { 6, 47, 256 },
{ 3, 48, 256 }, { 4, 49, 256 }, { 4, 50, 256 }, { 5, 51, 256 }, { 4, 52, 256 }, { 5, 53, 256 }, { 5, 54, 256 }, { 6, 55, 256 },
{ 4, 56, 256 }, { 5, 57, 256 }, { 5, 58, 256 }, { 6, 59, 256 }, { 5, 60, 256 }, { 6, 61, 256 }, { 6, 62, 256 }, { 7, 63, 256 },
{ 2, 64, 256 }, { 3, 65, 256 }, { 3, 66, 256 }, { 4, 67, 256 }, { 3, 68, 256 }, { 4, 69, 256 }, { 4, 70, 256 }, { 5, 71, 256 },
{ 3, 72, 256 }, { 4, 73, 256 }, { 4, 74, 256 }, { 5, 75, 256 }, { 4, 76, 256 }, { 5, 77, 256 }, { 5, 78, 256 }, { 6, 79, 256 },
{ 3, 80, 256 }, { 4, 81, 256 }, { 4, 82, 256 }, { 5, 83, 256 }, { 4, 84, 256 }, { 5, 85, 256 }, { 5, 86, 256 }, { 6, 87, 256 },
{ 4, 88, 256 }, { 5, 89, 256 }, { 5, 90, 256 }, { 6, 91, 256 }, { 5, 92, 256 }, { 6, 93, 256 }, { 6, 94, 256 }, { 7, 95, 256 },
{ 3, 96, 256 }, { 4, 97, 256 }, { 4, 98, 256 }, { 5, 99, 256 }, { 4, 100, 256 }, { 5, 101, 256 }, { 5, 102, 256 }, { 6, 103, 256 },
{ 4, 104, 256 }, { 5, 105, 256 }, { 5, 106, 256 }, { 6, 107, 256 }, { 5, 108, 256 }, { 6, 109, 256 }, { 6, 110, 256 }, { 7, 111, 256 },
{ 4, 112, 256 }, { 5, 113, 256 }, { 5, 114, 256 }, { 6, 115, 256 }, { 5, 116, 256 }, { 6, 117, 256 }, { 6, 118, 256 }, { 7, 119, 256 },
{ 5, 120, 256 }, { 6, 121, 256 }, { 6, 122, 256 }, { 7, 123, 256 }, { 6, 124, 256 }, { 7, 125, 256 }, { 7, 126, 256 }, { 8, 127, 256 },
{ 2, 128, 256 }, { 3, 129, 256 }, { 3, 130, 256 }, { 4, 131, 256 }, { 3, 132, 256 }, { 4, 133, 256 }, { 4, 134, 256 }, { 5, 135, 256 },
{ 3, 136, 256 }, { 4, 137, 256 }, { 4, 138, 256 }, { 5, 139, 256 }, { 4, 140, 256 }, { 5, 141, 256 }, { 5, 142, 256 }, { 6, 143, 256 },
{ 3, 144, 256 }, { 4, 145, 256 }, { 4, 146, 256 }, { 5, 147, 256 }, { 4, 148, 256 }, { 5, 149, 256 }, { 5, 150, 256 }, { 6, 151, 256 },
{ 4, 152, 256 }, { 5, 153, 256 }, { 5, 154, 256 }, { 6, 155, 256 }, { 5, 156, 256 }, { 6, 157, 256 }, { 6, 158, 256 }, { 7, 159, 256 },
{ 3, 160, 256 }, { 4, 161, 256 }, { 4, 162, 256 }, { 5, 163, 256 }, { 4, 164, 256 }, { 5, 165, 256 }, { 5, 166, 256 }, { 6, 167, 256 },
{ 4, 168, 256 }, { 5, 169, 256 }, { 5, 170, 256 }, { 6, 171, 256 }, { 5, 172, 256 }, { 6, 173, 256 }, { 6, 174, 256 }, { 7, 175, 256 },
{ 4, 176, 256 }, { 5, 177, 256 }, { 5, 178, 256 }, { 6, 179, 256 }, { 5, 180, 256 }, { 6, 181, 256 }, { 6, 182, 256 }, { 7, 183, 256 },
{ 5, 184, 256 }, { 6, 185, 256 }, { 6, 186, 256 }, { 7, 187, 256 }, { 6, 188, 256 }, { 7, 189, 256 }, { 7, 190, 256 }, { 8, 191, 256 },
{ 3, 192, 256 }, { 4, 193, 256 }, { 4, 194, 256 }, { 5, 195, 256 }, { 4, 196, 256 }, { 5, 197, 256 }, { 5, 198, 256 }, { 6, 199, 256 },
{ 4, 200, 256 }, { 5, 201, 256 }, { 5, 202, 256 }, { 6, 203, 256 }, { 5, 204, 256 }, { 6, 205, 256 }, { 6, 206, 256 }, { 7, 207, 256 },
{ 4, 208, 256 }, { 5, 209, 256 }, { 5, 210, 256 }, { 6, 211, 256 }, { 5, 212, 256 }, { 6, 213, 256 }, { 6, 214, 256 }, { 7, 215, 256 },
{ 5, 216, 256 }, { 6, 217, 256 }, { 6, 218, 256 }, { 7, 219, 256 }, { 6, 220, 256 }, { 7, 221, 256 }, { 7, 222, 256 }, { 8, 223, 256 },
{ 4, 224, 256 }, { 5, 225, 256 }, { 5, 226, 256 }, { 6, 227, 256 }, { 5, 228, 256 }, { 6, 229, 256 }, { 6, 230, 256 }, { 7, 231, 256 },
{ 5, 232, 256 }, { 6, 233, 256 }, { 6, 234, 256 }, { 7, 235, 256 }, { 6, 236, 256 }, { 7, 237, 256 }, { 7, 238, 256 }, { 8, 239, 256 },
{ 5, 240, 256 }, { 6, 241, 256 }, { 6, 242, 256 }, { 7, 243, 256 }, { 6, 244, 256 }, { 7, 245, 256 }, { 7, 246, 256 }, { 8, 247, 256 },
{ 6, 248, 256 }, { 7, 249, 256 }, { 7, 250, 256 }, { 8, 251, 256 }, { 7, 252, 256 }, { 8, 253, 256 }, { 8, 254, 256 }, { 9, 255, 256 },
#if FP_LUT > 9
{ 1, 0, 0 }, { 2, 1, 512 }, { 2, 2, 512 }, { 3, 3, 512 }, { 2, 4, 512 }, { 3, 5, 512 }, { 3, 6, 512 }, { 4, 7, 512 },
{ 2, 8, 512 }, { 3, 9, 512 }, { 3, 10, 512 }, { 4, 11, 512 }, { 3, 12, 512 }, { 4, 13, 512 }, { 4, 14, 512 }, { 5, 15, 512 },
{ 2, 16, 512 }, { 3, 17, 512 }, { 3, 18, 512 }, { 4, 19, 512 }, { 3, 20, 512 }, { 4, 21, 512 }, { 4, 22, 512 }, { 5, 23, 512 },
{ 3, 24, 512 }, { 4, 25, 512 }, { 4, 26, 512 }, { 5, 27, 512 }, { 4, 28, 512 }, { 5, 29, 512 }, { 5, 30, 512 }, { 6, 31, 512 },
{ 2, 32, 512 }, { 3, 33, 512 }, { 3, 34, 512 }, { 4, 35, 512 }, { 3, 36, 512 }, { 4, 37, 512 }, { 4, 38, 512 }, { 5, 39, 512 },
{ 3, 40, 512 }, { 4, 41, 512 }, { 4, 42, 512 }, { 5, 43, 512 }, { 4, 44, 512 }, { 5, 45, 512 }, { 5, 46, 512 }, { 6, 47, 512 },
{ 3, 48, 512 }, { 4, 49, 512 }, { 4, 50, 512 }, { 5, 51, 512 }, { 4, 52, 512 }, { 5, 53, 512 }, { 5, 54, 512 }, { 6, 55, 512 },
{ 4, 56, 512 }, { 5, 57, 512 }, { 5, 58, 512 }, { 6, 59, 512 }, { 5, 60, 512 }, { 6, 61, 512 }, { 6, 62, 512 }, { 7, 63, 512 },
{ 2, 64, 512 }, { 3, 65, 512 }, { 3, 66, 512 }, { 4, 67, 512 }, { 3, 68, 512 }, { 4, 69, 512 }, { 4, 70, 512 }, { 5, 71, 512 },
{ 3, 72, 512 }, { 4, 73, 512 }, { 4, 74, 512 }, { 5, 75, 512 }, { 4, 76, 512 }, { 5, 77, 512 }, { 5, 78, 512 }, { 6, 79, 512 },
{ 3, 80, 512 }, { 4, 81, 512 }, { 4, 82, 512 }, { 5, 83, 512 }, { 4, 84, 512 }, { 5, 85, 512 }, { 5, 86, 512 }, { 6, 87, 512 },
{ 4, 88, 512 }, { 5, 89, 512 }, { 5, 90, 512 }, { 6, 91, 512 }, { 5, 92, 512 }, { 6, 93, 512 }, { 6, 94, 512 }, { 7, 95, 512 },
{ 3, 96, 512 }, { 4, 97, 512 }, { 4, 98, 512 }, { 5, 99, 512 }, { 4, 100, 512 }, { 5, 101, 512 }, { 5, 102, 512 }, { 6, 103, 512 },
{ 4, 104, 512 }, { 5, 105, 512 }, { 5, 106, 512 }, { 6, 107, 512 }, { 5, 108, 512 }, { 6, 109, 512 }, { 6, 110, 512 }, { 7, 111, 512 },
{ 4, 112, 512 }, { 5, 113, 512 }, { 5, 114, 512 }, { 6, 115, 512 }, { 5, 116, 512 }, { 6, 117, 512 }, { 6, 118, 512 }, { 7, 119, 512 },
{ 5, 120, 512 }, { 6, 121, 512 }, { 6, 122, 512 }, { 7, 123, 512 }, { 6, 124, 512 }, { 7, 125, 512 }, { 7, 126, 512 }, { 8, 127, 512 },
{ 2, 128, 512 }, { 3, 129, 512 }, { 3, 130, 512 }, { 4, 131, 512 }, { 3, 132, 512 }, { 4, 133, 512 }, { 4, 134, 512 }, { 5, 135, 512 },
{ 3, 136, 512 }, { 4, 137, 512 }, { 4, 138, 512 }, { 5, 139, 512 }, { 4, 140, 512 }, { 5, 141, 512 }, { 5, 142, 512 }, { 6, 143, 512 },
{ 3, 144, 512 }, { 4, 145, 512 }, { 4, 146, 512 }, { 5, 147, 512 }, { 4, 148, 512 }, { 5, 149, 512 }, { 5, 150, 512 }, { 6, 151, 512 },
{ 4, 152, 512 }, { 5, 153, 512 }, { 5, 154, 512 }, { 6, 155, 512 }, { 5, 156, 512 }, { 6, 157, 512 }, { 6, 158, 512 }, { 7, 159, 512 },
{ 3, 160, 512 }, { 4, 161, 512 }, { 4, 162, 512 }, { 5, 163, 512 }, { 4, 164, 512 }, { 5, 165, 512 }, { 5, 166, 512 }, { 6, 167, 512 },
{ 4, 168, 512 }, { 5, 169, 512 }, { 5, 170, 512 }, { 6, 171, 512 }, { 5, 172, 512 }, { 6, 173, 512 }, { 6, 174, 512 }, { 7, 175, 512 },
{ 4, 176, 512 }, { 5, 177, 512 }, { 5, 178, 512 }, { 6, 179, 512 }, { 5, 180, 512 }, { 6, 181, 512 }, { 6, 182, 512 }, { 7, 183, 512 },
{ 5, 184, 512 }, { 6, 185, 512 }, { 6, 186, 512 }, { 7, 187, 512 }, { 6, 188, 512 }, { 7, 189, 512 }, { 7, 190, 512 }, { 8, 191, 512 },
{ 3, 192, 512 }, { 4, 193, 512 }, { 4, 194, 512 }, { 5, 195, 512 }, { 4, 196, 512 }, { 5, 197, 512 }, { 5, 198, 512 }, { 6, 199, 512 },
{ 4, 200, 512 }, { 5, 201, 512 }, { 5, 202, 512 }, { 6, 203, 512 }, { 5, 204, 512 }, { 6, 205, 512 }, { 6, 206, 512 }, { 7, 207, 512 },
{ 4, 208, 512 }, { 5, 209, 512 }, { 5, 210, 512 }, { 6, 211, 512 }, { 5, 212, 512 }, { 6, 213, 512 }, { 6, 214, 512 }, { 7, 215, 512 },
{ 5, 216, 512 }, { 6, 217, 512 }, { 6, 218, 512 }, { 7, 219, 512 }, { 6, 220, 512 }, { 7, 221, 512 }, { 7, 222, 512 }, { 8, 223, 512 },
{ 4, 224, 512 }, { 5, 225, 512 }, { 5, 226, 512 }, { 6, 227, 512 }, { 5, 228, 512 }, { 6, 229, 512 }, { 6, 230, 512 }, { 7, 231, 512 },
{ 5, 232, 512 }, { 6, 233, 512 }, { 6, 234, 512 }, { 7, 235, 512 }, { 6, 236, 512 }, { 7, 237, 512 }, { 7, 238, 512 }, { 8, 239, 512 },
{ 5, 240, 512 }, { 6, 241, 512 }, { 6, 242, 512 }, { 7, 243, 512 }, { 6, 244, 512 }, { 7, 245, 512 }, { 7, 246, 512 }, { 8, 247, 512 },
{ 6, 248, 512 }, { 7, 249, 512 }, { 7, 250, 512 }, { 8, 251, 512 }, { 7, 252, 512 }, { 8, 253, 512 }, { 8, 254, 512 }, { 9, 255, 512 },
{ 2, 256, 512 }, { 3, 257, 512 }, { 3, 258, 512 }, { 4, 259, 512 }, { 3, 260, 512 }, { 4, 261, 512 }, { 4, 262, 512 }, { 5, 263, 512 },
{ 3, 264, 512 }, { 4, 265, 512 }, { 4, 266, 512 }, { 5, 267, 512 }, { 4, 268, 512 }, { 5, 269, 512 }, { 5, 270, 512 }, { 6, 271, 512 },
{ 3, 272, 512 }, { 4, 273, 512 }, { 4, 274, 512 }, { 5, 275, 512 }, { 4, 276, 512 }, { 5, 277, 512 }, { 5, 278, 512 }, { 6, 279, 512 },
{ 4, 280, 512 }, { 5, 281, 512 }, { 5, 282, 512 }, { 6, 283, 512 }, { 5, 284, 512 }, { 6, 285, 512 }, { 6, 286, 512 }, { 7, 287, 512 },
{ 3, 288, 512 }, { 4, 289, 512 }, { 4, 290, 512 }, { 5, 291, 512 }, { 4, 292, 512 }, { 5, 293, 512 }, { 5, 294, 512 }, { 6, 295, 512 },
{ 4, 296, 512 }, { 5, 297, 512 }, { 5, 298, 512 }, { 6, 299, 512 }, { 5, 300, 512 }, { 6, 301, 512 }, { 6, 302, 512 }, { 7, 303, 512 },
{ 4, 304, 512 }, { 5, 305, 512 }, { 5, 306, 512 }, { 6, 307, 512 }, { 5, 308, 512 }, { 6, 309, 512 }, { 6, 310, 512 }, { 7, 311, 512 },
{ 5, 312, 512 }, { 6, 313, 512 }, { 6, 314, 512 }, { 7, 315, 512 }, { 6, 316, 512 }, { 7, 317, 512 }, { 7, 318, 512 }, { 8, 319, 512 },
{ 3, 320, 512 }, { 4, 321, 512 }, { 4, 322, 512 }, { 5, 323, 512 }, { 4, 324, 512 }, { 5, 325, 512 }, { 5, 326, 512 }, { 6, 327, 512 },
{ 4, 328, 512 }, { 5, 329, 512 }, { 5, 330, 512 }, { 6, 331, 512 }, { 5, 332, 512 }, { 6, 333, 512 }, { 6, 334, 512 }, { 7, 335, 512 },
{ 4, 336, 512 }, { 5, 337, 512 }, { 5, 338, 512 }, { 6, 339, 512 }, { 5, 340, 512 }, { 6, 341, 512 }, { 6, 342, 512 }, { 7, 343, 512 },
{ 5, 344, 512 }, { 6, 345, 512 }, { 6, 346, 512 }, { 7, 347, 512 }, { 6, 348, 512 }, { 7, 349, 512 }, { 7, 350, 512 }, { 8, 351, 512 },
{ 4, 352, 512 }, { 5, 353, 512 }, { 5, 354, 512 }, { 6, 355, 512 }, { 5, 356, 512 }, { 6, 357, 512 }, { 6, 358, 512 }, { 7, 359, 512 },
{ 5, 360, 512 }, { 6, 361, 512 }, { 6, 362, 512 }, { 7, 363, 512 }, { 6, 364, 512 }, { 7, 365, 512 }, { 7, 366, 512 }, { 8, 367, 512 },
{ 5, 368, 512 }, { 6, 369, 512 }, { 6, 370, 512 }, { 7, 371, 512 }, { 6, 372, 512 }, { 7, 373, 512 }, { 7, 374, 512 }, { 8, 375, 512 },
{ 6, 376, 512 }, { 7, 377, 512 }, { 7, 378, 512 }, { 8, 379, 512 }, { 7, 380, 512 }, { 8, 381, 512 }, { 8, 382, 512 }, { 9, 383, 512 },
{ 3, 384, 512 }, { 4, 385, 512 }, { 4, 386, 512 }, { 5, 387, 512 }, { 4, 388, 512 }, { 5, 389, 512 }, { 5, 390, 512 }, { 6, 391, 512 },
{ 4, 392, 512 }, { 5, 393, 512 }, { 5, 394, 512 }, { 6, 395, 512 }, { 5, 396, 512 }, { 6, 397, 512 }, { 6, 398, 512 }, { 7, 399, 512 },
{ 4, 400, 512 }, { 5, 401, 512 }, { 5, 402, 512 }, { 6, 403, 512 }, { 5, 404, 512 }, { 6, 405, 512 }, { 6, 406, 512 }, { 7, 407, 512 },
{ 5, 408, 512 }, { 6, 409, 512 }, { 6, 410, 512 }, { 7, 411, 512 }, { 6, 412, 512 }, { 7, 413, 512 }, { 7, 414, 512 }, { 8, 415, 512 },
{ 4, 416, 512 }, { 5, 417, 512 }, { 5, 418, 512 }, { 6, 419, 512 }, { 5, 420, 512 }, { 6, 421, 512 }, { 6, 422, 512 }, { 7, 423, 512 },
{ 5, 424, 512 }, { 6, 425, 512 }, { 6, 426, 512 }, { 7, 427, 512 }, { 6, 428, 512 }, { 7, 429, 512 }, { 7, 430, 512 }, { 8, 431, 512 },
{ 5, 432, 512 }, { 6, 433, 512 }, { 6, 434, 512 }, { 7, 435, 512 }, { 6, 436, 512 }, { 7, 437, 512 }, { 7, 438, 512 }, { 8, 439, 512 },
{ 6, 440, 512 }, { 7, 441, 512 }, { 7, 442, 512 }, { 8, 443, 512 }, { 7, 444, 512 }, { 8, 445, 512 }, { 8, 446, 512 }, { 9, 447, 512 },
{ 4, 448, 512 }, { 5, 449, 512 }, { 5, 450, 512 }, { 6, 451, 512 }, { 5, 452, 512 }, { 6, 453, 512 }, { 6, 454, 512 }, { 7, 455, 512 },
{ 5, 456, 512 }, { 6, 457, 512 }, { 6, 458, 512 }, { 7, 459, 512 }, { 6, 460, 512 }, { 7, 461, 512 }, { 7, 462, 512 }, { 8, 463, 512 },
{ 5, 464, 512 }, { 6, 465, 512 }, { 6, 466, 512 }, { 7, 467, 512 }, { 6, 468, 512 }, { 7, 469, 512 }, { 7, 470, 512 }, { 8, 471, 512 },
{ 6, 472, 512 }, { 7, 473, 512 }, { 7, 474, 512 }, { 8, 475, 512 }, { 7, 476, 512 }, { 8, 477, 512 }, { 8, 478, 512 }, { 9, 479, 512 },
{ 5, 480, 512 }, { 6, 481, 512 }, { 6, 482, 512 }, { 7, 483, 512 }, { 6, 484, 512 }, { 7, 485, 512 }, { 7, 486, 512 }, { 8, 487, 512 },
{ 6, 488, 512 }, { 7, 489, 512 }, { 7, 490, 512 }, { 8, 491, 512 }, { 7, 492, 512 }, { 8, 493, 512 }, { 8, 494, 512 }, { 9, 495, 512 },
{ 6, 496, 512 }, { 7, 497, 512 }, { 7, 498, 512 }, { 8, 499, 512 }, { 7, 500, 512 }, { 8, 501, 512 }, { 8, 502, 512 }, { 9, 503, 512 },
{ 7, 504, 512 }, { 8, 505, 512 }, { 8, 506, 512 }, { 9, 507, 512 }, { 8, 508, 512 }, { 9, 509, 512 }, { 9, 510, 512 }, { 10, 511, 512 },
#if FP_LUT > 10
{ 1, 0, 0 }, { 2, 1, 1024 }, { 2, 2, 1024 }, { 3, 3, 1024 }, { 2, 4, 1024 }, { 3, 5, 1024 }, { 3, 6, 1024 }, { 4, 7, 1024 },
{ 2, 8, 1024 }, { 3, 9, 1024 }, { 3, 10, 1024 }, { 4, 11, 1024 }, { 3, 12, 1024 }, { 4, 13, 1024 }, { 4, 14, 1024 }, { 5, 15, 1024 },
{ 2, 16, 1024 }, { 3, 17, 1024 }, { 3, 18, 1024 }, { 4, 19, 1024 }, { 3, 20, 1024 }, { 4, 21, 1024 }, { 4, 22, 1024 }, { 5, 23, 1024 },
{ 3, 24, 1024 }, { 4, 25, 1024 }, { 4, 26, 1024 }, { 5, 27, 1024 }, { 4, 28, 1024 }, { 5, 29, 1024 }, { 5, 30, 1024 }, { 6, 31, 1024 },
{ 2, 32, 1024 }, { 3, 33, 1024 }, { 3, 34, 1024 }, { 4, 35, 1024 }, { 3, 36, 1024 }, { 4, 37, 1024 }, { 4, 38, 1024 }, { 5, 39, 1024 },
{ 3, 40, 1024 }, { 4, 41, 1024 }, { 4, 42, 1024 }, { 5, 43, 1024 }, { 4, 44, 1024 }, { 5, 45, 1024 }, { 5, 46, 1024 }, { 6, 47, 1024 },
{ 3, 48, 1024 }, { 4, 49, 1024 }, { 4, 50, 1024 }, { 5, 51, 1024 }, { 4, 52, 1024 }, { 5, 53, 1024 }, { 5, 54, 1024 }, { 6, 55, 1024 },
{ 4, 56, 1024 }, { 5, 57, 1024 }, { 5, 58, 1024 }, { 6, 59, 1024 }, { 5, 60, 1024 }, { 6, 61, 1024 }, { 6, 62, 1024 }, { 7, 63, 1024 },
{ 2, 64, 1024 }, { 3, 65, 1024 }, { 3, 66, 1024 }, { 4, 67, 1024 }, { 3, 68, 1024 }, { 4, 69, 1024 }, { 4, 70, 1024 }, { 5, 71, 1024 },
{ 3, 72, 1024 }, { 4, 73, 1024 }, { 4, 74, 1024 }, { 5, 75, 1024 }, { 4, 76, 1024 }, { 5, 77, 1024 }, { 5, 78, 1024 }, { 6, 79, 1024 },
{ 3, 80, 1024 }, { 4, 81, 1024 }, { 4, 82, 1024 }, { 5, 83, 1024 }, { 4, 84, 1024 }, { 5, 85, 1024 }, { 5, 86, 1024 }, { 6, 87, 1024 },
{ 4, 88, 1024 }, { 5, 89, 1024 }, { 5, 90, 1024 }, { 6, 91, 1024 }, { 5, 92, 1024 }, { 6, 93, 1024 }, { 6, 94, 1024 }, { 7, 95, 1024 },
{ 3, 96, 1024 }, { 4, 97, 1024 }, { 4, 98, 1024 }, { 5, 99, 1024 }, { 4, 100, 1024 }, { 5, 101, 1024 }, { 5, 102, 1024 }, { 6, 103, 1024 },
{ 4, 104, 1024 }, { 5, 105, 1024 }, { 5, 106, 1024 }, { 6, 107, 1024 }, { 5, 108, 1024 }, { 6, 109, 1024 }, { 6, 110, 1024 }, { 7, 111, 1024 },
{ 4, 112, 1024 }, { 5, 113, 1024 }, { 5, 114, 1024 }, { 6, 115, 1024 }, { 5, 116, 1024 }, { 6, 117, 1024 }, { 6, 118, 1024 }, { 7, 119, 1024 },
{ 5, 120, 1024 }, { 6, 121, 1024 }, { 6, 122, 1024 }, { 7, 123, 1024 }, { 6, 124, 1024 }, { 7, 125, 1024 }, { 7, 126, 1024 }, { 8, 127, 1024 },
{ 2, 128, 1024 }, { 3, 129, 1024 }, { 3, 130, 1024 }, { 4, 131, 1024 }, { 3, 132, 1024 }, { 4, 133, 1024 }, { 4, 134, 1024 }, { 5, 135, 1024 },
{ 3, 136, 1024 }, { 4, 137, 1024 }, { 4, 138, 1024 }, { 5, 139, 1024 }, { 4, 140, 1024 }, { 5, 141, 1024 }, { 5, 142, 1024 }, { 6, 143, 1024 },
{ 3, 144, 1024 }, { 4, 145, 1024 }, { 4, 146, 1024 }, { 5, 147, 1024 }, { 4, 148, 1024 }, { 5, 149, 1024 }, { 5, 150, 1024 }, { 6, 151, 1024 },
{ 4, 152, 1024 }, { 5, 153, 1024 }, { 5, 154, 1024 }, { 6, 155, 1024 }, { 5, 156, 1024 }, { 6, 157, 1024 }, { 6, 158, 1024 }, { 7, 159, 1024 },
{ 3, 160, 1024 }, { 4, 161, 1024 }, { 4, 162, 1024 }, { 5, 163, 1024 }, { 4, 164, 1024 }, { 5, 165, 1024 }, { 5, 166, 1024 }, { 6, 167, 1024 },
{ 4, 168, 1024 }, { 5, 169, 1024 }, { 5, 170, 1024 }, { 6, 171, 1024 }, { 5, 172, 1024 }, { 6, 173, 1024 }, { 6, 174, 1024 }, { 7, 175, 1024 },
{ 4, 176, 1024 }, { 5, 177, 1024 }, { 5, 178, 1024 }, { 6, 179, 1024 }, { 5, 180, 1024 }, { 6, 181, 1024 }, { 6, 182, 1024 }, { 7, 183, 1024 },
{ 5, 184, 1024 }, { 6, 185, 1024 }, { 6, 186, 1024 }, { 7, 187, 1024 }, { 6, 188, 1024 }, { 7, 189, 1024 }, { 7, 190, 1024 }, { 8, 191, 1024 },
{ 3, 192, 1024 }, { 4, 193, 1024 }, { 4, 194, 1024 }, { 5, 195, 1024 }, { 4, 196, 1024 }, { 5, 197, 1024 }, { 5, 198, 1024 }, { 6, 199, 1024 },
{ 4, 200, 1024 }, { 5, 201, 1024 }, { 5, 202, 1024 }, { 6, 203, 1024 }, { 5, 204, 1024 }, { 6, 205, 1024 }, { 6, 206, 1024 }, { 7, 207, 1024 },
{ 4, 208, 1024 }, { 5, 209, 1024 }, { 5, 210, 1024 }, { 6, 211, 1024 }, { 5, 212, 1024 }, { 6, 213, 1024 }, { 6, 214, 1024 }, { 7, 215, 1024 },
{ 5, 216, 1024 }, { 6, 217, 1024 }, { 6, 218, 1024 }, { 7, 219, 1024 }, { 6, 220, 1024 }, { 7, 221, 1024 }, { 7, 222, 1024 }, { 8, 223, 1024 },
{ 4, 224, 1024 }, { 5, 225, 1024 }, { 5, 226, 1024 }, { 6, 227, 1024 }, { 5, 228, 1024 }, { 6, 229, 1024 }, { 6, 230, 1024 }, { 7, 231, 1024 },
{ 5, 232, 1024 }, { 6, 233, 1024 }, { 6, 234, 1024 }, { 7, 235, 1024 }, { 6, 236, 1024 }, { 7, 237, 1024 }, { 7, 238, 1024 }, { 8, 239, 1024 },
{ 5, 240, 1024 }, { 6, 241, 1024 }, { 6, 242, 1024 }, { 7, 243, 1024 }, { 6, 244, 1024 }, { 7, 245, 1024 }, { 7, 246, 1024 }, { 8, 247, 1024 },
{ 6, 248, 1024 }, { 7, 249, 1024 }, { 7, 250, 1024 }, { 8, 251, 1024 }, { 7, 252, 1024 }, { 8, 253, 1024 }, { 8, 254, 1024 }, { 9, 255, 1024 },
{ 2, 256, 1024 }, { 3, 257, 1024 }, { 3, 258, 1024 }, { 4, 259, 1024 }, { 3, 260, 1024 }, { 4, 261, 1024 }, { 4, 262, 1024 }, { 5, 263, 1024 },
{ 3, 264, 1024 }, { 4, 265, 1024 }, { 4, 266, 1024 }, { 5, 267, 1024 }, { 4, 268, 1024 }, { 5, 269, 1024 }, { 5, 270, 1024 }, { 6, 271, 1024 },
{ 3, 272, 1024 }, { 4, 273, 1024 }, { 4, 274, 1024 }, { 5, 275, 1024 }, { 4, 276, 1024 }, { 5, 277, 1024 }, { 5, 278, 1024 }, { 6, 279, 1024 },
{ 4, 280, 1024 }, { 5, 281, 1024 }, { 5, 282, 1024 }, { 6, 283, 1024 }, { 5, 284, 1024 }, { 6, 285, 1024 }, { 6, 286, 1024 }, { 7, 287, 1024 },
{ 3, 288, 1024 }, { 4, 289, 1024 }, { 4, 290, 1024 }, { 5, 291, 1024 }, { 4, 292, 1024 }, { 5, 293, 1024 }, { 5, 294, 1024 }, { 6, 295, 1024 },
{ 4, 296, 1024 }, { 5, 297, 1024 }, { 5, 298, 1024 }, { 6, 299, 1024 }, { 5, 300, 1024 }, { 6, 301, 1024 }, { 6, 302, 1024 }, { 7, 303, 1024 },
{ 4, 304, 1024 }, { 5, 305, 1024 }, { 5, 306, 1024 }, { 6, 307, 1024 }, { 5, 308, 1024 }, { 6, 309, 1024 }, { 6, 310, 1024 }, { 7, 311, 1024 },
{ 5, 312, 1024 }, { 6, 313, 1024 }, { 6, 314, 1024 }, { 7, 315, 1024 }, { 6, 316, 1024 }, { 7, 317, 1024 }, { 7, 318, 1024 }, { 8, 319, 1024 },
{ 3, 320, 1024 }, { 4, 321, 1024 }, { 4, 322, 1024 }, { 5, 323, 1024 }, { 4, 324, 1024 }, { 5, 325, 1024 }, { 5, 326, 1024 }, { 6, 327, 1024 },
{ 4, 328, 1024 }, { 5, 329, 1024 }, { 5, 330, 1024 }, { 6, 331, 1024 }, { 5, 332, 1024 }, { 6, 333, 1024 }, { 6, 334, 1024 }, { 7, 335, 1024 },
{ 4, 336, 1024 }, { 5, 337, 1024 }, { 5, 338, 1024 }, { 6, 339, 1024 }, { 5, 340, 1024 }, { 6, 341, 1024 }, { 6, 342, 1024 }, { 7, 343, 1024 },
{ 5, 344, 1024 }, { 6, 345, 1024 }, { 6, 346, 1024 }, { 7, 347, 1024 }, { 6, 348, 1024 }, { 7, 349, 1024 }, { 7, 350, 1024 }, { 8, 351, 1024 },
{ 4, 352, 1024 }, { 5, 353, 1024 }, { 5, 354, 1024 }, { 6, 355, 1024 }, { 5, 356, 1024 }, { 6, 357, 1024 }, { 6, 358, 1024 }, { 7, 359, 1024 },
{ 5, 360, 1024 }, { 6, 361, 1024 }, { 6, 362, 1024 }, { 7, 363, 1024 }, { 6, 364, 1024 }, { 7, 365, 1024 }, { 7, 366, 1024 }, { 8, 367, 1024 },
{ 5, 368, 1024 }, { 6, 369, 1024 }, { 6, 370, 1024 }, { 7, 371, 1024 }, { 6, 372, 1024 }, { 7, 373, 1024 }, { 7, 374, 1024 }, { 8, 375, 1024 },
{ 6, 376, 1024 }, { 7, 377, 1024 }, { 7, 378, 1024 }, { 8, 379, 1024 }, { 7, 380, 1024 }, { 8, 381, 1024 }, { 8, 382, 1024 }, { 9, 383, 1024 },
{ 3, 384, 1024 }, { 4, 385, 1024 }, { 4, 386, 1024 }, { 5, 387, 1024 }, { 4, 388, 1024 }, { 5, 389, 1024 }, { 5, 390, 1024 }, { 6, 391, 1024 },
{ 4, 392, 1024 }, { 5, 393, 1024 }, { 5, 394, 1024 }, { 6, 395, 1024 }, { 5, 396, 1024 }, { 6, 397, 1024 }, { 6, 398, 1024 }, { 7, 399, 1024 },
{ 4, 400, 1024 }, { 5, 401, 1024 }, { 5, 402, 1024 }, { 6, 403, 1024 }, { 5, 404, 1024 }, { 6, 405, 1024 }, { 6, 406, 1024 }, { 7, 407, 1024 },
{ 5, 408, 1024 }, { 6, 409, 1024 }, { 6, 410, 1024 }, { 7, 411, 1024 }, { 6, 412, 1024 }, { 7, 413, 1024 }, { 7, 414, 1024 }, { 8, 415, 1024 },
{ 4, 416, 1024 }, { 5, 417, 1024 }, { 5, 418, 1024 }, { 6, 419, 1024 }, { 5, 420, 1024 }, { 6, 421, 1024 }, { 6, 422, 1024 }, { 7, 423, 1024 },
{ 5, 424, 1024 }, { 6, 425, 1024 }, { 6, 426, 1024 }, { 7, 427, 1024 }, { 6, 428, 1024 }, { 7, 429, 1024 }, { 7, 430, 1024 }, { 8, 431, 1024 },
{ 5, 432, 1024 }, { 6, 433, 1024 }, { 6, 434, 1024 }, { 7, 435, 1024 }, { 6, 436, 1024 }, { 7, 437, 1024 }, { 7, 438, 1024 }, { 8, 439, 1024 },
{ 6, 440, 1024 }, { 7, 441, 1024 }, { 7, 442, 1024 }, { 8, 443, 1024 }, { 7, 444, 1024 }, { 8, 445, 1024 }, { 8, 446, 1024 }, { 9, 447, 1024 },
{ 4, 448, 1024 }, { 5, 449, 1024 }, { 5, 450, 1024 }, { 6, 451, 1024 }, { 5, 452, 1024 }, { 6, 453, 1024 }, { 6, 454, 1024 }, { 7, 455, 1024 },
{ 5, 456, 1024 }, { 6, 457, 1024 }, { 6, 458, 1024 }, { 7, 459, 1024 }, { 6, 460, 1024 }, { 7, 461, 1024 }, { 7, 462, 1024 }, { 8, 463, 1024 },
{ 5, 464, 1024 }, { 6, 465, 1024 }, { 6, 466, 1024 }, { 7, 467, 1024 }, { 6, 468, 1024 }, { 7, 469, 1024 }, { 7, 470, 1024 }, { 8, 471, 1024 },
{ 6, 472, 1024 }, { 7, 473, 1024 }, { 7, 474, 1024 }, { 8, 475, 1024 }, { 7, 476, 1024 }, { 8, 477, 1024 }, { 8, 478, 1024 }, { 9, 479, 1024 },
{ 5, 480, 1024 }, { 6, 481, 1024 }, { 6, 482, 1024 }, { 7, 483, 1024 }, { 6, 484, 1024 }, { 7, 485, 1024 }, { 7, 486, 1024 }, { 8, 487, 1024 },
{ 6, 488, 1024 }, { 7, 489, 1024 }, { 7, 490, 1024 }, { 8, 491, 1024 }, { 7, 492, 1024 }, { 8, 493, 1024 }, { 8, 494, 1024 }, { 9, 495, 1024 },
{ 6, 496, 1024 }, { 7, 497, 1024 }, { 7, 498, 1024 }, { 8, 499, 1024 }, { 7, 500, 1024 }, { 8, 501, 1024 }, { 8, 502, 1024 }, { 9, 503, 1024 },
{ 7, 504, 1024 }, { 8, 505, 1024 }, { 8, 506, 1024 }, { 9, 507, 1024 }, { 8, 508, 1024 }, { 9, 509, 1024 }, { 9, 510, 1024 }, { 10, 511, 1024 },
{ 2, 512, 1024 }, { 3, 513, 1024 }, { 3, 514, 1024 }, { 4, 515, 1024 }, { 3, 516, 1024 }, { 4, 517, 1024 }, { 4, 518, 1024 }, { 5, 519, 1024 },
{ 3, 520, 1024 }, { 4, 521, 1024 }, { 4, 522, 1024 }, { 5, 523, 1024 }, { 4, 524, 1024 }, { 5, 525, 1024 }, { 5, 526, 1024 }, { 6, 527, 1024 },
{ 3, 528, 1024 }, { 4, 529, 1024 }, { 4, 530, 1024 }, { 5, 531, 1024 }, { 4, 532, 1024 }, { 5, 533, 1024 }, { 5, 534, 1024 }, { 6, 535, 1024 },
{ 4, 536, 1024 }, { 5, 537, 1024 }, { 5, 538, 1024 }, { 6, 539, 1024 }, { 5, 540, 1024 }, { 6, 541, 1024 }, { 6, 542, 1024 }, { 7, 543, 1024 },
{ 3, 544, 1024 }, { 4, 545, 1024 }, { 4, 546, 1024 }, { 5, 547, 1024 }, { 4, 548, 1024 }, { 5, 549, 1024 }, { 5, 550, 1024 }, { 6, 551, 1024 },
{ 4, 552, 1024 }, { 5, 553, 1024 }, { 5, 554, 1024 }, { 6, 555, 1024 }, { 5, 556, 1024 }, { 6, 557, 1024 }, { 6, 558, 1024 }, { 7, 559, 1024 },
{ 4, 560, 1024 }, { 5, 561, 1024 }, { 5, 562, 1024 }, { 6, 563, 1024 }, { 5, 564, 1024 }, { 6, 565, 1024 }, { 6, 566, 1024 }, { 7, 567, 1024 },
{ 5, 568, 1024 }, { 6, 569, 1024 }, { 6, 570, 1024 }, { 7, 571, 1024 }, { 6, 572, 1024 }, { 7, 573, 1024 }, { 7, 574, 1024 }, { 8, 575, 1024 },
{ 3, 576, 1024 }, { 4, 577, 1024 }, { 4, 578, 1024 }, { 5, 579, 1024 }, { 4, 580, 1024 }, { 5, 581, 1024 }, { 5, 582, 1024 }, { 6, 583, 1024 },
{ 4, 584, 1024 }, { 5, 585, 1024 }, { 5, 586, 1024 }, { 6, 587, 1024 }, { 5, 588, 1024 }, { 6, 589, 1024 }, { 6, 590, 1024 }, { 7, 591, 1024 },
{ 4, 592, 1024 }, { 5, 593, 1024 }, { 5, 594, 1024 }, { 6, 595, 1024 }, { 5, 596, 1024 }, { 6, 597, 1024 }, { 6, 598, 1024 }, { 7, 599, 1024 },
{ 5, 600, 1024 }, { 6, 601, 1024 }, { 6, 602, 1024 }, { 7, 603, 1024 }, { 6, 604, 1024 }, { 7, 605, 1024 }, { 7, 606, 1024 }, { 8, 607, 1024 },
{ 4, 608, 1024 }, { 5, 609, 1024 }, { 5, 610, 1024 }, { 6, 611, 1024 }, { 5, 612, 1024 }, { 6, 613, 1024 }, { 6, 614, 1024 }, { 7, 615, 1024 },
{ 5, 616, 1024 }, { 6, 617, 1024 }, { 6, 618, 1024 }, { 7, 619, 1024 }, { 6, 620, 1024 }, { 7, 621, 1024 }, { 7, 622, 1024 }, { 8, 623, 1024 },
{ 5, 624, 1024 }, { 6, 625, 1024 }, { 6, 626, 1024 }, { 7, 627, 1024 }, { 6, 628, 1024 }, { 7, 629, 1024 }, { 7, 630, 1024 }, { 8, 631, 1024 },
{ 6, 632, 1024 }, { 7, 633, 1024 }, { 7, 634, 1024 }, { 8, 635, 1024 }, { 7, 636, 1024 }, { 8, 637, 1024 }, { 8, 638, 1024 }, { 9, 639, 1024 },
{ 3, 640, 1024 }, { 4, 641, 1024 }, { 4, 642, 1024 }, { 5, 643, 1024 }, { 4, 644, 1024 }, { 5, 645, 1024 }, { 5, 646, 1024 }, { 6, 647, 1024 },
{ 4, 648, 1024 }, { 5, 649, 1024 }, { 5, 650, 1024 }, { 6, 651, 1024 }, { 5, 652, 1024 }, { 6, 653, 1024 }, { 6, 654, 1024 }, { 7, 655, 1024 },
{ 4, 656, 1024 }, { 5, 657, 1024 }, { 5, 658, 1024 }, { 6, 659, 1024 }, { 5, 660, 1024 }, { 6, 661, 1024 }, { 6, 662, 1024 }, { 7, 663, 1024 },
{ 5, 664, 1024 }, { 6, 665, 1024 }, { 6, 666, 1024 }, { 7, 667, 1024 }, { 6, 668, 1024 }, { 7, 669, 1024 }, { 7, 670, 1024 }, { 8, 671, 1024 },
{ 4, 672, 1024 }, { 5, 673, 1024 }, { 5, 674, 1024 }, { 6, 675, 1024 }, { 5, 676, 1024 }, { 6, 677, 1024 }, { 6, 678, 1024 }, { 7, 679, 1024 },
{ 5, 680, 1024 }, { 6, 681, 1024 }, { 6, 682, 1024 }, { 7, 683, 1024 }, { 6, 684, 1024 }, { 7, 685, 1024 }, { 7, 686, 1024 }, { 8, 687, 1024 },
{ 5, 688, 1024 }, { 6, 689, 1024 }, { 6, 690, 1024 }, { 7, 691, 1024 }, { 6, 692, 1024 }, { 7, 693, 1024 }, { 7, 694, 1024 }, { 8, 695, 1024 },
{ 6, 696, 1024 }, { 7, 697, 1024 }, { 7, 698, 1024 }, { 8, 699, 1024 }, { 7, 700, 1024 }, { 8, 701, 1024 }, { 8, 702, 1024 }, { 9, 703, 1024 },
{ 4, 704, 1024 }, { 5, 705, 1024 }, { 5, 706, 1024 }, { 6, 707, 1024 }, { 5, 708, 1024 }, { 6, 709, 1024 }, { 6, 710, 1024 }, { 7, 711, 1024 },
{ 5, 712, 1024 }, { 6, 713, 1024 }, { 6, 714, 1024 }, { 7, 715, 1024 }, { 6, 716, 1024 }, { 7, 717, 1024 }, { 7, 718, 1024 }, { 8, 719, 1024 },
{ 5, 720, 1024 }, { 6, 721, 1024 }, { 6, 722, 1024 }, { 7, 723, 1024 }, { 6, 724, 1024 }, { 7, 725, 1024 }, { 7, 726, 1024 }, { 8, 727, 1024 },
{ 6, 728, 1024 }, { 7, 729, 1024 }, { 7, 730, 1024 }, { 8, 731, 1024 }, { 7, 732, 1024 }, { 8, 733, 1024 }, { 8, 734, 1024 }, { 9, 735, 1024 },
{ 5, 736, 1024 }, { 6, 737, 1024 }, { 6, 738, 1024 }, { 7, 739, 1024 }, { 6, 740, 1024 }, { 7, 741, 1024 }, { 7, 742, 1024 }, { 8, 743, 1024 },
{ 6, 744, 1024 }, { 7, 745, 1024 }, { 7, 746, 1024 }, { 8, 747, 1024 }, { 7, 748, 1024 }, { 8, 749, 1024 }, { 8, 750, 1024 }, { 9, 751, 1024 },
{ 6, 752, 1024 }, { 7, 753, 1024 }, { 7, 754, 1024 }, { 8, 755, 1024 }, { 7, 756, 1024 }, { 8, 757, 1024 }, { 8, 758, 1024 }, { 9, 759, 1024 },
{ 7, 760, 1024 }, { 8, 761, 1024 }, { 8, 762, 1024 }, { 9, 763, 1024 }, { 8, 764, 1024 }, { 9, 765, 1024 }, { 9, 766, 1024 }, { 10, 767, 1024 },
{ 3, 768, 1024 }, { 4, 769, 1024 }, { 4, 770, 1024 }, { 5, 771, 1024 }, { 4, 772, 1024 }, { 5, 773, 1024 }, { 5, 774, 1024 }, { 6, 775, 1024 },
{ 4, 776, 1024 }, { 5, 777, 1024 }, { 5, 778, 1024 }, { 6, 779, 1024 }, { 5, 780, 1024 }, { 6, 781, 1024 }, { 6, 782, 1024 }, { 7, 783, 1024 },
{ 4, 784, 1024 }, { 5, 785, 1024 }, { 5, 786, 1024 }, { 6, 787, 1024 }, { 5, 788, 1024 }, { 6, 789, 1024 }, { 6, 790, 1024 }, { 7, 791, 1024 },
{ 5, 792, 1024 }, { 6, 793, 1024 }, { 6, 794, 1024 }, { 7, 795, 1024 }, { 6, 796, 1024 }, { 7, 797, 1024 }, { 7, 798, 1024 }, { 8, 799, 1024 },
{ 4, 800, 1024 }, { 5, 801, 1024 }, { 5, 802, 1024 }, { 6, 803, 1024 }, { 5, 804, 1024 }, { 6, 805, 1024 }, { 6, 806, 1024 }, { 7, 807, 1024 },
{ 5, 808, 1024 }, { 6, 809, 1024 }, { 6, 810, 1024 }, { 7, 811, 1024 }, { 6, 812, 1024 }, { 7, 813, 1024 }, { 7, 814, 1024 }, { 8, 815, 1024 },
{ 5, 816, 1024 }, { 6, 817, 1024 }, { 6, 818, 1024 }, { 7, 819, 1024 }, { 6, 820, 1024 }, { 7, 821, 1024 }, { 7, 822, 1024 }, { 8, 823, 1024 },
{ 6, 824, 1024 }, { 7, 825, 1024 }, { 7, 826, 1024 }, { 8, 827, 1024 }, { 7, 828, 1024 }, { 8, 829, 1024 }, { 8, 830, 1024 }, { 9, 831, 1024 },
{ 4, 832, 1024 }, { 5, 833, 1024 }, { 5, 834, 1024 }, { 6, 835, 1024 }, { 5, 836, 1024 }, { 6, 837, 1024 }, { 6, 838, 1024 }, { 7, 839, 1024 },
{ 5, 840, 1024 }, { 6, 841, 1024 }, { 6, 842, 1024 }, { 7, 843, 1024 }, { 6, 844, 1024 }, { 7, 845, 1024 }, { 7, 846, 1024 }, { 8, 847, 1024 },
{ 5, 848, 1024 }, { 6, 849, 1024 }, { 6, 850, 1024 }, { 7, 851, 1024 }, { 6, 852, 1024 }, { 7, 853, 1024 }, { 7, 854, 1024 }, { 8, 855, 1024 },
{ 6, 856, 1024 }, { 7, 857, 1024 }, { 7, 858, 1024 }, { 8, 859, 1024 }, { 7, 860, 1024 }, { 8, 861, 1024 }, { 8, 862, 1024 }, { 9, 863, 1024 },
{ 5, 864, 1024 }, { 6, 865, 1024 }, { 6, 866, 1024 }, { 7, 867, 1024 }, { 6, 868, 1024 }, { 7, 869, 1024 }, { 7, 870, 1024 }, { 8, 871, 1024 },
{ 6, 872, 1024 }, { 7, 873, 1024 }, { 7, 874, 1024 }, { 8, 875, 1024 }, { 7, 876, 1024 }, { 8, 877, 1024 }, { 8, 878, 1024 }, { 9, 879, 1024 },
{ 6, 880, 1024 }, { 7, 881, 1024 }, { 7, 882, 1024 }, { 8, 883, 1024 }, { 7, 884, 1024 }, { 8, 885, 1024 }, { 8, 886, 1024 }, { 9, 887, 1024 },
{ 7, 888, 1024 }, { 8, 889, 1024 }, { 8, 890, 1024 }, { 9, 891, 1024 }, { 8, 892, 1024 }, { 9, 893, 1024 }, { 9, 894, 1024 }, { 10, 895, 1024 },
{ 4, 896, 1024 }, { 5, 897, 1024 }, { 5, 898, 1024 }, { 6, 899, 1024 }, { 5, 900, 1024 }, { 6, 901, 1024 }, { 6, 902, 1024 }, { 7, 903, 1024 },
{ 5, 904, 1024 }, { 6, 905, 1024 }, { 6, 906, 1024 }, { 7, 907, 1024 }, { 6, 908, 1024 }, { 7, 909, 1024 }, { 7, 910, 1024 }, { 8, 911, 1024 },
{ 5, 912, 1024 }, { 6, 913, 1024 }, { 6, 914, 1024 }, { 7, 915, 1024 }, { 6, 916, 1024 }, { 7, 917, 1024 }, { 7, 918, 1024 }, { 8, 919, 1024 },
{ 6, 920, 1024 }, { 7, 921, 1024 }, { 7, 922, 1024 }, { 8, 923, 1024 }, { 7, 924, 1024 }, { 8, 925, 1024 }, { 8, 926, 1024 }, { 9, 927, 1024 },
{ 5, 928, 1024 }, { 6, 929, 1024 }, { 6, 930, 1024 }, { 7, 931, 1024 }, { 6, 932, 1024 }, { 7, 933, 1024 }, { 7, 934, 1024 }, { 8, 935, 1024 },
{ 6, 936, 1024 }, { 7, 937, 1024 }, { 7, 938, 1024 }, { 8, 939, 1024 }, { 7, 940, 1024 }, { 8, 941, 1024 }, { 8, 942, 1024 }, { 9, 943, 1024 },
{ 6, 944, 1024 }, { 7, 945, 1024 }, { 7, 946, 1024 }, { 8, 947, 1024 }, { 7, 948, 1024 }, { 8, 949, 1024 }, { 8, 950, 1024 }, { 9, 951, 1024 },
{ 7, 952, 1024 }, { 8, 953, 1024 }, { 8, 954, 1024 }, { 9, 955, 1024 }, { 8, 956, 1024 }, { 9, 957, 1024 }, { 9, 958, 1024 }, { 10, 959, 1024 },
{ 5, 960, 1024 }, { 6, 961, 1024 }, { 6, 962, 1024 }, { 7, 963, 1024 }, { 6, 964, 1024 }, { 7, 965, 1024 }, { 7, 966, 1024 }, { 8, 967, 1024 },
{ 6, 968, 1024 }, { 7, 969, 1024 }, { 7, 970, 1024 }, { 8, 971, 1024 }, { 7, 972, 1024 }, { 8, 973, 1024 }, { 8, 974, 1024 }, { 9, 975, 1024 },
{ 6, 976, 1024 }, { 7, 977, 1024 }, { 7, 978, 1024 }, { 8, 979, 1024 }, { 7, 980, 1024 }, { 8, 981, 1024 }, { 8, 982, 1024 }, { 9, 983, 1024 },
{ 7, 984, 1024 }, { 8, 985, 1024 }, { 8, 986, 1024 }, { 9, 987, 1024 }, { 8, 988, 1024 }, { 9, 989, 1024 }, { 9, 990, 1024 }, { 10, 991, 1024 },
{ 6, 992, 1024 }, { 7, 993, 1024 }, { 7, 994, 1024 }, { 8, 995, 1024 }, { 7, 996, 1024 }, { 8, 997, 1024 }, { 8, 998, 1024 }, { 9, 999, 1024 },
{ 7, 1000, 1024 }, { 8, 1001, 1024 }, { 8, 1002, 1024 }, { 9, 1003, 1024 }, { 8, 1004, 1024 }, { 9, 1005, 1024 }, { 9, 1006, 1024 }, { 10, 1007, 1024 },
{ 7, 1008, 1024 }, { 8, 1009, 1024 }, { 8, 1010, 1024 }, { 9, 1011, 1024 }, { 8, 1012, 1024 }, { 9, 1013, 1024 }, { 9, 1014, 1024 }, { 10, 1015, 1024 },
{ 8, 1016, 1024 }, { 9, 1017, 1024 }, { 9, 1018, 1024 }, { 10, 1019, 1024 }, { 9, 1020, 1024 }, { 10, 1021, 1024 }, { 10, 1022, 1024 }, { 11, 1023, 1024 },
#if FP_LUT > 11
{ 1, 0, 0 }, { 2, 1, 2048 }, { 2, 2, 2048 }, { 3, 3, 2048 }, { 2, 4, 2048 }, { 3, 5, 2048 }, { 3, 6, 2048 }, { 4, 7, 2048 },
{ 2, 8, 2048 }, { 3, 9, 2048 }, { 3, 10, 2048 }, { 4, 11, 2048 }, { 3, 12, 2048 }, { 4, 13, 2048 }, { 4, 14, 2048 }, { 5, 15, 2048 },
{ 2, 16, 2048 }, { 3, 17, 2048 }, { 3, 18, 2048 }, { 4, 19, 2048 }, { 3, 20, 2048 }, { 4, 21, 2048 }, { 4, 22, 2048 }, { 5, 23, 2048 },
{ 3, 24, 2048 }, { 4, 25, 2048 }, { 4, 26, 2048 }, { 5, 27, 2048 }, { 4, 28, 2048 }, { 5, 29, 2048 }, { 5, 30, 2048 }, { 6, 31, 2048 },
{ 2, 32, 2048 }, { 3, 33, 2048 }, { 3, 34, 2048 }, { 4, 35, 2048 }, { 3, 36, 2048 }, { 4, 37, 2048 }, { 4, 38, 2048 }, { 5, 39, 2048 },
{ 3, 40, 2048 }, { 4, 41, 2048 }, { 4, 42, 2048 }, { 5, 43, 2048 }, { 4, 44, 2048 }, { 5, 45, 2048 }, { 5, 46, 2048 }, { 6, 47, 2048 },
{ 3, 48, 2048 }, { 4, 49, 2048 }, { 4, 50, 2048 }, { 5, 51, 2048 }, { 4, 52, 2048 }, { 5, 53, 2048 }, { 5, 54, 2048 }, { 6, 55, 2048 },
{ 4, 56, 2048 }, { 5, 57, 2048 }, { 5, 58, 2048 }, { 6, 59, 2048 }, { 5, 60, 2048 }, { 6, 61, 2048 }, { 6, 62, 2048 }, { 7, 63, 2048 },
{ 2, 64, 2048 }, { 3, 65, 2048 }, { 3, 66, 2048 }, { 4, 67, 2048 }, { 3, 68, 2048 }, { 4, 69, 2048 }, { 4, 70, 2048 }, { 5, 71, 2048 },
{ 3, 72, 2048 }, { 4, 73, 2048 }, { 4, 74, 2048 }, { 5, 75, 2048 }, { 4, 76, 2048 }, { 5, 77, 2048 }, { 5, 78, 2048 }, { 6, 79, 2048 },
{ 3, 80, 2048 }, { 4, 81, 2048 }, { 4, 82, 2048 }, { 5, 83, 2048 }, { 4, 84, 2048 }, { 5, 85, 2048 }, { 5, 86, 2048 }, { 6, 87, 2048 },
{ 4, 88, 2048 }, { 5, 89, 2048 }, { 5, 90, 2048 }, { 6, 91, 2048 }, { 5, 92, 2048 }, { 6, 93, 2048 }, { 6, 94, 2048 }, { 7, 95, 2048 },
{ 3, 96, 2048 }, { 4, 97, 2048 }, { 4, 98, 2048 }, { 5, 99, 2048 }, { 4, 100, 2048 }, { 5, 101, 2048 }, { 5, 102, 2048 }, { 6, 103, 2048 },
{ 4, 104, 2048 }, { 5, 105, 2048 }, { 5, 106, 2048 }, { 6, 107, 2048 }, { 5, 108, 2048 }, { 6, 109, 2048 }, { 6, 110, 2048 }, { 7, 111, 2048 },
{ 4, 112, 2048 }, { 5, 113, 2048 }, { 5, 114, 2048 }, { 6, 115, 2048 }, { 5, 116, 2048 }, { 6, 117, 2048 }, { 6, 118, 2048 }, { 7, 119, 2048 },
{ 5, 120, 2048 }, { 6, 121, 2048 }, { 6, 122, 2048 }, { 7, 123, 2048 }, { 6, 124, 2048 }, { 7, 125, 2048 }, { 7, 126, 2048 }, { 8, 127, 2048 },
{ 2, 128, 2048 }, { 3, 129, 2048 }, { 3, 130, 2048 }, { 4, 131, 2048 }, { 3, 132, 2048 }, { 4, 133, 2048 }, { 4, 134, 2048 }, { 5, 135, 2048 },
{ 3, 136, 2048 }, { 4, 137, 2048 }, { 4, 138, 2048 }, { 5, 139, 2048 }, { 4, 140, 2048 }, { 5, 141, 2048 }, { 5, 142, 2048 }, { 6, 143, 2048 },
{ 3, 144, 2048 }, { 4, 145, 2048 }, { 4, 146, 2048 }, { 5, 147, 2048 }, { 4, 148, 2048 }, { 5, 149, 2048 }, { 5, 150, 2048 }, { 6, 151, 2048 },
{ 4, 152, 2048 }, { 5, 153, 2048 }, { 5, 154, 2048 }, { 6, 155, 2048 }, { 5, 156, 2048 }, { 6, 157, 2048 }, { 6, 158, 2048 }, { 7, 159, 2048 },
{ 3, 160, 2048 }, { 4, 161, 2048 }, { 4, 162, 2048 }, { 5, 163, 2048 }, { 4, 164, 2048 }, { 5, 165, 2048 }, { 5, 166, 2048 }, { 6, 167, 2048 },
{ 4, 168, 2048 }, { 5, 169, 2048 }, { 5, 170, 2048 }, { 6, 171, 2048 }, { 5, 172, 2048 }, { 6, 173, 2048 }, { 6, 174, 2048 }, { 7, 175, 2048 },
{ 4, 176, 2048 }, { 5, 177, 2048 }, { 5, 178, 2048 }, { 6, 179, 2048 }, { 5, 180, 2048 }, { 6, 181, 2048 }, { 6, 182, 2048 }, { 7, 183, 2048 },
{ 5, 184, 2048 }, { 6, 185, 2048 }, { 6, 186, 2048 }, { 7, 187, 2048 }, { 6, 188, 2048 }, { 7, 189, 2048 }, { 7, 190, 2048 }, { 8, 191, 2048 },
{ 3, 192, 2048 }, { 4, 193, 2048 }, { 4, 194, 2048 }, { 5, 195, 2048 }, { 4, 196, 2048 }, { 5, 197, 2048 }, { 5, 198, 2048 }, { 6, 199, 2048 },
{ 4, 200, 2048 }, { 5, 201, 2048 }, { 5, 202, 2048 }, { 6, 203, 2048 }, { 5, 204, 2048 }, { 6, 205, 2048 }, { 6, 206, 2048 }, { 7, 207, 2048 },
{ 4, 208, 2048 }, { 5, 209, 2048 }, { 5, 210, 2048 }, { 6, 211, 2048 }, { 5, 212, 2048 }, { 6, 213, 2048 }, { 6, 214, 2048 }, { 7, 215, 2048 },
{ 5, 216, 2048 }, { 6, 217, 2048 }, { 6, 218, 2048 }, { 7, 219, 2048 }, { 6, 220, 2048 }, { 7, 221, 2048 }, { 7, 222, 2048 }, { 8, 223, 2048 },
{ 4, 224, 2048 }, { 5, 225, 2048 }, { 5, 226, 2048 }, { 6, 227, 2048 }, { 5, 228, 2048 }, { 6, 229, 2048 }, { 6, 230, 2048 }, { 7, 231, 2048 },
{ 5, 232, 2048 }, { 6, 233, 2048 }, { 6, 234, 2048 }, { 7, 235, 2048 }, { 6, 236, 2048 }, { 7, 237, 2048 }, { 7, 238, 2048 }, { 8, 239, 2048 },
{ 5, 240, 2048 }, { 6, 241, 2048 }, { 6, 242, 2048 }, { 7, 243, 2048 }, { 6, 244, 2048 }, { 7, 245, 2048 }, { 7, 246, 2048 }, { 8, 247, 2048 },
{ 6, 248, 2048 }, { 7, 249, 2048 }, { 7, 250, 2048 }, { 8, 251, 2048 }, { 7, 252, 2048 }, { 8, 253, 2048 }, { 8, 254, 2048 }, { 9, 255, 2048 },
{ 2, 256, 2048 }, { 3, 257, 2048 }, { 3, 258, 2048 }, { 4, 259, 2048 }, { 3, 260, 2048 }, { 4, 261, 2048 }, { 4, 262, 2048 }, { 5, 263, 2048 },
{ 3, 264, 2048 }, { 4, 265, 2048 }, { 4, 266, 2048 }, { 5, 267, 2048 }, { 4, 268, 2048 }, { 5, 269, 2048 }, { 5, 270, 2048 }, { 6, 271, 2048 },
{ 3, 272, 2048 }, { 4, 273, 2048 }, { 4, 274, 2048 }, { 5, 275, 2048 }, { 4, 276, 2048 }, { 5, 277, 2048 }, { 5, 278, 2048 }, { 6, 279, 2048 },
{ 4, 280, 2048 }, { 5, 281, 2048 }, { 5, 282, 2048 }, { 6, 283, 2048 }, { 5, 284, 2048 }, { 6, 285, 2048 }, { 6, 286, 2048 }, { 7, 287, 2048 },
{ 3, 288, 2048 }, { 4, 289, 2048 }, { 4, 290, 2048 }, { 5, 291, 2048 }, { 4, 292, 2048 }, { 5, 293, 2048 }, { 5, 294, 2048 }, { 6, 295, 2048 },
{ 4, 296, 2048 }, { 5, 297, 2048 }, { 5, 298, 2048 }, { 6, 299, 2048 }, { 5, 300, 2048 }, { 6, 301, 2048 }, { 6, 302, 2048 }, { 7, 303, 2048 },
{ 4, 304, 2048 }, { 5, 305, 2048 }, { 5, 306, 2048 }, { 6, 307, 2048 }, { 5, 308, 2048 }, { 6, 309, 2048 }, { 6, 310, 2048 }, { 7, 311, 2048 },
{ 5, 312, 2048 }, { 6, 313, 2048 }, { 6, 314, 2048 }, { 7, 315, 2048 }, { 6, 316, 2048 }, { 7, 317, 2048 }, { 7, 318, 2048 }, { 8, 319, 2048 },
{ 3, 320, 2048 }, { 4, 321, 2048 }, { 4, 322, 2048 }, { 5, 323, 2048 }, { 4, 324, 2048 }, { 5, 325, 2048 }, { 5, 326, 2048 }, { 6, 327, 2048 },
{ 4, 328, 2048 }, { 5, 329, 2048 }, { 5, 330, 2048 }, { 6, 331, 2048 }, { 5, 332, 2048 }, { 6, 333, 2048 }, { 6, 334, 2048 }, { 7, 335, 2048 },
{ 4, 336, 2048 }, { 5, 337, 2048 }, { 5, 338, 2048 }, { 6, 339, 2048 }, { 5, 340, 2048 }, { 6, 341, 2048 }, { 6, 342, 2048 }, { 7, 343, 2048 },
{ 5, 344, 2048 }, { 6, 345, 2048 }, { 6, 346, 2048 }, { 7, 347, 2048 }, { 6, 348, 2048 }, { 7, 349, 2048 }, { 7, 350, 2048 }, { 8, 351, 2048 },
{ 4, 352, 2048 }, { 5, 353, 2048 }, { 5, 354, 2048 }, { 6, 355, 2048 }, { 5, 356, 2048 }, { 6, 357, 2048 }, { 6, 358, 2048 }, { 7, 359, 2048 },
{ 5, 360, 2048 }, { 6, 361, 2048 }, { 6, 362, 2048 }, { 7, 363, 2048 }, { 6, 364, 2048 }, { 7, 365, 2048 }, { 7, 366, 2048 }, { 8, 367, 2048 },
{ 5, 368, 2048 }, { 6, 369, 2048 }, { 6, 370, 2048 }, { 7, 371, 2048 }, { 6, 372, 2048 }, { 7, 373, 2048 }, { 7, 374, 2048 }, { 8, 375, 2048 },
{ 6, 376, 2048 }, { 7, 377, 2048 }, { 7, 378, 2048 }, { 8, 379, 2048 }, { 7, 380, 2048 }, { 8, 381, 2048 }, { 8, 382, 2048 }, { 9, 383, 2048 },
{ 3, 384, 2048 }, { 4, 385, 2048 }, { 4, 386, 2048 }, { 5, 387, 2048 }, { 4, 388, 2048 }, { 5, 389, 2048 }, { 5, 390, 2048 }, { 6, 391, 2048 },
{ 4, 392, 2048 }, { 5, 393, 2048 }, { 5, 394, 2048 }, { 6, 395, 2048 }, { 5, 396, 2048 }, { 6, 397, 2048 }, { 6, 398, 2048 }, { 7, 399, 2048 },
{ 4, 400, 2048 }, { 5, 401, 2048 }, { 5, 402, 2048 }, { 6, 403, 2048 }, { 5, 404, 2048 }, { 6, 405, 2048 }, { 6, 406, 2048 }, { 7, 407, 2048 },
{ 5, 408, 2048 }, { 6, 409, 2048 }, { 6, 410, 2048 }, { 7, 411, 2048 }, { 6, 412, 2048 }, { 7, 413, 2048 }, { 7, 414, 2048 }, { 8, 415, 2048 },
{ 4, 416, 2048 }, { 5, 417, 2048 }, { 5, 418, 2048 }, { 6, 419, 2048 }, { 5, 420, 2048 }, { 6, 421, 2048 }, { 6, 422, 2048 }, { 7, 423, 2048 },
{ 5, 424, 2048 }, { 6, 425, 2048 }, { 6, 426, 2048 }, { 7, 427, 2048 }, { 6, 428, 2048 }, { 7, 429, 2048 }, { 7, 430, 2048 }, { 8, 431, 2048 },
{ 5, 432, 2048 }, { 6, 433, 2048 }, { 6, 434, 2048 }, { 7, 435, 2048 }, { 6, 436, 2048 }, { 7, 437, 2048 }, { 7, 438, 2048 }, { 8, 439, 2048 },
{ 6, 440, 2048 }, { 7, 441, 2048 }, { 7, 442, 2048 }, { 8, 443, 2048 }, { 7, 444, 2048 }, { 8, 445, 2048 }, { 8, 446, 2048 }, { 9, 447, 2048 },
{ 4, 448, 2048 }, { 5, 449, 2048 }, { 5, 450, 2048 }, { 6, 451, 2048 }, { 5, 452, 2048 }, { 6, 453, 2048 }, { 6, 454, 2048 }, { 7, 455, 2048 },
{ 5, 456, 2048 }, { 6, 457, 2048 }, { 6, 458, 2048 }, { 7, 459, 2048 }, { 6, 460, 2048 }, { 7, 461, 2048 }, { 7, 462, 2048 }, { 8, 463, 2048 },
{ 5, 464, 2048 }, { 6, 465, 2048 }, { 6, 466, 2048 }, { 7, 467, 2048 }, { 6, 468, 2048 }, { 7, 469, 2048 }, { 7, 470, 2048 }, { 8, 471, 2048 },
{ 6, 472, 2048 }, { 7, 473, 2048 }, { 7, 474, 2048 }, { 8, 475, 2048 }, { 7, 476, 2048 }, { 8, 477, 2048 }, { 8, 478, 2048 }, { 9, 479, 2048 },
{ 5, 480, 2048 }, { 6, 481, 2048 }, { 6, 482, 2048 }, { 7, 483, 2048 }, { 6, 484, 2048 }, { 7, 485, 2048 }, { 7, 486, 2048 }, { 8, 487, 2048 },
{ 6, 488, 2048 }, { 7, 489, 2048 }, { 7, 490, 2048 }, { 8, 491, 2048 }, { 7, 492, 2048 }, { 8, 493, 2048 }, { 8, 494, 2048 }, { 9, 495, 2048 },
{ 6, 496, 2048 }, { 7, 497, 2048 }, { 7, 498, 2048 }, { 8, 499, 2048 }, { 7, 500, 2048 }, { 8, 501, 2048 }, { 8, 502, 2048 }, { 9, 503, 2048 },
{ 7, 504, 2048 }, { 8, 505, 2048 }, { 8, 506, 2048 }, { 9, 507, 2048 }, { 8, 508, 2048 }, { 9, 509, 2048 }, { 9, 510, 2048 }, { 10, 511, 2048 },
{ 2, 512, 2048 }, { 3, 513, 2048 }, { 3, 514, 2048 }, { 4, 515, 2048 }, { 3, 516, 2048 }, { 4, 517, 2048 }, { 4, 518, 2048 }, { 5, 519, 2048 },
{ 3, 520, 2048 }, { 4, 521, 2048 }, { 4, 522, 2048 }, { 5, 523, 2048 }, { 4, 524, 2048 }, { 5, 525, 2048 }, { 5, 526, 2048 }, { 6, 527, 2048 },
{ 3, 528, 2048 }, { 4, 529, 2048 }, { 4, 530, 2048 }, { 5, 531, 2048 }, { 4, 532, 2048 }, { 5, 533, 2048 }, { 5, 534, 2048 }, { 6, 535, 2048 },
{ 4, 536, 2048 }, { 5, 537, 2048 }, { 5, 538, 2048 }, { 6, 539, 2048 }, { 5, 540, 2048 }, { 6, 541, 2048 }, { 6, 542, 2048 }, { 7, 543, 2048 },
{ 3, 544, 2048 }, { 4, 545, 2048 }, { 4, 546, 2048 }, { 5, 547, 2048 }, { 4, 548, 2048 }, { 5, 549, 2048 }, { 5, 550, 2048 }, { 6, 551, 2048 },
{ 4, 552, 2048 }, { 5, 553, 2048 }, { 5, 554, 2048 }, { 6, 555, 2048 }, { 5, 556, 2048 }, { 6, 557, 2048 }, { 6, 558, 2048 }, { 7, 559, 2048 },
{ 4, 560, 2048 }, { 5, 561, 2048 }, { 5, 562, 2048 }, { 6, 563, 2048 }, { 5, 564, 2048 }, { 6, 565, 2048 }, { 6, 566, 2048 }, { 7, 567, 2048 },
{ 5, 568, 2048 }, { 6, 569, 2048 }, { 6, 570, 2048 }, { 7, 571, 2048 }, { 6, 572, 2048 }, { 7, 573, 2048 }, { 7, 574, 2048 }, { 8, 575, 2048 },
{ 3, 576, 2048 }, { 4, 577, 2048 }, { 4, 578, 2048 }, { 5, 579, 2048 }, { 4, 580, 2048 }, { 5, 581, 2048 }, { 5, 582, 2048 }, { 6, 583, 2048 },
{ 4, 584, 2048 }, { 5, 585, 2048 }, { 5, 586, 2048 }, { 6, 587, 2048 }, { 5, 588, 2048 }, { 6, 589, 2048 }, { 6, 590, 2048 }, { 7, 591, 2048 },
{ 4, 592, 2048 }, { 5, 593, 2048 }, { 5, 594, 2048 }, { 6, 595, 2048 }, { 5, 596, 2048 }, { 6, 597, 2048 }, { 6, 598, 2048 }, { 7, 599, 2048 },
{ 5, 600, 2048 }, { 6, 601, 2048 }, { 6, 602, 2048 }, { 7, 603, 2048 }, { 6, 604, 2048 }, { 7, 605, 2048 }, { 7, 606, 2048 }, { 8, 607, 2048 },
{ 4, 608, 2048 }, { 5, 609, 2048 }, { 5, 610, 2048 }, { 6, 611, 2048 }, { 5, 612, 2048 }, { 6, 613, 2048 }, { 6, 614, 2048 }, { 7, 615, 2048 },
{ 5, 616, 2048 }, { 6, 617, 2048 }, { 6, 618, 2048 }, { 7, 619, 2048 }, { 6, 620, 2048 }, { 7, 621, 2048 }, { 7, 622, 2048 }, { 8, 623, 2048 },
{ 5, 624, 2048 }, { 6, 625, 2048 }, { 6, 626, 2048 }, { 7, 627, 2048 }, { 6, 628, 2048 }, { 7, 629, 2048 }, { 7, 630, 2048 }, { 8, 631, 2048 },
{ 6, 632, 2048 }, { 7, 633, 2048 }, { 7, 634, 2048 }, { 8, 635, 2048 }, { 7, 636, 2048 }, { 8, 637, 2048 }, { 8, 638, 2048 }, { 9, 639, 2048 },
{ 3, 640, 2048 }, { 4, 641, 2048 }, { 4, 642, 2048 }, { 5, 643, 2048 }, { 4, 644, 2048 }, { 5, 645, 2048 }, { 5, 646, 2048 }, { 6, 647, 2048 },
{ 4, 648, 2048 }, { 5, 649, 2048 }, { 5, 650, 2048 }, { 6, 651, 2048 }, { 5, 652, 2048 }, { 6, 653, 2048 }, { 6, 654, 2048 }, { 7, 655, 2048 },
{ 4, 656, 2048 }, { 5, 657, 2048 }, { 5, 658, 2048 }, { 6, 659, 2048 }, { 5, 660, 2048 }, { 6, 661, 2048 }, { 6, 662, 2048 }, { 7, 663, 2048 },
{ 5, 664, 2048 }, { 6, 665, 2048 }, { 6, 666, 2048 }, { 7, 667, 2048 }, { 6, 668, 2048 }, { 7, 669, 2048 }, { 7, 670, 2048 }, { 8, 671, 2048 },
{ 4, 672, 2048 }, { 5, 673, 2048 }, { 5, 674, 2048 }, { 6, 675, 2048 }, { 5, 676, 2048 }, { 6, 677, 2048 }, { 6, 678, 2048 }, { 7, 679, 2048 },
{ 5, 680, 2048 }, { 6, 681, 2048 }, { 6, 682, 2048 }, { 7, 683, 2048 }, { 6, 684, 2048 }, { 7, 685, 2048 }, { 7, 686, 2048 }, { 8, 687, 2048 },
{ 5, 688, 2048 }, { 6, 689, 2048 }, { 6, 690, 2048 }, { 7, 691, 2048 }, { 6, 692, 2048 }, { 7, 693, 2048 }, { 7, 694, 2048 }, { 8, 695, 2048 },
{ 6, 696, 2048 }, { 7, 697, 2048 }, { 7, 698, 2048 }, { 8, 699, 2048 }, { 7, 700, 2048 }, { 8, 701, 2048 }, { 8, 702, 2048 }, { 9, 703, 2048 },
{ 4, 704, 2048 }, { 5, 705, 2048 }, { 5, 706, 2048 }, { 6, 707, 2048 }, { 5, 708, 2048 }, { 6, 709, 2048 }, { 6, 710, 2048 }, { 7, 711, 2048 },
{ 5, 712, 2048 }, { 6, 713, 2048 }, { 6, 714, 2048 }, { 7, 715, 2048 }, { 6, 716, 2048 }, { 7, 717, 2048 }, { 7, 718, 2048 }, { 8, 719, 2048 },
{ 5, 720, 2048 }, { 6, 721, 2048 }, { 6, 722, 2048 }, { 7, 723, 2048 }, { 6, 724, 2048 }, { 7, 725, 2048 }, { 7, 726, 2048 }, { 8, 727, 2048 },
{ 6, 728, 2048 }, { 7, 729, 2048 }, { 7, 730, 2048 }, { 8, 731, 2048 }, { 7, 732, 2048 }, { 8, 733, 2048 }, { 8, 734, 2048 }, { 9, 735, 2048 },
{ 5, 736, 2048 }, { 6, 737, 2048 }, { 6, 738, 2048 }, { 7, 739, 2048 }, { 6, 740, 2048 }, { 7, 741, 2048 }, { 7, 742, 2048 }, { 8, 743, 2048 },
{ 6, 744, 2048 }, { 7, 745, 2048 }, { 7, 746, 2048 }, { 8, 747, 2048 }, { 7, 748, 2048 }, { 8, 749, 2048 }, { 8, 750, 2048 }, { 9, 751, 2048 },
{ 6, 752, 2048 }, { 7, 753, 2048 }, { 7, 754, 2048 }, { 8, 755, 2048 }, { 7, 756, 2048 }, { 8, 757, 2048 }, { 8, 758, 2048 }, { 9, 759, 2048 },
{ 7, 760, 2048 }, { 8, 761, 2048 }, { 8, 762, 2048 }, { 9, 763, 2048 }, { 8, 764, 2048 }, { 9, 765, 2048 }, { 9, 766, 2048 }, { 10, 767, 2048 },
{ 3, 768, 2048 }, { 4, 769, 2048 }, { 4, 770, 2048 }, { 5, 771, 2048 }, { 4, 772, 2048 }, { 5, 773, 2048 }, { 5, 774, 2048 }, { 6, 775, 2048 },
{ 4, 776, 2048 }, { 5, 777, 2048 }, { 5, 778, 2048 }, { 6, 779, 2048 }, { 5, 780, 2048 }, { 6, 781, 2048 }, { 6, 782, 2048 }, { 7, 783, 2048 },
{ 4, 784, 2048 }, { 5, 785, 2048 }, { 5, 786, 2048 }, { 6, 787, 2048 }, { 5, 788, 2048 }, { 6, 789, 2048 }, { 6, 790, 2048 }, { 7, 791, 2048 },
{ 5, 792, 2048 }, { 6, 793, 2048 }, { 6, 794, 2048 }, { 7, 795, 2048 }, { 6, 796, 2048 }, { 7, 797, 2048 }, { 7, 798, 2048 }, { 8, 799, 2048 },
{ 4, 800, 2048 }, { 5, 801, 2048 }, { 5, 802, 2048 }, { 6, 803, 2048 }, { 5, 804, 2048 }, { 6, 805, 2048 }, { 6, 806, 2048 }, { 7, 807, 2048 },
{ 5, 808, 2048 }, { 6, 809, 2048 }, { 6, 810, 2048 }, { 7, 811, 2048 }, { 6, 812, 2048 }, { 7, 813, 2048 }, { 7, 814, 2048 }, { 8, 815, 2048 },
{ 5, 816, 2048 }, { 6, 817, 2048 }, { 6, 818, 2048 }, { 7, 819, 2048 }, { 6, 820, 2048 }, { 7, 821, 2048 }, { 7, 822, 2048 }, { 8, 823, 2048 },
{ 6, 824, 2048 }, { 7, 825, 2048 }, { 7, 826, 2048 }, { 8, 827, 2048 }, { 7, 828, 2048 }, { 8, 829, 2048 }, { 8, 830, 2048 }, { 9, 831, 2048 },
{ 4, 832, 2048 }, { 5, 833, 2048 }, { 5, 834, 2048 }, { 6, 835, 2048 }, { 5, 836, 2048 }, { 6, 837, 2048 }, { 6, 838, 2048 }, { 7, 839, 2048 },
{ 5, 840, 2048 }, { 6, 841, 2048 }, { 6, 842, 2048 }, { 7, 843, 2048 }, { 6, 844, 2048 }, { 7, 845, 2048 }, { 7, 846, 2048 }, { 8, 847, 2048 },
{ 5, 848, 2048 }, { 6, 849, 2048 }, { 6, 850, 2048 }, { 7, 851, 2048 }, { 6, 852, 2048 }, { 7, 853, 2048 }, { 7, 854, 2048 }, { 8, 855, 2048 },
{ 6, 856, 2048 }, { 7, 857, 2048 }, { 7, 858, 2048 }, { 8, 859, 2048 }, { 7, 860, 2048 }, { 8, 861, 2048 }, { 8, 862, 2048 }, { 9, 863, 2048 },
{ 5, 864, 2048 }, { 6, 865, 2048 }, { 6, 866, 2048 }, { 7, 867, 2048 }, { 6, 868, 2048 }, { 7, 869, 2048 }, { 7, 870, 2048 }, { 8, 871, 2048 },
{ 6, 872, 2048 }, { 7, 873, 2048 }, { 7, 874, 2048 }, { 8, 875, 2048 }, { 7, 876, 2048 }, { 8, 877, 2048 }, { 8, 878, 2048 }, { 9, 879, 2048 },
{ 6, 880, 2048 }, { 7, 881, 2048 }, { 7, 882, 2048 }, { 8, 883, 2048 }, { 7, 884, 2048 }, { 8, 885, 2048 }, { 8, 886, 2048 }, { 9, 887, 2048 },
{ 7, 888, 2048 }, { 8, 889, 2048 }, { 8, 890, 2048 }, { 9, 891, 2048 }, { 8, 892, 2048 }, { 9, 893, 2048 }, { 9, 894, 2048 }, { 10, 895, 2048 },
{ 4, 896, 2048 }, { 5, 897, 2048 }, { 5, 898, 2048 }, { 6, 899, 2048 }, { 5, 900, 2048 }, { 6, 901, 2048 }, { 6, 902, 2048 }, { 7, 903, 2048 },
{ 5, 904, 2048 }, { 6, 905, 2048 }, { 6, 906, 2048 }, { 7, 907, 2048 }, { 6, 908, 2048 }, { 7, 909, 2048 }, { 7, 910, 2048 }, { 8, 911, 2048 },
{ 5, 912, 2048 }, { 6, 913, 2048 }, { 6, 914, 2048 }, { 7, 915, 2048 }, { 6, 916, 2048 }, { 7, 917, 2048 }, { 7, 918, 2048 }, { 8, 919, 2048 },
{ 6, 920, 2048 }, { 7, 921, 2048 }, { 7, 922, 2048 }, { 8, 923, 2048 }, { 7, 924, 2048 }, { 8, 925, 2048 }, { 8, 926, 2048 }, { 9, 927, 2048 },
{ 5, 928, 2048 }, { 6, 929, 2048 }, { 6, 930, 2048 }, { 7, 931, 2048 }, { 6, 932, 2048 }, { 7, 933, 2048 }, { 7, 934, 2048 }, { 8, 935, 2048 },
{ 6, 936, 2048 }, { 7, 937, 2048 }, { 7, 938, 2048 }, { 8, 939, 2048 }, { 7, 940, 2048 }, { 8, 941, 2048 }, { 8, 942, 2048 }, { 9, 943, 2048 },
{ 6, 944, 2048 }, { 7, 945, 2048 }, { 7, 946, 2048 }, { 8, 947, 2048 }, { 7, 948, 2048 }, { 8, 949, 2048 }, { 8, 950, 2048 }, { 9, 951, 2048 },
{ 7, 952, 2048 }, { 8, 953, 2048 }, { 8, 954, 2048 }, { 9, 955, 2048 }, { 8, 956, 2048 }, { 9, 957, 2048 }, { 9, 958, 2048 }, { 10, 959, 2048 },
{ 5, 960, 2048 }, { 6, 961, 2048 }, { 6, 962, 2048 }, { 7, 963, 2048 }, { 6, 964, 2048 }, { 7, 965, 2048 }, { 7, 966, 2048 }, { 8, 967, 2048 },
{ 6, 968, 2048 }, { 7, 969, 2048 }, { 7, 970, 2048 }, { 8, 971, 2048 }, { 7, 972, 2048 }, { 8, 973, 2048 }, { 8, 974, 2048 }, { 9, 975, 2048 },
{ 6, 976, 2048 }, { 7, 977, 2048 }, { 7, 978, 2048 }, { 8, 979, 2048 }, { 7, 980, 2048 }, { 8, 981, 2048 }, { 8, 982, 2048 }, { 9, 983, 2048 },
{ 7, 984, 2048 }, { 8, 985, 2048 }, { 8, 986, 2048 }, { 9, 987, 2048 }, { 8, 988, 2048 }, { 9, 989, 2048 }, { 9, 990, 2048 }, { 10, 991, 2048 },
{ 6, 992, 2048 }, { 7, 993, 2048 }, { 7, 994, 2048 }, { 8, 995, 2048 }, { 7, 996, 2048 }, { 8, 997, 2048 }, { 8, 998, 2048 }, { 9, 999, 2048 },
{ 7, 1000, 2048 }, { 8, 1001, 2048 }, { 8, 1002, 2048 }, { 9, 1003, 2048 }, { 8, 1004, 2048 }, { 9, 1005, 2048 }, { 9, 1006, 2048 }, { 10, 1007, 2048 },
{ 7, 1008, 2048 }, { 8, 1009, 2048 }, { 8, 1010, 2048 }, { 9, 1011, 2048 }, { 8, 1012, 2048 }, { 9, 1013, 2048 }, { 9, 1014, 2048 }, { 10, 1015, 2048 },
{ 8, 1016, 2048 }, { 9, 1017, 2048 }, { 9, 1018, 2048 }, { 10, 1019, 2048 }, { 9, 1020, 2048 }, { 10, 1021, 2048 }, { 10, 1022, 2048 }, { 11, 1023, 2048 },
{ 2, 1024, 2048 }, { 3, 1025, 2048 }, { 3, 1026, 2048 }, { 4, 1027, 2048 }, { 3, 1028, 2048 }, { 4, 1029, 2048 }, { 4, 1030, 2048 }, { 5, 1031, 2048 },
{ 3, 1032, 2048 }, { 4, 1033, 2048 }, { 4, 1034, 2048 }, { 5, 1035, 2048 }, { 4, 1036, 2048 }, { 5, 1037, 2048 }, { 5, 1038, 2048 }, { 6, 1039, 2048 },
{ 3, 1040, 2048 }, { 4, 1041, 2048 }, { 4, 1042, 2048 }, { 5, 1043, 2048 }, { 4, 1044, 2048 }, { 5, 1045, 2048 }, { 5, 1046, 2048 }, { 6, 1047, 2048 },
{ 4, 1048, 2048 }, { 5, 1049, 2048 }, { 5, 1050, 2048 }, { 6, 1051, 2048 }, { 5, 1052, 2048 }, { 6, 1053, 2048 }, { 6, 1054, 2048 }, { 7, 1055, 2048 },
{ 3, 1056, 2048 }, { 4, 1057, 2048 }, { 4, 1058, 2048 }, { 5, 1059, 2048 }, { 4, 1060, 2048 }, { 5, 1061, 2048 }, { 5, 1062, 2048 }, { 6, 1063, 2048 },
{ 4, 1064, 2048 }, { 5, 1065, 2048 }, { 5, 1066, 2048 }, { 6, 1067, 2048 }, { 5, 1068, 2048 }, { 6, 1069, 2048 }, { 6, 1070, 2048 }, { 7, 1071, 2048 },
{ 4, 1072, 2048 }, { 5, 1073, 2048 }, { 5, 1074, 2048 }, { 6, 1075, 2048 }, { 5, 1076, 2048 }, { 6, 1077, 2048 }, { 6, 1078, 2048 }, { 7, 1079, 2048 },
{ 5, 1080, 2048 }, { 6, 1081, 2048 }, { 6, 1082, 2048 }, { 7, 1083, 2048 }, { 6, 1084, 2048 }, { 7, 1085, 2048 }, { 7, 1086, 2048 }, { 8, 1087, 2048 },
{ 3, 1088, 2048 }, { 4, 1089, 2048 }, { 4, 1090, 2048 }, { 5, 1091, 2048 }, { 4, 1092, 2048 }, { 5, 1093, 2048 }, { 5, 1094, 2048 }, { 6, 1095, 2048 },
{ 4, 1096, 2048 }, { 5, 1097, 2048 }, { 5, 1098, 2048 }, { 6, 1099, 2048 }, { 5, 1100, 2048 }, { 6, 1101, 2048 }, { 6, 1102, 2048 }, { 7, 1103, 2048 },
{ 4, 1104, 2048 }, { 5, 1105, 2048 }, { 5, 1106, 2048 }, { 6, 1107, 2048 }, { 5, 1108, 2048 }, { 6, 1109, 2048 }, { 6, 1110, 2048 }, { 7, 1111, 2048 },
{ 5, 1112, 2048 }, { 6, 1113, 2048 }, { 6, 1114, 2048 }, { 7, 1115, 2048 }, { 6, 1116, 2048 }, { 7, 1117, 2048 }, { 7, 1118, 2048 }, { 8, 1119, 2048 },
{ 4, 1120, 2048 }, { 5, 1121, 2048 }, { 5, 1122, 2048 }, { 6, 1123, 2048 }, { 5, 1124, 2048 }, { 6, 1125, 2048 }, { 6, 1126, 2048 }, { 7, 1127, 2048 },
{ 5, 1128, 2048 }, { 6, 1129, 2048 }, { 6, 1130, 2048 }, { 7, 1131, 2048 }, { 6, 1132, 2048 }, { 7, 1133, 2048 }, { 7, 1134, 2048 }, { 8, 1135, 2048 },
{ 5, 1136, 2048 }, { 6, 1137, 2048 }, { 6, 1138, 2048 }, { 7, 1139, 2048 }, { 6, 1140, 2048 }, { 7, 1141, 2048 }, { 7, 1142, 2048 }, { 8, 1143, 2048 },
{ 6, 1144, 2048 }, { 7, 1145, 2048 }, { 7, 1146, 2048 }, { 8, 1147, 2048 }, { 7, 1148, 2048 }, { 8, 1149, 2048 }, { 8, 1150, 2048 }, { 9, 1151, 2048 },
{ 3, 1152, 2048 }, { 4, 1153, 2048 }, { 4, 1154, 2048 }, { 5, 1155, 2048 }, { 4, 1156, 2048 }, { 5, 1157, 2048 }, { 5, 1158, 2048 }, { 6, 1159, 2048 },
{ 4, 1160, 2048 }, { 5, 1161, 2048 }, { 5, 1162, 2048 }, { 6, 1163, 2048 }, { 5, 1164, 2048 }, { 6, 1165, 2048 }, { 6, 1166, 2048 }, { 7, 1167, 2048 },
{ 4, 1168, 2048 }, { 5, 1169, 2048 }, { 5, 1170, 2048 }, { 6, 1171, 2048 }, { 5, 1172, 2048 }, { 6, 1173, 2048 }, { 6, 1174, 2048 }, { 7, 1175, 2048 },
{ 5, 1176, 2048 }, { 6, 1177, 2048 }, { 6, 1178, 2048 }, { 7, 1179, 2048 }, { 6, 1180, 2048 }, { 7, 1181, 2048 }, { 7, 1182, 2048 }, { 8, 1183, 2048 },
{ 4, 1184, 2048 }, { 5, 1185, 2048 }, { 5, 1186, 2048 }, { 6, 1187, 2048 }, { 5, 1188, 2048 }, { 6, 1189, 2048 }, { 6, 1190, 2048 }, { 7, 1191, 2048 },
{ 5, 1192, 2048 }, { 6, 1193, 2048 }, { 6, 1194, 2048 }, { 7, 1195, 2048 }, { 6, 1196, 2048 }, { 7, 1197, 2048 }, { 7, 1198, 2048 }, { 8, 1199, 2048 },
{ 5, 1200, 2048 }, { 6, 1201, 2048 }, { 6, 1202, 2048 }, { 7, 1203, 2048 }, { 6, 1204, 2048 }, { 7, 1205, 2048 }, { 7, 1206, 2048 }, { 8, 1207, 2048 },
{ 6, 1208, 2048 }, { 7, 1209, 2048 }, { 7, 1210, 2048 }, { 8, 1211, 2048 }, { 7, 1212, 2048 }, { 8, 1213, 2048 }, { 8, 1214, 2048 }, { 9, 1215, 2048 },
{ 4, 1216, 2048 }, { 5, 1217, 2048 }, { 5, 1218, 2048 }, { 6, 1219, 2048 }, { 5, 1220, 2048 }, { 6, 1221, 2048 }, { 6, 1222, 2048 }, { 7, 1223, 2048 },
{ 5, 1224, 2048 }, { 6, 1225, 2048 }, { 6, 1226, 2048 }, { 7, 1227, 2048 }, { 6, 1228, 2048 }, { 7, 1229, 2048 }, { 7, 1230, 2048 }, { 8, 1231, 2048 },
{ 5, 1232, 2048 }, { 6, 1233, 2048 }, { 6, 1234, 2048 }, { 7, 1235, 2048 }, { 6, 1236, 2048 }, { 7, 1237, 2048 }, { 7, 1238, 2048 }, { 8, 1239, 2048 },
{ 6, 1240, 2048 }, { 7, 1241, 2048 }, { 7, 1242, 2048 }, { 8, 1243, 2048 }, { 7, 1244, 2048 }, { 8, 1245, 2048 }, { 8, 1246, 2048 }, { 9, 1247, 2048 },
{ 5, 1248, 2048 }, { 6, 1249, 2048 }, { 6, 1250, 2048 }, { 7, 1251, 2048 }, { 6, 1252, 2048 }, { 7, 1253, 2048 }, { 7, 1254, 2048 }, { 8, 1255, 2048 },
{ 6, 1256, 2048 }, { 7, 1257, 2048 }, { 7, 1258, 2048 }, { 8, 1259, 2048 }, { 7, 1260, 2048 }, { 8, 1261, 2048 }, { 8, 1262, 2048 }, { 9, 1263, 2048 },
{ 6, 1264, 2048 }, { 7, 1265, 2048 }, { 7, 1266, 2048 }, { 8, 1267, 2048 }, { 7, 1268, 2048 }, { 8, 1269, 2048 }, { 8, 1270, 2048 }, { 9, 1271, 2048 },
{ 7, 1272, 2048 }, { 8, 1273, 2048 }, { 8, 1274, 2048 }, { 9, 1275, 2048 }, { 8, 1276, 2048 }, { 9, 1277, 2048 }, { 9, 1278, 2048 }, { 10, 1279, 2048 },
{ 3, 1280, 2048 }, { 4, 1281, 2048 }, { 4, 1282, 2048 }, { 5, 1283, 2048 }, { 4, 1284, 2048 }, { 5, 1285, 2048 }, { 5, 1286, 2048 }, { 6, 1287, 2048 },
{ 4, 1288, 2048 }, { 5, 1289, 2048 }, { 5, 1290, 2048 }, { 6, 1291, 2048 }, { 5, 1292, 2048 }, { 6, 1293, 2048 }, { 6, 1294, 2048 }, { 7, 1295, 2048 },
{ 4, 1296, 2048 }, { 5, 1297, 2048 }, { 5, 1298, 2048 }, { 6, 1299, 2048 }, { 5, 1300, 2048 }, { 6, 1301, 2048 }, { 6, 1302, 2048 }, { 7, 1303, 2048 },
{ 5, 1304, 2048 }, { 6, 1305, 2048 }, { 6, 1306, 2048 }, { 7, 1307, 2048 }, { 6, 1308, 2048 }, { 7, 1309, 2048 }, { 7, 1310, 2048 }, { 8, 1311, 2048 },
{ 4, 1312, 2048 }, { 5, 1313, 2048 }, { 5, 1314, 2048 }, { 6, 1315, 2048 }, { 5, 1316, 2048 }, { 6, 1317, 2048 }, { 6, 1318, 2048 }, { 7, 1319, 2048 },
{ 5, 1320, 2048 }, { 6, 1321, 2048 }, { 6, 1322, 2048 }, { 7, 1323, 2048 }, { 6, 1324, 2048 }, { 7, 1325, 2048 }, { 7, 1326, 2048 }, { 8, 1327, 2048 },
{ 5, 1328, 2048 }, { 6, 1329, 2048 }, { 6, 1330, 2048 }, { 7, 1331, 2048 }, { 6, 1332, 2048 }, { 7, 1333, 2048 }, { 7, 1334, 2048 }, { 8, 1335, 2048 },
{ 6, 1336, 2048 }, { 7, 1337, 2048 }, { 7, 1338, 2048 }, { 8, 1339, 2048 }, { 7, 1340, 2048 }, { 8, 1341, 2048 }, { 8, 1342, 2048 }, { 9, 1343, 2048 },
{ 4, 1344, 2048 }, { 5, 1345, 2048 }, { 5, 1346, 2048 }, { 6, 1347, 2048 }, { 5, 1348, 2048 }, { 6, 1349, 2048 }, { 6, 1350, 2048 }, { 7, 1351, 2048 },
{ 5, 1352, 2048 }, { 6, 1353, 2048 }, { 6, 1354, 2048 }, { 7, 1355, 2048 }, { 6, 1356, 2048 }, { 7, 1357, 2048 }, { 7, 1358, 2048 }, { 8, 1359, 2048 },
{ 5, 1360, 2048 }, { 6, 1361, 2048 }, { 6, 1362, 2048 }, { 7, 1363, 2048 }, { 6, 1364, 2048 }, { 7, 1365, 2048 }, { 7, 1366, 2048 }, { 8, 1367, 2048 },
{ 6, 1368, 2048 }, { 7, 1369, 2048 }, { 7, 1370, 2048 }, { 8, 1371, 2048 }, { 7, 1372, 2048 }, { 8, 1373, 2048 }, { 8, 1374, 2048 }, { 9, 1375, 2048 },
{ 5, 1376, 2048 }, { 6, 1377, 2048 }, { 6, 1378, 2048 }, { 7, 1379, 2048 }, { 6, 1380, 2048 }, { 7, 1381, 2048 }, { 7, 1382, 2048 }, { 8, 1383, 2048 },
{ 6, 1384, 2048 }, { 7, 1385, 2048 }, { 7, 1386, 2048 }, { 8, 1387, 2048 }, { 7, 1388, 2048 }, { 8, 1389, 2048 }, { 8, 1390, 2048 }, { 9, 1391, 2048 },
{ 6, 1392, 2048 }, { 7, 1393, 2048 }, { 7, 1394, 2048 }, { 8, 1395, 2048 }, { 7, 1396, 2048 }, { 8, 1397, 2048 }, { 8, 1398, 2048 }, { 9, 1399, 2048 },
{ 7, 1400, 2048 }, { 8, 1401, 2048 }, { 8, 1402, 2048 }, { 9, 1403, 2048 }, { 8, 1404, 2048 }, { 9, 1405, 2048 }, { 9, 1406, 2048 }, { 10, 1407, 2048 },
{ 4, 1408, 2048 }, { 5, 1409, 2048 }, { 5, 1410, 2048 }, { 6, 1411, 2048 }, { 5, 1412, 2048 }, { 6, 1413, 2048 }, { 6, 1414, 2048 }, { 7, 1415, 2048 },
{ 5, 1416, 2048 }, { 6, 1417, 2048 }, { 6, 1418, 2048 }, { 7, 1419, 2048 }, { 6, 1420, 2048 }, { 7, 1421, 2048 }, { 7, 1422, 2048 }, { 8, 1423, 2048 },
{ 5, 1424, 2048 }, { 6, 1425, 2048 }, { 6, 1426, 2048 }, { 7, 1427, 2048 }, { 6, 1428, 2048 }, { 7, 1429, 2048 }, { 7, 1430, 2048 }, { 8, 1431, 2048 },
{ 6, 1432, 2048 }, { 7, 1433, 2048 }, { 7, 1434, 2048 }, { 8, 1435, 2048 }, { 7, 1436, 2048 }, { 8, 1437, 2048 }, { 8, 1438, 2048 }, { 9, 1439, 2048 },
{ 5, 1440, 2048 }, { 6, 1441, 2048 }, { 6, 1442, 2048 }, { 7, 1443, 2048 }, { 6, 1444, 2048 }, { 7, 1445, 2048 }, { 7, 1446, 2048 }, { 8, 1447, 2048 },
{ 6, 1448, 2048 }, { 7, 1449, 2048 }, { 7, 1450, 2048 }, { 8, 1451, 2048 }, { 7, 1452, 2048 }, { 8, 1453, 2048 }, { 8, 1454, 2048 }, { 9, 1455, 2048 },
{ 6, 1456, 2048 }, { 7, 1457, 2048 }, { 7, 1458, 2048 }, { 8, 1459, 2048 }, { 7, 1460, 2048 }, { 8, 1461, 2048 }, { 8, 1462, 2048 }, { 9, 1463, 2048 },
{ 7, 1464, 2048 }, { 8, 1465, 2048 }, { 8, 1466, 2048 }, { 9, 1467, 2048 }, { 8, 1468, 2048 }, { 9, 1469, 2048 }, { 9, 1470, 2048 }, { 10, 1471, 2048 },
{ 5, 1472, 2048 }, { 6, 1473, 2048 }, { 6, 1474, 2048 }, { 7, 1475, 2048 }, { 6, 1476, 2048 }, { 7, 1477, 2048 }, { 7, 1478, 2048 }, { 8, 1479, 2048 },
{ 6, 1480, 2048 }, { 7, 1481, 2048 }, { 7, 1482, 2048 }, { 8, 1483, 2048 }, { 7, 1484, 2048 }, { 8, 1485, 2048 }, { 8, 1486, 2048 }, { 9, 1487, 2048 },
{ 6, 1488, 2048 }, { 7, 1489, 2048 }, { 7, 1490, 2048 }, { 8, 1491, 2048 }, { 7, 1492, 2048 }, { 8, 1493, 2048 }, { 8, 1494, 2048 }, { 9, 1495, 2048 },
{ 7, 1496, 2048 }, { 8, 1497, 2048 }, { 8, 1498, 2048 }, { 9, 1499, 2048 }, { 8, 1500, 2048 }, { 9, 1501, 2048 }, { 9, 1502, 2048 }, { 10, 1503, 2048 },
{ 6, 1504, 2048 }, { 7, 1505, 2048 }, { 7, 1506, 2048 }, { 8, 1507, 2048 }, { 7, 1508, 2048 }, { 8, 1509, 2048 }, { 8, 1510, 2048 }, { 9, 1511, 2048 },
{ 7, 1512, 2048 }, { 8, 1513, 2048 }, { 8, 1514, 2048 }, { 9, 1515, 2048 }, { 8, 1516, 2048 }, { 9, 1517, 2048 }, { 9, 1518, 2048 }, { 10, 1519, 2048 },
{ 7, 1520, 2048 }, { 8, 1521, 2048 }, { 8, 1522, 2048 }, { 9, 1523, 2048 }, { 8, 1524, 2048 }, { 9, 1525, 2048 }, { 9, 1526, 2048 }, { 10, 1527, 2048 },
{ 8, 1528, 2048 }, { 9, 1529, 2048 }, { 9, 1530, 2048 }, { 10, 1531, 2048 }, { 9, 1532, 2048 }, { 10, 1533, 2048 }, { 10, 1534, 2048 }, { 11, 1535, 2048 },
{ 3, 1536, 2048 }, { 4, 1537, 2048 }, { 4, 1538, 2048 }, { 5, 1539, 2048 }, { 4, 1540, 2048 }, { 5, 1541, 2048 }, { 5, 1542, 2048 }, { 6, 1543, 2048 },
{ 4, 1544, 2048 }, { 5, 1545, 2048 }, { 5, 1546, 2048 }, { 6, 1547, 2048 }, { 5, 1548, 2048 }, { 6, 1549, 2048 }, { 6, 1550, 2048 }, { 7, 1551, 2048 },
{ 4, 1552, 2048 }, { 5, 1553, 2048 }, { 5, 1554, 2048 }, { 6, 1555, 2048 }, { 5, 1556, 2048 }, { 6, 1557, 2048 }, { 6, 1558, 2048 }, { 7, 1559, 2048 },
{ 5, 1560, 2048 }, { 6, 1561, 2048 }, { 6, 1562, 2048 }, { 7, 1563, 2048 }, { 6, 1564, 2048 }, { 7, 1565, 2048 }, { 7, 1566, 2048 }, { 8, 1567, 2048 },
{ 4, 1568, 2048 }, { 5, 1569, 2048 }, { 5, 1570, 2048 }, { 6, 1571, 2048 }, { 5, 1572, 2048 }, { 6, 1573, 2048 }, { 6, 1574, 2048 }, { 7, 1575, 2048 },
{ 5, 1576, 2048 }, { 6, 1577, 2048 }, { 6, 1578, 2048 }, { 7, 1579, 2048 }, { 6, 1580, 2048 }, { 7, 1581, 2048 }, { 7, 1582, 2048 }, { 8, 1583, 2048 },
{ 5, 1584, 2048 }, { 6, 1585, 2048 }, { 6, 1586, 2048 }, { 7, 1587, 2048 }, { 6, 1588, 2048 }, { 7, 1589, 2048 }, { 7, 1590, 2048 }, { 8, 1591, 2048 },
{ 6, 1592, 2048 }, { 7, 1593, 2048 }, { 7, 1594, 2048 }, { 8, 1595, 2048 }, { 7, 1596, 2048 }, { 8, 1597, 2048 }, { 8, 1598, 2048 }, { 9, 1599, 2048 },
{ 4, 1600, 2048 }, { 5, 1601, 2048 }, { 5, 1602, 2048 }, { 6, 1603, 2048 }, { 5, 1604, 2048 }, { 6, 1605, 2048 }, { 6, 1606, 2048 }, { 7, 1607, 2048 },
{ 5, 1608, 2048 }, { 6, 1609, 2048 }, { 6, 1610, 2048 }, { 7, 1611, 2048 }, { 6, 1612, 2048 }, { 7, 1613, 2048 }, { 7, 1614, 2048 }, { 8, 1615, 2048 },
{ 5, 1616, 2048 }, { 6, 1617, 2048 }, { 6, 1618, 2048 }, { 7, 1619, 2048 }, { 6, 1620, 2048 }, { 7, 1621, 2048 }, { 7, 1622, 2048 }, { 8, 1623, 2048 },
{ 6, 1624, 2048 }, { 7, 1625, 2048 }, { 7, 1626, 2048 }, { 8, 1627, 2048 }, { 7, 1628, 2048 }, { 8, 1629, 2048 }, { 8, 1630, 2048 }, { 9, 1631, 2048 },
{ 5, 1632, 2048 }, { 6, 1633, 2048 }, { 6, 1634, 2048 }, { 7, 1635, 2048 }, { 6, 1636, 2048 }, { 7, 1637, 2048 }, { 7, 1638, 2048 }, { 8, 1639, 2048 },
{ 6, 1640, 2048 }, { 7, 1641, 2048 }, { 7, 1642, 2048 }, { 8, 1643, 2048 }, { 7, 1644, 2048 }, { 8, 1645, 2048 }, { 8, 1646, 2048 }, { 9, 1647, 2048 },
{ 6, 1648, 2048 }, { 7, 1649, 2048 }, { 7, 1650, 2048 }, { 8, 1651, 2048 }, { 7, 1652, 2048 }, { 8, 1653, 2048 }, { 8, 1654, 2048 }, { 9, 1655, 2048 },
{ 7, 1656, 2048 }, { 8, 1657, 2048 }, { 8, 1658, 2048 }, { 9, 1659, 2048 }, { 8, 1660, 2048 }, { 9, 1661, 2048 }, { 9, 1662, 2048 }, { 10, 1663, 2048 },
{ 4, 1664, 2048 }, { 5, 1665, 2048 }, { 5, 1666, 2048 }, { 6, 1667, 2048 }, { 5, 1668, 2048 }, { 6, 1669, 2048 }, { 6, 1670, 2048 }, { 7, 1671, 2048 },
{ 5, 1672, 2048 }, { 6, 1673, 2048 }, { 6, 1674, 2048 }, { 7, 1675, 2048 }, { 6, 1676, 2048 }, { 7, 1677, 2048 }, { 7, 1678, 2048 }, { 8, 1679, 2048 },
{ 5, 1680, 2048 }, { 6, 1681, 2048 }, { 6, 1682, 2048 }, { 7, 1683, 2048 }, { 6, 1684, 2048 }, { 7, 1685, 2048 }, { 7, 1686, 2048 }, { 8, 1687, 2048 },
{ 6, 1688, 2048 }, { 7, 1689, 2048 }, { 7, 1690, 2048 }, { 8, 1691, 2048 }, { 7, 1692, 2048 }, { 8, 1693, 2048 }, { 8, 1694, 2048 }, { 9, 1695, 2048 },
{ 5, 1696, 2048 }, { 6, 1697, 2048 }, { 6, 1698, 2048 }, { 7, 1699, 2048 }, { 6, 1700, 2048 }, { 7, 1701, 2048 }, { 7, 1702, 2048 }, { 8, 1703, 2048 },
{ 6, 1704, 2048 }, { 7, 1705, 2048 }, { 7, 1706, 2048 }, { 8, 1707, 2048 }, { 7, 1708, 2048 }, { 8, 1709, 2048 }, { 8, 1710, 2048 }, { 9, 1711, 2048 },
{ 6, 1712, 2048 }, { 7, 1713, 2048 }, { 7, 1714, 2048 }, { 8, 1715, 2048 }, { 7, 1716, 2048 }, { 8, 1717, 2048 }, { 8, 1718, 2048 }, { 9, 1719, 2048 },
{ 7, 1720, 2048 }, { 8, 1721, 2048 }, { 8, 1722, 2048 }, { 9, 1723, 2048 }, { 8, 1724, 2048 }, { 9, 1725, 2048 }, { 9, 1726, 2048 }, { 10, 1727, 2048 },
{ 5, 1728, 2048 }, { 6, 1729, 2048 }, { 6, 1730, 2048 }, { 7, 1731, 2048 }, { 6, 1732, 2048 }, { 7, 1733, 2048 }, { 7, 1734, 2048 }, { 8, 1735, 2048 },
{ 6, 1736, 2048 }, { 7, 1737, 2048 }, { 7, 1738, 2048 }, { 8, 1739, 2048 }, { 7, 1740, 2048 }, { 8, 1741, 2048 }, { 8, 1742, 2048 }, { 9, 1743, 2048 },
{ 6, 1744, 2048 }, { 7, 1745, 2048 }, { 7, 1746, 2048 }, { 8, 1747, 2048 }, { 7, 1748, 2048 }, { 8, 1749, 2048 }, { 8, 1750, 2048 }, { 9, 1751, 2048 },
{ 7, 1752, 2048 }, { 8, 1753, 2048 }, { 8, 1754, 2048 }, { 9, 1755, 2048 }, { 8, 1756, 2048 }, { 9, 1757, 2048 }, { 9, 1758, 2048 }, { 10, 1759, 2048 },
{ 6, 1760, 2048 }, { 7, 1761, 2048 }, { 7, 1762, 2048 }, { 8, 1763, 2048 }, { 7, 1764, 2048 }, { 8, 1765, 2048 }, { 8, 1766, 2048 }, { 9, 1767, 2048 },
{ 7, 1768, 2048 }, { 8, 1769, 2048 }, { 8, 1770, 2048 }, { 9, 1771, 2048 }, { 8, 1772, 2048 }, { 9, 1773, 2048 }, { 9, 1774, 2048 }, { 10, 1775, 2048 },
{ 7, 1776, 2048 }, { 8, 1777, 2048 }, { 8, 1778, 2048 }, { 9, 1779, 2048 }, { 8, 1780, 2048 }, { 9, 1781, 2048 }, { 9, 1782, 2048 }, { 10, 1783, 2048 },
{ 8, 1784, 2048 }, { 9, 1785, 2048 }, { 9, 1786, 2048 }, { 10, 1787, 2048 }, { 9, 1788, 2048 }, { 10, 1789, 2048 }, { 10, 1790, 2048 }, { 11, 1791, 2048 },
{ 4, 1792, 2048 }, { 5, 1793, 2048 }, { 5, 1794, 2048 }, { 6, 1795, 2048 }, { 5, 1796, 2048 }, { 6, 1797, 2048 }, { 6, 1798, 2048 }, { 7, 1799, 2048 },
{ 5, 1800, 2048 }, { 6, 1801, 2048 }, { 6, 1802, 2048 }, { 7, 1803, 2048 }, { 6, 1804, 2048 }, { 7, 1805, 2048 }, { 7, 1806, 2048 }, { 8, 1807, 2048 },
{ 5, 1808, 2048 }, { 6, 1809, 2048 }, { 6, 1810, 2048 }, { 7, 1811, 2048 }, { 6, 1812, 2048 }, { 7, 1813, 2048 }, { 7, 1814, 2048 }, { 8, 1815, 2048 },
{ 6, 1816, 2048 }, { 7, 1817, 2048 }, { 7, 1818, 2048 }, { 8, 1819, 2048 }, { 7, 1820, 2048 }, { 8, 1821, 2048 }, { 8, 1822, 2048 }, { 9, 1823, 2048 },
{ 5, 1824, 2048 }, { 6, 1825, 2048 }, { 6, 1826, 2048 }, { 7, 1827, 2048 }, { 6, 1828, 2048 }, { 7, 1829, 2048 }, { 7, 1830, 2048 }, { 8, 1831, 2048 },
{ 6, 1832, 2048 }, { 7, 1833, 2048 }, { 7, 1834, 2048 }, { 8, 1835, 2048 }, { 7, 1836, 2048 }, { 8, 1837, 2048 }, { 8, 1838, 2048 }, { 9, 1839, 2048 },
{ 6, 1840, 2048 }, { 7, 1841, 2048 }, { 7, 1842, 2048 }, { 8, 1843, 2048 }, { 7, 1844, 2048 }, { 8, 1845, 2048 }, { 8, 1846, 2048 }, { 9, 1847, 2048 },
{ 7, 1848, 2048 }, { 8, 1849, 2048 }, { 8, 1850, 2048 }, { 9, 1851, 2048 }, { 8, 1852, 2048 }, { 9, 1853, 2048 }, { 9, 1854, 2048 }, { 10, 1855, 2048 },
{ 5, 1856, 2048 }, { 6, 1857, 2048 }, { 6, 1858, 2048 }, { 7, 1859, 2048 }, { 6, 1860, 2048 }, { 7, 1861, 2048 }, { 7, 1862, 2048 }, { 8, 1863, 2048 },
{ 6, 1864, 2048 }, { 7, 1865, 2048 }, { 7, 1866, 2048 }, { 8, 1867, 2048 }, { 7, 1868, 2048 }, { 8, 1869, 2048 }, { 8, 1870, 2048 }, { 9, 1871, 2048 },
{ 6, 1872, 2048 }, { 7, 1873, 2048 }, { 7, 1874, 2048 }, { 8, 1875, 2048 }, { 7, 1876, 2048 }, { 8, 1877, 2048 }, { 8, 1878, 2048 }, { 9, 1879, 2048 },
{ 7, 1880, 2048 }, { 8, 1881, 2048 }, { 8, 1882, 2048 }, { 9, 1883, 2048 }, { 8, 1884, 2048 }, { 9, 1885, 2048 }, { 9, 1886, 2048 }, { 10, 1887, 2048 },
{ 6, 1888, 2048 }, { 7, 1889, 2048 }, { 7, 1890, 2048 }, { 8, 1891, 2048 }, { 7, 1892, 2048 }, { 8, 1893, 2048 }, { 8, 1894, 2048 }, { 9, 1895, 2048 },
{ 7, 1896, 2048 }, { 8, 1897, 2048 }, { 8, 1898, 2048 }, { 9, 1899, 2048 }, { 8, 1900, 2048 }, { 9, 1901, 2048 }, { 9, 1902, 2048 }, { 10, 1903, 2048 },
{ 7, 1904, 2048 }, { 8, 1905, 2048 }, { 8, 1906, 2048 }, { 9, 1907, 2048 }, { 8, 1908, 2048 }, { 9, 1909, 2048 }, { 9, 1910, 2048 }, { 10, 1911, 2048 },
{ 8, 1912, 2048 }, { 9, 1913, 2048 }, { 9, 1914, 2048 }, { 10, 1915, 2048 }, { 9, 1916, 2048 }, { 10, 1917, 2048 }, { 10, 1918, 2048 }, { 11, 1919, 2048 },
{ 5, 1920, 2048 }, { 6, 1921, 2048 }, { 6, 1922, 2048 }, { 7, 1923, 2048 }, { 6, 1924, 2048 }, { 7, 1925, 2048 }, { 7, 1926, 2048 }, { 8, 1927, 2048 },
{ 6, 1928, 2048 }, { 7, 1929, 2048 }, { 7, 1930, 2048 }, { 8, 1931, 2048 }, { 7, 1932, 2048 }, { 8, 1933, 2048 }, { 8, 1934, 2048 }, { 9, 1935, 2048 },
{ 6, 1936, 2048 }, { 7, 1937, 2048 }, { 7, 1938, 2048 }, { 8, 1939, 2048 }, { 7, 1940, 2048 }, { 8, 1941, 2048 }, { 8, 1942, 2048 }, { 9, 1943, 2048 },
{ 7, 1944, 2048 }, { 8, 1945, 2048 }, { 8, 1946, 2048 }, { 9, 1947, 2048 }, { 8, 1948, 2048 }, { 9, 1949, 2048 }, { 9, 1950, 2048 }, { 10, 1951, 2048 },
{ 6, 1952, 2048 }, { 7, 1953, 2048 }, { 7, 1954, 2048 }, { 8, 1955, 2048 }, { 7, 1956, 2048 }, { 8, 1957, 2048 }, { 8, 1958, 2048 }, { 9, 1959, 2048 },
{ 7, 1960, 2048 }, { 8, 1961, 2048 }, { 8, 1962, 2048 }, { 9, 1963, 2048 }, { 8, 1964, 2048 }, { 9, 1965, 2048 }, { 9, 1966, 2048 }, { 10, 1967, 2048 },
{ 7, 1968, 2048 }, { 8, 1969, 2048 }, { 8, 1970, 2048 }, { 9, 1971, 2048 }, { 8, 1972, 2048 }, { 9, 1973, 2048 }, { 9, 1974, 2048 }, { 10, 1975, 2048 },
{ 8, 1976, 2048 }, { 9, 1977, 2048 }, { 9, 1978, 2048 }, { 10, 1979, 2048 }, { 9, 1980, 2048 }, { 10, 1981, 2048 }, { 10, 1982, 2048 }, { 11, 1983, 2048 },
{ 6, 1984, 2048 }, { 7, 1985, 2048 }, { 7, 1986, 2048 }, { 8, 1987, 2048 }, { 7, 1988, 2048 }, { 8, 1989, 2048 }, { 8, 1990, 2048 }, { 9, 1991, 2048 },
{ 7, 1992, 2048 }, { 8, 1993, 2048 }, { 8, 1994, 2048 }, { 9, 1995, 2048 }, { 8, 1996, 2048 }, { 9, 1997, 2048 }, { 9, 1998, 2048 }, { 10, 1999, 2048 },
{ 7, 2000, 2048 }, { 8, 2001, 2048 }, { 8, 2002, 2048 }, { 9, 2003, 2048 }, { 8, 2004, 2048 }, { 9, 2005, 2048 }, { 9, 2006, 2048 }, { 10, 2007, 2048 },
{ 8, 2008, 2048 }, { 9, 2009, 2048 }, { 9, 2010, 2048 }, { 10, 2011, 2048 }, { 9, 2012, 2048 }, { 10, 2013, 2048 }, { 10, 2014, 2048 }, { 11, 2015, 2048 },
{ 7, 2016, 2048 }, { 8, 2017, 2048 }, { 8, 2018, 2048 }, { 9, 2019, 2048 }, { 8, 2020, 2048 }, { 9, 2021, 2048 }, { 9, 2022, 2048 }, { 10, 2023, 2048 },
{ 8, 2024, 2048 }, { 9, 2025, 2048 }, { 9, 2026, 2048 }, { 10, 2027, 2048 }, { 9, 2028, 2048 }, { 10, 2029, 2048 }, { 10, 2030, 2048 }, { 11, 2031, 2048 },
{ 8, 2032, 2048 }, { 9, 2033, 2048 }, { 9, 2034, 2048 }, { 10, 2035, 2048 }, { 9, 2036, 2048 }, { 10, 2037, 2048 }, { 10, 2038, 2048 }, { 11, 2039, 2048 },
{ 9, 2040, 2048 }, { 10, 2041, 2048 }, { 10, 2042, 2048 }, { 11, 2043, 2048 }, { 10, 2044, 2048 }, { 11, 2045, 2048 }, { 11, 2046, 2048 }, { 12, 2047, 2048 },
#endif
#endif
#endif
#endif
#endif
#endif
};
/* find a hole and free as required, return -1 if no hole found */
static int find_hole(void)
{
unsigned x;
int y, z;
for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) {
z = x;
y = fp_cache[x].lru_count;
}
}
/* decrease all */
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].lru_count > 3) {
--(fp_cache[x].lru_count);
}
}
/* free entry z */
if (z >= 0 && fp_cache[z].g) {
mp_clear(&fp_cache[z].mu);
wc_ecc_del_point(fp_cache[z].g);
fp_cache[z].g = NULL;
for (x = 0; x < (1U<<FP_LUT); x++) {
wc_ecc_del_point(fp_cache[z].LUT[x]);
fp_cache[z].LUT[x] = NULL;
}
fp_cache[z].lru_count = 0;
}
return z;
}
/* determine if a base is already in the cache and if so, where */
static int find_base(ecc_point* g)
{
int x;
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].g != NULL &&
mp_cmp(fp_cache[x].g->x, g->x) == MP_EQ &&
mp_cmp(fp_cache[x].g->y, g->y) == MP_EQ &&
mp_cmp(fp_cache[x].g->z, g->z) == MP_EQ) {
break;
}
}
if (x == FP_ENTRIES) {
x = -1;
}
return x;
}
/* add a new base to the cache */
static int add_entry(int idx, ecc_point *g)
{
unsigned x, y;
/* allocate base and LUT */
fp_cache[idx].g = wc_ecc_new_point();
if (fp_cache[idx].g == NULL) {
return GEN_MEM_ERR;
}
/* copy x and y */
if ((mp_copy(g->x, fp_cache[idx].g->x) != MP_OKAY) ||
(mp_copy(g->y, fp_cache[idx].g->y) != MP_OKAY) ||
(mp_copy(g->z, fp_cache[idx].g->z) != MP_OKAY)) {
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
return GEN_MEM_ERR;
}
for (x = 0; x < (1U<<FP_LUT); x++) {
fp_cache[idx].LUT[x] = wc_ecc_new_point();
if (fp_cache[idx].LUT[x] == NULL) {
for (y = 0; y < x; y++) {
wc_ecc_del_point(fp_cache[idx].LUT[y]);
fp_cache[idx].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
fp_cache[idx].lru_count = 0;
return GEN_MEM_ERR;
}
}
fp_cache[idx].lru_count = 0;
return MP_OKAY;
}
#endif
#ifndef WOLFSSL_SP_MATH
/* build the LUT by spacing the bits of the input by #modulus/FP_LUT bits apart
*
* The algorithm builds patterns in increasing bit order by first making all
* single bit input patterns, then all two bit input patterns and so on
*/
static int build_lut(int idx, mp_int* a, mp_int* modulus, mp_digit mp,
mp_int* mu)
{
int err;
unsigned x, y, bitlen, lut_gap;
mp_int tmp;
if (mp_init(&tmp) != MP_OKAY)
return GEN_MEM_ERR;
/* sanity check to make sure lut_order table is of correct size,
should compile out to a NOP if true */
if ((sizeof(lut_orders) / sizeof(lut_orders[0])) < (1U<<FP_LUT)) {
err = BAD_FUNC_ARG;
}
else {
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* init the mu */
err = mp_init_copy(&fp_cache[idx].mu, mu);
}
/* copy base */
if (err == MP_OKAY) {
if ((mp_mulmod(fp_cache[idx].g->x, mu, modulus,
fp_cache[idx].LUT[1]->x) != MP_OKAY) ||
(mp_mulmod(fp_cache[idx].g->y, mu, modulus,
fp_cache[idx].LUT[1]->y) != MP_OKAY) ||
(mp_mulmod(fp_cache[idx].g->z, mu, modulus,
fp_cache[idx].LUT[1]->z) != MP_OKAY)) {
err = MP_MULMOD_E;
}
}
/* make all single bit entries */
for (x = 1; x < FP_LUT; x++) {
if (err != MP_OKAY)
break;
if ((mp_copy(fp_cache[idx].LUT[1<<(x-1)]->x,
fp_cache[idx].LUT[1<<x]->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[1<<(x-1)]->y,
fp_cache[idx].LUT[1<<x]->y) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[1<<(x-1)]->z,
fp_cache[idx].LUT[1<<x]->z) != MP_OKAY)){
err = MP_INIT_E;
break;
} else {
/* now double it bitlen/FP_LUT times */
for (y = 0; y < lut_gap; y++) {
if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[1<<x],
fp_cache[idx].LUT[1<<x], a, modulus, mp)) != MP_OKAY) {
break;
}
}
}
}
/* now make all entries in increase order of hamming weight */
for (x = 2; x <= FP_LUT; x++) {
if (err != MP_OKAY)
break;
for (y = 0; y < (1UL<<FP_LUT); y++) {
if (lut_orders[y].ham != (int)x) continue;
/* perform the add */
if ((err = ecc_projective_add_point(
fp_cache[idx].LUT[lut_orders[y].terma],
fp_cache[idx].LUT[lut_orders[y].termb],
fp_cache[idx].LUT[y], a, modulus, mp)) != MP_OKAY) {
break;
}
}
}
/* now map all entries back to affine space to make point addition faster */
for (x = 1; x < (1UL<<FP_LUT); x++) {
if (err != MP_OKAY)
break;
/* convert z to normal from montgomery */
err = mp_montgomery_reduce(fp_cache[idx].LUT[x]->z, modulus, mp);
/* invert it */
if (err == MP_OKAY)
err = mp_invmod(fp_cache[idx].LUT[x]->z, modulus,
fp_cache[idx].LUT[x]->z);
if (err == MP_OKAY)
/* now square it */
err = mp_sqrmod(fp_cache[idx].LUT[x]->z, modulus, &tmp);
if (err == MP_OKAY)
/* fix x */
err = mp_mulmod(fp_cache[idx].LUT[x]->x, &tmp, modulus,
fp_cache[idx].LUT[x]->x);
if (err == MP_OKAY)
/* get 1/z^3 */
err = mp_mulmod(&tmp, fp_cache[idx].LUT[x]->z, modulus, &tmp);
if (err == MP_OKAY)
/* fix y */
err = mp_mulmod(fp_cache[idx].LUT[x]->y, &tmp, modulus,
fp_cache[idx].LUT[x]->y);
if (err == MP_OKAY)
/* free z */
mp_clear(fp_cache[idx].LUT[x]->z);
}
mp_clear(&tmp);
if (err == MP_OKAY)
return MP_OKAY;
/* err cleanup */
for (y = 0; y < (1U<<FP_LUT); y++) {
wc_ecc_del_point(fp_cache[idx].LUT[y]);
fp_cache[idx].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
fp_cache[idx].lru_count = 0;
mp_clear(&fp_cache[idx].mu);
return err;
}
/* perform a fixed point ECC mulmod */
static int accel_fp_mul(int idx, mp_int* k, ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp, int map)
{
#define KB_SIZE 128
#ifdef WOLFSSL_SMALL_STACK
unsigned char* kb = NULL;
#else
unsigned char kb[KB_SIZE];
#endif
int x, err;
unsigned y, z = 0, bitlen, bitpos, lut_gap, first;
mp_int tk, order;
if (mp_init_multi(&tk, &order, NULL, NULL, NULL, NULL) != MP_OKAY)
return MP_INIT_E;
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(k) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* k must be less than modulus */
if (mp_cmp(k, &order) != MP_LT) {
if ((err = mp_mod(k, &order, &tk)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(k, &tk)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(k, &tk)) != MP_OKAY) {
goto done;
}
}
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* get the k value */
if (mp_unsigned_bin_size(&tk) > (int)(KB_SIZE - 2)) {
err = BUFFER_E; goto done;
}
/* store k */
#ifdef WOLFSSL_SMALL_STACK
kb = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb, 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tk, kb)) == MP_OKAY) {
/* let's reverse kb so it's little endian */
x = 0;
y = mp_unsigned_bin_size(&tk);
if (y > 0) {
y -= 1;
}
while ((unsigned)x < y) {
z = kb[x]; kb[x] = kb[y]; kb[y] = (byte)z;
++x; --y;
}
/* at this point we can start, yipee */
first = 1;
for (x = lut_gap-1; x >= 0; x--) {
/* extract FP_LUT bits from kb spread out by lut_gap bits and offset
by x bits from the start */
bitpos = x;
for (y = z = 0; y < FP_LUT; y++) {
z |= ((kb[bitpos>>3] >> (bitpos&7)) & 1) << y;
bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid
the mult in each loop */
}
/* double if not first */
if (!first) {
if ((err = ecc_projective_dbl_point(R, R, a, modulus,
mp)) != MP_OKAY) {
break;
}
}
/* add if not first, otherwise copy */
if (!first && z) {
if ((err = ecc_projective_add_point(R, fp_cache[idx].LUT[z], R, a,
modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[z],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
} else if (z) {
if ((mp_copy(fp_cache[idx].LUT[z]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[z]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
}
}
if (err == MP_OKAY) {
(void) z; /* Acknowledge the unused assignment */
ForceZero(kb, KB_SIZE);
/* map R back from projective space */
if (map) {
err = ecc_map(R, modulus, mp);
} else {
err = MP_OKAY;
}
}
done:
/* cleanup */
mp_clear(&order);
mp_clear(&tk);
#ifdef WOLFSSL_SMALL_STACK
XFREE(kb, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
#undef KB_SIZE
return err;
}
#endif
#ifdef ECC_SHAMIR
#ifndef WOLFSSL_SP_MATH
/* perform a fixed point ECC mulmod */
static int accel_fp_mul2add(int idx1, int idx2,
mp_int* kA, mp_int* kB,
ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp)
{
#define KB_SIZE 128
#ifdef WOLFSSL_SMALL_STACK
unsigned char* kb[2] = {NULL, NULL};
#else
unsigned char kb[2][KB_SIZE];
#endif
int x, err;
unsigned y, z, bitlen, bitpos, lut_gap, first, zA, zB;
mp_int tka, tkb, order;
if (mp_init_multi(&tka, &tkb, &order, NULL, NULL, NULL) != MP_OKAY)
return MP_INIT_E;
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(kA) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* kA must be less than modulus */
if (mp_cmp(kA, &order) != MP_LT) {
if ((err = mp_mod(kA, &order, &tka)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
goto done;
}
}
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(kB) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* kB must be less than modulus */
if (mp_cmp(kB, &order) != MP_LT) {
if ((err = mp_mod(kB, &order, &tkb)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
goto done;
}
}
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* get the k value */
if ((mp_unsigned_bin_size(&tka) > (int)(KB_SIZE - 2)) ||
(mp_unsigned_bin_size(&tkb) > (int)(KB_SIZE - 2)) ) {
err = BUFFER_E; goto done;
}
/* store k */
#ifdef WOLFSSL_SMALL_STACK
kb[0] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb[0] == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb[0], 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tka, kb[0])) != MP_OKAY) {
goto done;
}
/* let's reverse kb so it's little endian */
x = 0;
y = mp_unsigned_bin_size(&tka);
if (y > 0) {
y -= 1;
}
mp_clear(&tka);
while ((unsigned)x < y) {
z = kb[0][x]; kb[0][x] = kb[0][y]; kb[0][y] = (byte)z;
++x; --y;
}
/* store b */
#ifdef WOLFSSL_SMALL_STACK
kb[1] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb[1] == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb[1], 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tkb, kb[1])) == MP_OKAY) {
x = 0;
y = mp_unsigned_bin_size(&tkb);
if (y > 0) {
y -= 1;
}
while ((unsigned)x < y) {
z = kb[1][x]; kb[1][x] = kb[1][y]; kb[1][y] = (byte)z;
++x; --y;
}
/* at this point we can start, yipee */
first = 1;
for (x = lut_gap-1; x >= 0; x--) {
/* extract FP_LUT bits from kb spread out by lut_gap bits and
offset by x bits from the start */
bitpos = x;
for (y = zA = zB = 0; y < FP_LUT; y++) {
zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y;
zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y;
bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid
the mult in each loop */
}
/* double if not first */
if (!first) {
if ((err = ecc_projective_dbl_point(R, R, a, modulus,
mp)) != MP_OKAY) {
break;
}
}
/* add if not first, otherwise copy */
if (!first) {
if (zA) {
if ((err = ecc_projective_add_point(R, fp_cache[idx1].LUT[zA],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx1].LUT[zA], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx1].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
if (zB) {
if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx2].LUT[zB], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx2].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
} else {
if (zA) {
if ((mp_copy(fp_cache[idx1].LUT[zA]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx1].LUT[zA]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx1].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
if (zB && first == 0) {
if (zB) {
if ((err = ecc_projective_add_point(R,
fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY){
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx2].LUT[zB], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx2].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
} else if (zB && first == 1) {
if ((mp_copy(fp_cache[idx2].LUT[zB]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx2].LUT[zB]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx2].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
}
}
}
done:
/* cleanup */
mp_clear(&tkb);
mp_clear(&tka);
mp_clear(&order);
#ifdef WOLFSSL_SMALL_STACK
if (kb[0])
#endif
ForceZero(kb[0], KB_SIZE);
#ifdef WOLFSSL_SMALL_STACK
if (kb[1])
#endif
ForceZero(kb[1], KB_SIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(kb[0], NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
#undef KB_SIZE
if (err != MP_OKAY)
return err;
return ecc_map(R, modulus, mp);
}
/** ECC Fixed Point mulmod global with heap hint used
Computes kA*A + kB*B = C using Shamir's Trick
A First point to multiply
kA What to multiple A by
B Second point to multiply
kB What to multiple B by
C [out] Destination point (can overlap with A or B)
a ECC curve parameter a
modulus Modulus for curve
return MP_OKAY on success
*/
int ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus, void* heap)
{
int idx1 = -1, idx2 = -1, err, mpInit = 0;
mp_digit mp;
mp_int mu;
err = mp_init(&mu);
if (err != MP_OKAY)
return err;
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) != 0)
return BAD_MUTEX_E;
#endif /* HAVE_THREAD_LS */
/* find point */
idx1 = find_base(A);
/* no entry? */
if (idx1 == -1) {
/* find hole and add it */
if ((idx1 = find_hole()) >= 0) {
err = add_entry(idx1, A);
}
}
if (err == MP_OKAY && idx1 != -1) {
/* increment LRU */
++(fp_cache[idx1].lru_count);
}
if (err == MP_OKAY)
/* find point */
idx2 = find_base(B);
if (err == MP_OKAY) {
/* no entry? */
if (idx2 == -1) {
/* find hole and add it */
if ((idx2 = find_hole()) >= 0)
err = add_entry(idx2, B);
}
}
if (err == MP_OKAY && idx2 != -1) {
/* increment LRU */
++(fp_cache[idx2].lru_count);
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx1 >= 0 && fp_cache[idx1].lru_count == 2) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
mpInit = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx1, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx2 >= 0 && fp_cache[idx2].lru_count == 2) {
if (mpInit == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
mpInit = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx2, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].lru_count >= 2 &&
fp_cache[idx2].lru_count >= 2) {
if (mpInit == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
}
if (err == MP_OKAY)
err = accel_fp_mul2add(idx1, idx2, kA, kB, C, a, modulus, mp);
} else {
err = normal_ecc_mul2add(A, kA, B, kB, C, a, modulus, heap);
}
}
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
#endif /* HAVE_THREAD_LS */
mp_clear(&mu);
return err;
}
#endif
#endif /* ECC_SHAMIR */
/** ECC Fixed Point mulmod global
k The multiplicand
G Base point to multiply
R [out] Destination of product
a ECC curve parameter a
modulus The modulus for the curve
map [boolean] If non-zero maps the point back to affine coordinates,
otherwise it's left in jacobian-montgomery form
return MP_OKAY if successful
*/
int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
mp_int* modulus, int map, void* heap)
{
#ifndef WOLFSSL_SP_MATH
int idx, err = MP_OKAY;
mp_digit mp;
mp_int mu;
int mpSetup = 0;
if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
if (mp_init(&mu) != MP_OKAY)
return MP_INIT_E;
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) != 0)
return BAD_MUTEX_E;
#endif /* HAVE_THREAD_LS */
/* find point */
idx = find_base(G);
/* no entry? */
if (idx == -1) {
/* find hole and add it */
idx = find_hole();
if (idx >= 0)
err = add_entry(idx, G);
}
if (err == MP_OKAY && idx >= 0) {
/* increment LRU */
++(fp_cache[idx].lru_count);
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx >= 0 && fp_cache[idx].lru_count == 2) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
/* compute mu */
mpSetup = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
if (idx >= 0 && fp_cache[idx].lru_count >= 2) {
if (mpSetup == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
}
if (err == MP_OKAY)
err = accel_fp_mul(idx, k, R, a, modulus, mp, map);
} else {
err = normal_ecc_mulmod(k, G, R, a, modulus, map, heap);
}
}
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
#endif /* HAVE_THREAD_LS */
mp_clear(&mu);
return err;
#else
if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_mulmod_256(k, G, R, map, heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_mulmod_384(k, G, R, map, heap);
}
#endif
return WC_KEY_SIZE_E;
#endif
}
#ifndef WOLFSSL_SP_MATH
/* helper function for freeing the cache ...
must be called with the cache mutex locked */
static void wc_ecc_fp_free_cache(void)
{
unsigned x, y;
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].g != NULL) {
for (y = 0; y < (1U<<FP_LUT); y++) {
wc_ecc_del_point(fp_cache[x].LUT[y]);
fp_cache[x].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[x].g);
fp_cache[x].g = NULL;
mp_clear(&fp_cache[x].mu);
fp_cache[x].lru_count = 0;
fp_cache[x].lock = 0;
}
}
}
#endif
/** Free the Fixed Point cache */
void wc_ecc_fp_free(void)
{
#ifndef WOLFSSL_SP_MATH
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) == 0) {
#endif /* HAVE_THREAD_LS */
wc_ecc_fp_free_cache();
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
wc_FreeMutex(&ecc_fp_lock);
initMutex = 0;
}
#endif /* HAVE_THREAD_LS */
#endif
}
#endif /* FP_ECC */
#ifdef HAVE_ECC_ENCRYPT
enum ecCliState {
ecCLI_INIT = 1,
ecCLI_SALT_GET = 2,
ecCLI_SALT_SET = 3,
ecCLI_SENT_REQ = 4,
ecCLI_RECV_RESP = 5,
ecCLI_BAD_STATE = 99
};
enum ecSrvState {
ecSRV_INIT = 1,
ecSRV_SALT_GET = 2,
ecSRV_SALT_SET = 3,
ecSRV_RECV_REQ = 4,
ecSRV_SENT_RESP = 5,
ecSRV_BAD_STATE = 99
};
struct ecEncCtx {
const byte* kdfSalt; /* optional salt for kdf */
const byte* kdfInfo; /* optional info for kdf */
const byte* macSalt; /* optional salt for mac */
word32 kdfSaltSz; /* size of kdfSalt */
word32 kdfInfoSz; /* size of kdfInfo */
word32 macSaltSz; /* size of macSalt */
void* heap; /* heap hint for memory used */
byte clientSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */
byte serverSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */
byte encAlgo; /* which encryption type */
byte kdfAlgo; /* which key derivation function type */
byte macAlgo; /* which mac function type */
byte protocol; /* are we REQ_RESP client or server ? */
byte cliSt; /* protocol state, for sanity checks */
byte srvSt; /* protocol state, for sanity checks */
};
const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx)
{
if (ctx == NULL || ctx->protocol == 0)
return NULL;
if (ctx->protocol == REQ_RESP_CLIENT) {
if (ctx->cliSt == ecCLI_INIT) {
ctx->cliSt = ecCLI_SALT_GET;
return ctx->clientSalt;
}
else {
ctx->cliSt = ecCLI_BAD_STATE;
return NULL;
}
}
else if (ctx->protocol == REQ_RESP_SERVER) {
if (ctx->srvSt == ecSRV_INIT) {
ctx->srvSt = ecSRV_SALT_GET;
return ctx->serverSalt;
}
else {
ctx->srvSt = ecSRV_BAD_STATE;
return NULL;
}
}
return NULL;
}
/* optional set info, can be called before or after set_peer_salt */
int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz)
{
if (ctx == NULL || info == 0 || sz < 0)
return BAD_FUNC_ARG;
ctx->kdfInfo = info;
ctx->kdfInfoSz = sz;
return 0;
}
static const char* exchange_info = "Secure Message Exchange";
int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt)
{
byte tmp[EXCHANGE_SALT_SZ/2];
int halfSz = EXCHANGE_SALT_SZ/2;
if (ctx == NULL || ctx->protocol == 0 || salt == NULL)
return BAD_FUNC_ARG;
if (ctx->protocol == REQ_RESP_CLIENT) {
XMEMCPY(ctx->serverSalt, salt, EXCHANGE_SALT_SZ);
if (ctx->cliSt == ecCLI_SALT_GET)
ctx->cliSt = ecCLI_SALT_SET;
else {
ctx->cliSt = ecCLI_BAD_STATE;
return BAD_STATE_E;
}
}
else {
XMEMCPY(ctx->clientSalt, salt, EXCHANGE_SALT_SZ);
if (ctx->srvSt == ecSRV_SALT_GET)
ctx->srvSt = ecSRV_SALT_SET;
else {
ctx->srvSt = ecSRV_BAD_STATE;
return BAD_STATE_E;
}
}
/* mix half and half */
/* tmp stores 2nd half of client before overwrite */
XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz);
XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz);
XMEMCPY(ctx->serverSalt, tmp, halfSz);
ctx->kdfSalt = ctx->clientSalt;
ctx->kdfSaltSz = EXCHANGE_SALT_SZ;
ctx->macSalt = ctx->serverSalt;
ctx->macSaltSz = EXCHANGE_SALT_SZ;
if (ctx->kdfInfo == NULL) {
/* default info */
ctx->kdfInfo = (const byte*)exchange_info;
ctx->kdfInfoSz = EXCHANGE_INFO_SZ;
}
return 0;
}
static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng)
{
byte* saltBuffer = NULL;
if (ctx == NULL || rng == NULL || flags == 0)
return BAD_FUNC_ARG;
saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt;
return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ);
}
static void ecc_ctx_init(ecEncCtx* ctx, int flags)
{
if (ctx) {
XMEMSET(ctx, 0, sizeof(ecEncCtx));
ctx->encAlgo = ecAES_128_CBC;
ctx->kdfAlgo = ecHKDF_SHA256;
ctx->macAlgo = ecHMAC_SHA256;
ctx->protocol = (byte)flags;
if (flags == REQ_RESP_CLIENT)
ctx->cliSt = ecCLI_INIT;
if (flags == REQ_RESP_SERVER)
ctx->srvSt = ecSRV_INIT;
}
}
/* allow ecc context reset so user doesn't have to init/free for reuse */
int wc_ecc_ctx_reset(ecEncCtx* ctx, WC_RNG* rng)
{
if (ctx == NULL || rng == NULL)
return BAD_FUNC_ARG;
ecc_ctx_init(ctx, ctx->protocol);
return ecc_ctx_set_salt(ctx, ctx->protocol, rng);
}
ecEncCtx* wc_ecc_ctx_new_ex(int flags, WC_RNG* rng, void* heap)
{
int ret = 0;
ecEncCtx* ctx = (ecEncCtx*)XMALLOC(sizeof(ecEncCtx), heap,
DYNAMIC_TYPE_ECC);
if (ctx) {
ctx->protocol = (byte)flags;
ctx->heap = heap;
}
ret = wc_ecc_ctx_reset(ctx, rng);
if (ret != 0) {
wc_ecc_ctx_free(ctx);
ctx = NULL;
}
return ctx;
}
/* alloc/init and set defaults, return new Context */
ecEncCtx* wc_ecc_ctx_new(int flags, WC_RNG* rng)
{
return wc_ecc_ctx_new_ex(flags, rng, NULL);
}
/* free any resources, clear any keys */
void wc_ecc_ctx_free(ecEncCtx* ctx)
{
if (ctx) {
ForceZero(ctx, sizeof(ecEncCtx));
XFREE(ctx, ctx->heap, DYNAMIC_TYPE_ECC);
}
}
static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz,
int* keysLen, word32* digestSz, word32* blockSz)
{
if (ctx) {
switch (ctx->encAlgo) {
case ecAES_128_CBC:
*encKeySz = KEY_SIZE_128;
*ivSz = IV_SIZE_128;
*blockSz = AES_BLOCK_SIZE;
break;
default:
return BAD_FUNC_ARG;
}
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
*digestSz = WC_SHA256_DIGEST_SIZE;
break;
default:
return BAD_FUNC_ARG;
}
} else
return BAD_FUNC_ARG;
*keysLen = *encKeySz + *ivSz + *digestSz;
return 0;
}
/* ecc encrypt with shared secret run through kdf
ctx holds non default algos and inputs
msgSz should be the right size for encAlgo, i.e., already padded
return 0 on success */
int wc_ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg,
word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx)
{
int ret = 0;
word32 blockSz;
word32 digestSz;
ecEncCtx localCtx;
#ifdef WOLFSSL_SMALL_STACK
byte* sharedSecret;
byte* keys;
#else
byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */
byte keys[ECC_BUFSIZE]; /* max size */
#endif
word32 sharedSz = ECC_MAXSIZE;
int keysLen;
int encKeySz;
int ivSz;
int offset = 0; /* keys offset if doing msg exchange */
byte* encKey;
byte* encIv;
byte* macKey;
if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL ||
outSz == NULL)
return BAD_FUNC_ARG;
if (ctx == NULL) { /* use defaults */
ecc_ctx_init(&localCtx, 0);
ctx = &localCtx;
}
ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz,
&blockSz);
if (ret != 0)
return ret;
if (ctx->protocol == REQ_RESP_SERVER) {
offset = keysLen;
keysLen *= 2;
if (ctx->srvSt != ecSRV_RECV_REQ)
return BAD_STATE_E;
ctx->srvSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */
}
else if (ctx->protocol == REQ_RESP_CLIENT) {
if (ctx->cliSt != ecCLI_SALT_SET)
return BAD_STATE_E;
ctx->cliSt = ecCLI_SENT_REQ; /* only do this once */
}
if (keysLen > ECC_BUFSIZE) /* keys size */
return BUFFER_E;
if ( (msgSz%blockSz) != 0)
return BAD_PADDING_E;
if (*outSz < (msgSz + digestSz))
return BUFFER_E;
#ifdef WOLFSSL_SMALL_STACK
sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (sharedSecret == NULL)
return MEMORY_E;
keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (keys == NULL) {
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
#endif
do {
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
if (ret != 0)
break;
#endif
ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz);
} while (ret == WC_PENDING_E);
if (ret == 0) {
switch (ctx->kdfAlgo) {
case ecHKDF_SHA256 :
ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt,
ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz,
keys, keysLen);
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
encKey = keys + offset;
encIv = encKey + encKeySz;
macKey = encKey + encKeySz + ivSz;
switch (ctx->encAlgo) {
case ecAES_128_CBC:
{
Aes aes;
ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
AES_ENCRYPTION);
if (ret == 0) {
ret = wc_AesCbcEncrypt(&aes, out, msg, msgSz);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
ret = wc_AsyncWait(ret, &aes.asyncDev,
WC_ASYNC_FLAG_NONE);
#endif
}
wc_AesFree(&aes);
}
if (ret != 0)
break;
}
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
{
Hmac hmac;
ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, out, msgSz);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
if (ret == 0)
ret = wc_HmacFinal(&hmac, out+msgSz);
wc_HmacFree(&hmac);
}
}
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0)
*outSz = msgSz + digestSz;
#ifdef WOLFSSL_SMALL_STACK
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* ecc decrypt with shared secret run through kdf
ctx holds non default algos and inputs
return 0 on success */
int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg,
word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx)
{
int ret = 0;
word32 blockSz;
word32 digestSz;
ecEncCtx localCtx;
#ifdef WOLFSSL_SMALL_STACK
byte* sharedSecret;
byte* keys;
#else
byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */
byte keys[ECC_BUFSIZE]; /* max size */
#endif
word32 sharedSz = ECC_MAXSIZE;
int keysLen;
int encKeySz;
int ivSz;
int offset = 0; /* in case using msg exchange */
byte* encKey;
byte* encIv;
byte* macKey;
if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL ||
outSz == NULL)
return BAD_FUNC_ARG;
if (ctx == NULL) { /* use defaults */
ecc_ctx_init(&localCtx, 0);
ctx = &localCtx;
}
ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz,
&blockSz);
if (ret != 0)
return ret;
if (ctx->protocol == REQ_RESP_CLIENT) {
offset = keysLen;
keysLen *= 2;
if (ctx->cliSt != ecCLI_SENT_REQ)
return BAD_STATE_E;
ctx->cliSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */
}
else if (ctx->protocol == REQ_RESP_SERVER) {
if (ctx->srvSt != ecSRV_SALT_SET)
return BAD_STATE_E;
ctx->srvSt = ecSRV_RECV_REQ; /* only do this once */
}
if (keysLen > ECC_BUFSIZE) /* keys size */
return BUFFER_E;
if ( ((msgSz-digestSz) % blockSz) != 0)
return BAD_PADDING_E;
if (*outSz < (msgSz - digestSz))
return BUFFER_E;
#ifdef WOLFSSL_SMALL_STACK
sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (sharedSecret == NULL)
return MEMORY_E;
keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (keys == NULL) {
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
#endif
do {
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
if (ret != 0)
break;
#endif
ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz);
} while (ret == WC_PENDING_E);
if (ret == 0) {
switch (ctx->kdfAlgo) {
case ecHKDF_SHA256 :
ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt,
ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz,
keys, keysLen);
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
encKey = keys + offset;
encIv = encKey + encKeySz;
macKey = encKey + encKeySz + ivSz;
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
{
byte verify[WC_SHA256_DIGEST_SIZE];
Hmac hmac;
ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, msg, msgSz-digestSz);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
if (ret == 0)
ret = wc_HmacFinal(&hmac, verify);
if (ret == 0) {
if (XMEMCMP(verify, msg + msgSz - digestSz, digestSz) != 0)
ret = -1;
}
wc_HmacFree(&hmac);
}
break;
}
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
switch (ctx->encAlgo) {
#ifdef HAVE_AES_CBC
case ecAES_128_CBC:
{
Aes aes;
ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
AES_DECRYPTION);
if (ret != 0)
break;
ret = wc_AesCbcDecrypt(&aes, out, msg, msgSz-digestSz);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE);
#endif
}
break;
#endif
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0)
*outSz = msgSz - digestSz;
#ifdef WOLFSSL_SMALL_STACK
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
#endif /* HAVE_ECC_ENCRYPT */
#ifdef HAVE_COMP_KEY
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifndef WOLFSSL_SP_MATH
int do_mp_jacobi(mp_int* a, mp_int* n, int* c);
int do_mp_jacobi(mp_int* a, mp_int* n, int* c)
{
int k, s, res;
int r = 0; /* initialize to help static analysis out */
mp_digit residue;
/* if a < 0 return MP_VAL */
if (mp_isneg(a) == MP_YES) {
return MP_VAL;
}
/* if n <= 0 return MP_VAL */
if (mp_cmp_d(n, 0) != MP_GT) {
return MP_VAL;
}
/* step 1. handle case of a == 0 */
if (mp_iszero (a) == MP_YES) {
/* special case of a == 0 and n == 1 */
if (mp_cmp_d (n, 1) == MP_EQ) {
*c = 1;
} else {
*c = 0;
}
return MP_OKAY;
}
/* step 2. if a == 1, return 1 */
if (mp_cmp_d (a, 1) == MP_EQ) {
*c = 1;
return MP_OKAY;
}
/* default */
s = 0;
/* divide out larger power of two */
k = mp_cnt_lsb(a);
res = mp_div_2d(a, k, a, NULL);
if (res == MP_OKAY) {
/* step 4. if e is even set s=1 */
if ((k & 1) == 0) {
s = 1;
} else {
/* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */
residue = n->dp[0] & 7;
if (residue == 1 || residue == 7) {
s = 1;
} else if (residue == 3 || residue == 5) {
s = -1;
}
}
/* step 5. if p == 3 (mod 4) *and* a == 3 (mod 4) then s = -s */
if ( ((n->dp[0] & 3) == 3) && ((a->dp[0] & 3) == 3)) {
s = -s;
}
}
if (res == MP_OKAY) {
/* if a == 1 we're done */
if (mp_cmp_d(a, 1) == MP_EQ) {
*c = s;
} else {
/* n1 = n mod a */
res = mp_mod (n, a, n);
if (res == MP_OKAY)
res = do_mp_jacobi(n, a, &r);
if (res == MP_OKAY)
*c = s * r;
}
}
return res;
}
/* computes the jacobi c = (a | n) (or Legendre if n is prime)
* HAC pp. 73 Algorithm 2.149
* HAC is wrong here, as the special case of (0 | 1) is not
* handled correctly.
*/
int mp_jacobi(mp_int* a, mp_int* n, int* c)
{
mp_int a1, n1;
int res;
/* step 3. write a = a1 * 2**k */
if ((res = mp_init_multi(&a1, &n1, NULL, NULL, NULL, NULL)) != MP_OKAY) {
return res;
}
if ((res = mp_copy(a, &a1)) != MP_OKAY) {
goto done;
}
if ((res = mp_copy(n, &n1)) != MP_OKAY) {
goto done;
}
res = do_mp_jacobi(&a1, &n1, c);
done:
/* cleanup */
mp_clear(&n1);
mp_clear(&a1);
return res;
}
/* Solves the modular equation x^2 = n (mod p)
* where prime number is greater than 2 (odd prime).
* The result is returned in the third argument x
* the function returns MP_OKAY on success, MP_VAL or another error on failure
*/
int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret)
{
#ifdef SQRTMOD_USE_MOD_EXP
int res;
mp_int e;
res = mp_init(&e);
if (res == MP_OKAY)
res = mp_add_d(prime, 1, &e);
if (res == MP_OKAY)
res = mp_div_2d(&e, 2, &e, NULL);
if (res == MP_OKAY)
res = mp_exptmod(n, &e, prime, ret);
mp_clear(&e);
return res;
#else
int res, legendre, done = 0;
mp_int t1, C, Q, S, Z, M, T, R, two;
mp_digit i;
/* first handle the simple cases n = 0 or n = 1 */
if (mp_cmp_d(n, 0) == MP_EQ) {
mp_zero(ret);
return MP_OKAY;
}
if (mp_cmp_d(n, 1) == MP_EQ) {
return mp_set(ret, 1);
}
/* prime must be odd */
if (mp_cmp_d(prime, 2) == MP_EQ) {
return MP_VAL;
}
/* is quadratic non-residue mod prime */
if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) {
return res;
}
if (legendre == -1) {
return MP_VAL;
}
if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M)) != MP_OKAY)
return res;
if ((res = mp_init_multi(&T, &R, &two, NULL, NULL, NULL))
!= MP_OKAY) {
mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z);
mp_clear(&M);
return res;
}
/* SPECIAL CASE: if prime mod 4 == 3
* compute directly: res = n^(prime+1)/4 mod prime
* Handbook of Applied Cryptography algorithm 3.36
*/
res = mp_mod_d(prime, 4, &i);
if (res == MP_OKAY && i == 3) {
res = mp_add_d(prime, 1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
if (res == MP_OKAY)
res = mp_exptmod(n, &t1, prime, ret);
done = 1;
}
/* NOW: TonelliShanks algorithm */
if (res == MP_OKAY && done == 0) {
/* factor out powers of 2 from prime-1, defining Q and S
* as: prime-1 = Q*2^S */
/* Q = prime - 1 */
res = mp_copy(prime, &Q);
if (res == MP_OKAY)
res = mp_sub_d(&Q, 1, &Q);
/* S = 0 */
if (res == MP_OKAY)
mp_zero(&S);
while (res == MP_OKAY && mp_iseven(&Q) == MP_YES) {
/* Q = Q / 2 */
res = mp_div_2(&Q, &Q);
/* S = S + 1 */
if (res == MP_OKAY)
res = mp_add_d(&S, 1, &S);
}
/* find a Z such that the Legendre symbol (Z|prime) == -1 */
/* Z = 2 */
if (res == MP_OKAY)
res = mp_set_int(&Z, 2);
while (res == MP_OKAY) {
res = mp_jacobi(&Z, prime, &legendre);
if (res == MP_OKAY && legendre == -1)
break;
/* Z = Z + 1 */
if (res == MP_OKAY)
res = mp_add_d(&Z, 1, &Z);
}
/* C = Z ^ Q mod prime */
if (res == MP_OKAY)
res = mp_exptmod(&Z, &Q, prime, &C);
/* t1 = (Q + 1) / 2 */
if (res == MP_OKAY)
res = mp_add_d(&Q, 1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
/* R = n ^ ((Q + 1) / 2) mod prime */
if (res == MP_OKAY)
res = mp_exptmod(n, &t1, prime, &R);
/* T = n ^ Q mod prime */
if (res == MP_OKAY)
res = mp_exptmod(n, &Q, prime, &T);
/* M = S */
if (res == MP_OKAY)
res = mp_copy(&S, &M);
if (res == MP_OKAY)
res = mp_set_int(&two, 2);
while (res == MP_OKAY && done == 0) {
res = mp_copy(&T, &t1);
/* reduce to 1 and count */
i = 0;
while (res == MP_OKAY) {
if (mp_cmp_d(&t1, 1) == MP_EQ)
break;
res = mp_exptmod(&t1, &two, prime, &t1);
if (res == MP_OKAY)
i++;
}
if (res == MP_OKAY && i == 0) {
res = mp_copy(&R, ret);
done = 1;
}
if (done == 0) {
/* t1 = 2 ^ (M - i - 1) */
if (res == MP_OKAY)
res = mp_sub_d(&M, i, &t1);
if (res == MP_OKAY)
res = mp_sub_d(&t1, 1, &t1);
if (res == MP_OKAY)
res = mp_exptmod(&two, &t1, prime, &t1);
/* t1 = C ^ (2 ^ (M - i - 1)) mod prime */
if (res == MP_OKAY)
res = mp_exptmod(&C, &t1, prime, &t1);
/* C = (t1 * t1) mod prime */
if (res == MP_OKAY)
res = mp_sqrmod(&t1, prime, &C);
/* R = (R * t1) mod prime */
if (res == MP_OKAY)
res = mp_mulmod(&R, &t1, prime, &R);
/* T = (T * C) mod prime */
if (res == MP_OKAY)
res = mp_mulmod(&T, &C, prime, &T);
/* M = i */
if (res == MP_OKAY)
res = mp_set(&M, i);
}
}
}
/* done */
mp_clear(&t1);
mp_clear(&C);
mp_clear(&Q);
mp_clear(&S);
mp_clear(&Z);
mp_clear(&M);
mp_clear(&T);
mp_clear(&R);
mp_clear(&two);
return res;
#endif
}
#endif
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
/* export public ECC key in ANSI X9.63 format compressed */
static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen)
{
word32 numlen;
int ret = MP_OKAY;
if (key == NULL || out == NULL || outLen == NULL)
return BAD_FUNC_ARG;
if (wc_ecc_is_valid_idx(key->idx) == 0) {
return ECC_BAD_ARG_E;
}
numlen = key->dp->size;
if (*outLen < (1 + numlen)) {
*outLen = 1 + numlen;
return BUFFER_E;
}
/* store first byte */
out[0] = mp_isodd(key->pubkey.y) == MP_YES ? ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
/* pad and store x */
XMEMSET(out+1, 0, numlen);
ret = mp_to_unsigned_bin(key->pubkey.x,
out+1 + (numlen - mp_unsigned_bin_size(key->pubkey.x)));
*outLen = 1 + numlen;
return ret;
}
#endif /* HAVE_COMP_KEY */
int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz)
{
int x;
if (oidSum == 0) {
return BAD_FUNC_ARG;
}
/* find matching OID sum (based on encoded value) */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (ecc_sets[x].oidSum == oidSum) {
int ret = 0;
#ifdef HAVE_OID_ENCODING
/* check cache */
oid_cache_t* o = &ecc_oid_cache[x];
if (o->oidSz == 0) {
o->oidSz = sizeof(o->oid);
ret = EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz,
o->oid, &o->oidSz);
}
if (oidSz) {
*oidSz = o->oidSz;
}
if (oid) {
*oid = o->oid;
}
#else
if (oidSz) {
*oidSz = ecc_sets[x].oidSz;
}
if (oid) {
*oid = ecc_sets[x].oid;
}
#endif
/* on success return curve id */
if (ret == 0) {
ret = ecc_sets[x].id;
}
return ret;
}
}
return NOT_COMPILED_IN;
}
#ifdef WOLFSSL_CUSTOM_CURVES
int wc_ecc_set_custom_curve(ecc_key* key, const ecc_set_type* dp)
{
if (key == NULL || dp == NULL) {
return BAD_FUNC_ARG;
}
key->idx = ECC_CUSTOM_IDX;
key->dp = dp;
return 0;
}
#endif /* WOLFSSL_CUSTOM_CURVES */
#ifdef HAVE_X963_KDF
static WC_INLINE void IncrementX963KdfCounter(byte* inOutCtr)
{
int i;
/* in network byte order so start at end and work back */
for (i = 3; i >= 0; i--) {
if (++inOutCtr[i]) /* we're done unless we overflow */
return;
}
}
/* ASN X9.63 Key Derivation Function (SEC1) */
int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz,
const byte* sinfo, word32 sinfoSz, byte* out, word32 outSz)
{
int ret, i;
int digestSz, copySz;
int remaining = outSz;
byte* outIdx;
byte counter[4];
byte tmp[WC_MAX_DIGEST_SIZE];
#ifdef WOLFSSL_SMALL_STACK
wc_HashAlg* hash;
#else
wc_HashAlg hash[1];
#endif
if (secret == NULL || secretSz == 0 || out == NULL)
return BAD_FUNC_ARG;
/* X9.63 allowed algos only */
if (type != WC_HASH_TYPE_SHA && type != WC_HASH_TYPE_SHA224 &&
type != WC_HASH_TYPE_SHA256 && type != WC_HASH_TYPE_SHA384 &&
type != WC_HASH_TYPE_SHA512)
return BAD_FUNC_ARG;
digestSz = wc_HashGetDigestSize(type);
if (digestSz < 0)
return digestSz;
#ifdef WOLFSSL_SMALL_STACK
hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), NULL,
DYNAMIC_TYPE_HASHES);
if (hash == NULL)
return MEMORY_E;
#endif
ret = wc_HashInit(hash, type);
if (ret != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(hash, NULL, DYNAMIC_TYPE_HASHES);
#endif
return ret;
}
outIdx = out;
XMEMSET(counter, 0, sizeof(counter));
for (i = 1; remaining > 0; i++) {
IncrementX963KdfCounter(counter);
ret = wc_HashUpdate(hash, type, secret, secretSz);
if (ret != 0) {
break;
}
ret = wc_HashUpdate(hash, type, counter, sizeof(counter));
if (ret != 0) {
break;
}
if (sinfo) {
ret = wc_HashUpdate(hash, type, sinfo, sinfoSz);
if (ret != 0) {
break;
}
}
ret = wc_HashFinal(hash, type, tmp);
if (ret != 0) {
break;
}
copySz = min(remaining, digestSz);
XMEMCPY(outIdx, tmp, copySz);
remaining -= copySz;
outIdx += copySz;
}
wc_HashFree(hash, type);
#ifdef WOLFSSL_SMALL_STACK
XFREE(hash, NULL, DYNAMIC_TYPE_HASHES);
#endif
return ret;
}
#endif /* HAVE_X963_KDF */
#endif /* HAVE_ECC */
| ./CrossVul/dataset_final_sorted/CWE-326/c/good_3970_0 |
crossvul-cpp_data_bad_3970_1 | /* tfm.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/*
* Based on public domain TomsFastMath 0.10 by Tom St Denis, tomstdenis@iahu.ca,
* http://math.libtomcrypt.com
*/
/**
* Edited by Moises Guimaraes (moises@wolfssl.com)
* to fit wolfSSL's needs.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* in case user set USE_FAST_MATH there */
#include <wolfssl/wolfcrypt/settings.h>
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#ifdef USE_FAST_MATH
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/tfm.h>
#include <wolfcrypt/src/asm.c> /* will define asm MACROS or C ones */
#include <wolfssl/wolfcrypt/wolfmath.h> /* common functions */
#if defined(FREESCALE_LTC_TFM)
#include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
#endif
#ifdef WOLFSSL_DEBUG_MATH
#include <stdio.h>
#endif
#ifdef USE_WINDOWS_API
#pragma warning(disable:4127)
/* Disables the warning:
* 4127: conditional expression is constant
* in this file.
*/
#endif
#if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
#ifdef __cplusplus
extern "C" {
#endif
WOLFSSL_LOCAL int sp_ModExp_1024(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_1536(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_2048(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_3072(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_4096(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
#ifndef WOLFSSL_SP_MATH
/* math settings check */
word32 CheckRunTimeSettings(void)
{
return CTC_SETTINGS;
}
#endif
/* math settings size check */
word32 CheckRunTimeFastMath(void)
{
return FP_SIZE;
}
/* Functions */
void fp_add(fp_int *a, fp_int *b, fp_int *c)
{
int sa, sb;
/* get sign of both inputs */
sa = a->sign;
sb = b->sign;
/* handle two cases, not four */
if (sa == sb) {
/* both positive or both negative */
/* add their magnitudes, copy the sign */
c->sign = sa;
s_fp_add (a, b, c);
} else {
/* one positive, the other negative */
/* subtract the one with the greater magnitude from */
/* the one of the lesser magnitude. The result gets */
/* the sign of the one with the greater magnitude. */
if (fp_cmp_mag (a, b) == FP_LT) {
c->sign = sb;
s_fp_sub (b, a, c);
} else {
c->sign = sa;
s_fp_sub (a, b, c);
}
}
}
/* unsigned addition */
void s_fp_add(fp_int *a, fp_int *b, fp_int *c)
{
int x, y, oldused;
fp_word t;
y = MAX(a->used, b->used);
oldused = MIN(c->used, FP_SIZE); /* help static analysis w/ largest size */
c->used = y;
t = 0;
for (x = 0; x < y; x++) {
t += ((fp_word)a->dp[x]) + ((fp_word)b->dp[x]);
c->dp[x] = (fp_digit)t;
t >>= DIGIT_BIT;
}
if (t != 0 && x < FP_SIZE) {
c->dp[c->used++] = (fp_digit)t;
++x;
}
c->used = x;
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a - b */
void fp_sub(fp_int *a, fp_int *b, fp_int *c)
{
int sa, sb;
sa = a->sign;
sb = b->sign;
if (sa != sb) {
/* subtract a negative from a positive, OR */
/* subtract a positive from a negative. */
/* In either case, ADD their magnitudes, */
/* and use the sign of the first number. */
c->sign = sa;
s_fp_add (a, b, c);
} else {
/* subtract a positive from a positive, OR */
/* subtract a negative from a negative. */
/* First, take the difference between their */
/* magnitudes, then... */
if (fp_cmp_mag (a, b) != FP_LT) {
/* Copy the sign from the first */
c->sign = sa;
/* The first has a larger or equal magnitude */
s_fp_sub (a, b, c);
} else {
/* The result has the *opposite* sign from */
/* the first number. */
c->sign = (sa == FP_ZPOS) ? FP_NEG : FP_ZPOS;
/* The second has a larger magnitude */
s_fp_sub (b, a, c);
}
}
}
/* unsigned subtraction ||a|| >= ||b|| ALWAYS! */
void s_fp_sub(fp_int *a, fp_int *b, fp_int *c)
{
int x, oldbused, oldused;
fp_word t;
oldused = c->used;
oldbused = b->used;
c->used = a->used;
t = 0;
for (x = 0; x < oldbused; x++) {
t = ((fp_word)a->dp[x]) - (((fp_word)b->dp[x]) + t);
c->dp[x] = (fp_digit)t;
t = (t >> DIGIT_BIT)&1;
}
for (; x < a->used; x++) {
t = ((fp_word)a->dp[x]) - t;
c->dp[x] = (fp_digit)t;
t = (t >> DIGIT_BIT)&1;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a * b */
int fp_mul(fp_int *A, fp_int *B, fp_int *C)
{
int ret = 0;
int y, yy, oldused;
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
ret = esp_mp_mul(A, B, C);
if(ret != -2) return ret;
#endif
oldused = C->used;
y = MAX(A->used, B->used);
yy = MIN(A->used, B->used);
/* call generic if we're out of range */
if (y + yy > FP_SIZE) {
ret = fp_mul_comba(A, B, C);
goto clean;
}
/* pick a comba (unrolled 4/8/16/32 x or rolled) based on the size
of the largest input. We also want to avoid doing excess mults if the
inputs are not close to the next power of two. That is, for example,
if say y=17 then we would do (32-17)^2 = 225 unneeded multiplications
*/
#if defined(TFM_MUL3) && FP_SIZE >= 6
if (y <= 3) {
ret = fp_mul_comba3(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL4) && FP_SIZE >= 8
if (y == 4) {
ret = fp_mul_comba4(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL6) && FP_SIZE >= 12
if (y <= 6) {
ret = fp_mul_comba6(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL7) && FP_SIZE >= 14
if (y == 7) {
ret = fp_mul_comba7(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL8) && FP_SIZE >= 16
if (y == 8) {
ret = fp_mul_comba8(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL9) && FP_SIZE >= 18
if (y == 9) {
ret = fp_mul_comba9(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL12) && FP_SIZE >= 24
if (y <= 12) {
ret = fp_mul_comba12(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL17) && FP_SIZE >= 34
if (y <= 17) {
ret = fp_mul_comba17(A,B,C);
goto clean;
}
#endif
#if defined(TFM_SMALL_SET) && FP_SIZE >= 32
if (y <= 16) {
ret = fp_mul_comba_small(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL20) && FP_SIZE >= 40
if (y <= 20) {
ret = fp_mul_comba20(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL24) && FP_SIZE >= 48
if (yy >= 16 && y <= 24) {
ret = fp_mul_comba24(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL28) && FP_SIZE >= 56
if (yy >= 20 && y <= 28) {
ret = fp_mul_comba28(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL32) && FP_SIZE >= 64
if (yy >= 24 && y <= 32) {
ret = fp_mul_comba32(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL48) && FP_SIZE >= 96
if (yy >= 40 && y <= 48) {
ret = fp_mul_comba48(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL64) && FP_SIZE >= 128
if (yy >= 56 && y <= 64) {
ret = fp_mul_comba64(A,B,C);
goto clean;
}
#endif
ret = fp_mul_comba(A,B,C);
clean:
/* zero any excess digits on the destination that we didn't write to */
for (y = C->used; y >= 0 && y < oldused; y++) {
C->dp[y] = 0;
}
return ret;
}
void fp_mul_2(fp_int * a, fp_int * b)
{
int x, oldused;
oldused = b->used;
b->used = a->used;
{
fp_digit r, rr, *tmpa, *tmpb;
/* alias for source */
tmpa = a->dp;
/* alias for dest */
tmpb = b->dp;
/* carry */
r = 0;
for (x = 0; x < a->used; x++) {
/* get what will be the *next* carry bit from the
* MSB of the current digit
*/
rr = *tmpa >> ((fp_digit)(DIGIT_BIT - 1));
/* now shift up this digit, add in the carry [from the previous] */
*tmpb++ = ((*tmpa++ << ((fp_digit)1)) | r);
/* copy the carry that would be from the source
* digit into the next iteration
*/
r = rr;
}
/* new leading digit? */
if (r != 0 && b->used != (FP_SIZE-1)) {
/* add a MSB which is always 1 at this point */
*tmpb = 1;
++(b->used);
}
/* zero any excess digits on the destination that we didn't write to */
tmpb = b->dp + b->used;
for (x = b->used; x < oldused; x++) {
*tmpb++ = 0;
}
}
b->sign = a->sign;
}
/* c = a * b */
void fp_mul_d(fp_int *a, fp_digit b, fp_int *c)
{
fp_word w;
int x, oldused;
oldused = c->used;
c->used = a->used;
c->sign = a->sign;
w = 0;
for (x = 0; x < a->used; x++) {
w = ((fp_word)a->dp[x]) * ((fp_word)b) + w;
c->dp[x] = (fp_digit)w;
w = w >> DIGIT_BIT;
}
if (w != 0 && (a->used != FP_SIZE)) {
c->dp[c->used++] = (fp_digit) w;
++x;
}
/* zero any excess digits on the destination that we didn't write to */
/* also checking FP_SIZE here for static analysis */
for (; x < oldused && x < FP_SIZE; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a * 2**d */
void fp_mul_2d(fp_int *a, int b, fp_int *c)
{
fp_digit carry, carrytmp, shift;
int x;
/* copy it */
fp_copy(a, c);
/* handle whole digits */
if (b >= DIGIT_BIT) {
fp_lshd(c, b/DIGIT_BIT);
}
b %= DIGIT_BIT;
/* shift the digits */
if (b != 0) {
carry = 0;
shift = DIGIT_BIT - b;
for (x = 0; x < c->used; x++) {
carrytmp = c->dp[x] >> shift;
c->dp[x] = (c->dp[x] << b) + carry;
carry = carrytmp;
}
/* store last carry if room */
if (carry && x < FP_SIZE) {
c->dp[c->used++] = carry;
}
}
fp_clamp(c);
}
/* generic PxQ multiplier */
#if defined(HAVE_INTEL_MULX)
WC_INLINE static int fp_mul_comba_mulx(fp_int *A, fp_int *B, fp_int *C)
{
int ix, iy, iz, pa;
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)ix; (void)iy; (void)iz;
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* get size of output and trim */
pa = A->used + B->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* Always take branch to use tmp variable. This avoids a cache attack for
* determining if C equals A */
if (1) {
fp_init(tmp);
dst = tmp;
}
TFM_INTEL_MUL_COMBA(A, B, dst) ;
dst->used = pa;
dst->sign = A->sign ^ B->sign;
fp_clamp(dst);
fp_copy(dst, C);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
int fp_mul_comba(fp_int *A, fp_int *B, fp_int *C)
{
int ret = 0;
int ix, iy, iz, tx, ty, pa;
fp_digit c0, c1, c2, *tmpx, *tmpy;
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)c0; (void)c1; (void)c2;
IF_HAVE_INTEL_MULX(ret = fp_mul_comba_mulx(A, B, C), return ret) ;
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
COMBA_START;
COMBA_CLEAR;
/* get size of output and trim */
pa = A->used + B->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* Always take branch to use tmp variable. This avoids a cache attack for
* determining if C equals A */
if (1) {
fp_init(tmp);
dst = tmp;
}
for (ix = 0; ix < pa; ix++) {
/* get offsets into the two bignums */
ty = MIN(ix, (B->used > 0 ? B->used - 1 : 0));
tx = ix - ty;
/* setup temp aliases */
tmpx = A->dp + tx;
tmpy = B->dp + ty;
/* this is the number of times the loop will iterate, essentially its
while (tx++ < a->used && ty-- >= 0) { ... }
*/
iy = MIN(A->used-tx, ty+1);
/* execute loop */
COMBA_FORWARD;
for (iz = 0; iz < iy; ++iz) {
fp_digit _tmpx = *tmpx++;
fp_digit _tmpy = *tmpy--;
MULADD(_tmpx, _tmpy);
}
/* store term */
COMBA_STORE(dst->dp[ix]);
}
COMBA_FINI;
dst->used = pa;
dst->sign = A->sign ^ B->sign;
fp_clamp(dst);
fp_copy(dst, C);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return ret;
}
/* a/b => cb + d == a */
int fp_div(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int n, t, i, norm, neg;
#ifndef WOLFSSL_SMALL_STACK
fp_int q[1], x[1], y[1], t1[1], t2[1];
#else
fp_int *q, *x, *y, *t1, *t2;
#endif
/* is divisor zero ? */
if (fp_iszero (b) == FP_YES) {
return FP_VAL;
}
/* if a < b then q=0, r = a */
if (fp_cmp_mag (a, b) == FP_LT) {
if (d != NULL) {
fp_copy (a, d);
}
if (c != NULL) {
fp_zero (c);
}
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
q = (fp_int*)XMALLOC(sizeof(fp_int) * 5, NULL, DYNAMIC_TYPE_BIGINT);
if (q == NULL) {
return FP_MEM;
}
x = &q[1]; y = &q[2]; t1 = &q[3]; t2 = &q[4];
#endif
fp_init(q);
q->used = a->used + 2;
fp_init(t1);
fp_init(t2);
fp_init_copy(x, a);
fp_init_copy(y, b);
/* fix the sign */
neg = (a->sign == b->sign) ? FP_ZPOS : FP_NEG;
x->sign = y->sign = FP_ZPOS;
/* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */
norm = fp_count_bits(y) % DIGIT_BIT;
if (norm < (int)(DIGIT_BIT-1)) {
norm = (DIGIT_BIT-1) - norm;
fp_mul_2d (x, norm, x);
fp_mul_2d (y, norm, y);
} else {
norm = 0;
}
/* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
n = x->used - 1;
t = y->used - 1;
/* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
fp_lshd (y, n - t); /* y = y*b**{n-t} */
while (fp_cmp (x, y) != FP_LT) {
++(q->dp[n - t]);
fp_sub (x, y, x);
}
/* reset y by shifting it back down */
fp_rshd (y, n - t);
/* step 3. for i from n down to (t + 1) */
for (i = n; i >= (t + 1); i--) {
if (i > x->used) {
continue;
}
/* step 3.1 if xi == yt then set q{i-t-1} to b-1,
* otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
if (x->dp[i] == y->dp[t]) {
q->dp[i - t - 1] = (fp_digit) ((((fp_word)1) << DIGIT_BIT) - 1);
} else {
fp_word tmp;
tmp = ((fp_word) x->dp[i]) << ((fp_word) DIGIT_BIT);
tmp |= ((fp_word) x->dp[i - 1]);
tmp /= ((fp_word)y->dp[t]);
q->dp[i - t - 1] = (fp_digit) (tmp);
}
/* while (q{i-t-1} * (yt * b + y{t-1})) >
xi * b**2 + xi-1 * b + xi-2
do q{i-t-1} -= 1;
*/
q->dp[i - t - 1] = (q->dp[i - t - 1] + 1);
do {
q->dp[i - t - 1] = (q->dp[i - t - 1] - 1);
/* find left hand */
fp_zero (t1);
t1->dp[0] = (t - 1 < 0) ? 0 : y->dp[t - 1];
t1->dp[1] = y->dp[t];
t1->used = 2;
fp_mul_d (t1, q->dp[i - t - 1], t1);
/* find right hand */
t2->dp[0] = (i - 2 < 0) ? 0 : x->dp[i - 2];
t2->dp[1] = (i - 1 < 0) ? 0 : x->dp[i - 1];
t2->dp[2] = x->dp[i];
t2->used = 3;
} while (fp_cmp_mag(t1, t2) == FP_GT);
/* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
fp_mul_d (y, q->dp[i - t - 1], t1);
fp_lshd (t1, i - t - 1);
fp_sub (x, t1, x);
/* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
if (x->sign == FP_NEG) {
fp_copy (y, t1);
fp_lshd (t1, i - t - 1);
fp_add (x, t1, x);
q->dp[i - t - 1] = q->dp[i - t - 1] - 1;
}
}
/* now q is the quotient and x is the remainder
* [which we have to normalize]
*/
/* get sign before writing to c */
x->sign = x->used == 0 ? FP_ZPOS : a->sign;
if (c != NULL) {
fp_clamp (q);
fp_copy (q, c);
c->sign = neg;
}
if (d != NULL) {
fp_div_2d (x, norm, x, NULL);
/* zero any excess digits on the destination that we didn't write to */
for (i = b->used; i < x->used; i++) {
x->dp[i] = 0;
}
fp_clamp(x);
fp_copy (x, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(q, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* b = a/2 */
void fp_div_2(fp_int * a, fp_int * b)
{
int x, oldused;
oldused = b->used;
b->used = a->used;
{
fp_digit r, rr, *tmpa, *tmpb;
/* source alias */
tmpa = a->dp + b->used - 1;
/* dest alias */
tmpb = b->dp + b->used - 1;
/* carry */
r = 0;
for (x = b->used - 1; x >= 0; x--) {
/* get the carry for the next iteration */
rr = *tmpa & 1;
/* shift the current digit, add in carry and store */
*tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
/* forward carry to next iteration */
r = rr;
}
/* zero any excess digits on the destination that we didn't write to */
tmpb = b->dp + b->used;
for (x = b->used; x < oldused; x++) {
*tmpb++ = 0;
}
}
b->sign = a->sign;
fp_clamp (b);
}
/* c = a / 2**b */
void fp_div_2d(fp_int *a, int b, fp_int *c, fp_int *d)
{
int D;
/* if the shift count is <= 0 then we do no work */
if (b <= 0) {
fp_copy (a, c);
if (d != NULL) {
fp_zero (d);
}
return;
}
/* get the remainder before a is changed in calculating c */
if (a == c && d != NULL) {
fp_mod_2d (a, b, d);
}
/* copy */
fp_copy(a, c);
/* shift by as many digits in the bit count */
if (b >= (int)DIGIT_BIT) {
fp_rshd (c, b / DIGIT_BIT);
}
/* shift any bit count < DIGIT_BIT */
D = (b % DIGIT_BIT);
if (D != 0) {
fp_rshb(c, D);
}
/* get the remainder if a is not changed in calculating c */
if (a != c && d != NULL) {
fp_mod_2d (a, b, d);
}
fp_clamp (c);
}
/* c = a mod b, 0 <= c < b */
int fp_mod(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
int err;
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_div(a, b, NULL, t);
if (err == FP_OKAY) {
if (t->sign != b->sign) {
fp_add(t, b, c);
} else {
fp_copy(t, c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* c = a mod 2**d */
void fp_mod_2d(fp_int *a, int b, fp_int *c)
{
int x;
/* zero if count less than or equal to zero */
if (b <= 0) {
fp_zero(c);
return;
}
/* get copy of input */
fp_copy(a, c);
/* if 2**d is larger than we just return */
if (b >= (DIGIT_BIT * a->used)) {
return;
}
/* zero digits above the last digit of the modulus */
for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
c->dp[x] = 0;
}
/* clear the digit that is not completely outside/inside the modulus */
c->dp[b / DIGIT_BIT] &= ~((fp_digit)0) >> (DIGIT_BIT - b);
fp_clamp (c);
}
static int fp_invmod_slow (fp_int * a, fp_int * b, fp_int * c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int x[1], y[1], u[1], v[1], A[1], B[1], C[1], D[1];
#else
fp_int *x, *y, *u, *v, *A, *B, *C, *D;
#endif
int err;
/* b cannot be negative */
if (b->sign == FP_NEG || fp_iszero(b) == FP_YES) {
return FP_VAL;
}
if (fp_iszero(a) == FP_YES) {
return FP_VAL;
}
#ifdef WOLFSSL_SMALL_STACK
x = (fp_int*)XMALLOC(sizeof(fp_int) * 8, NULL, DYNAMIC_TYPE_BIGINT);
if (x == NULL) {
return FP_MEM;
}
y = &x[1]; u = &x[2]; v = &x[3]; A = &x[4]; B = &x[5]; C = &x[6]; D = &x[7];
#endif
/* init temps */
fp_init(x); fp_init(y);
fp_init(u); fp_init(v);
fp_init(A); fp_init(B);
fp_init(C); fp_init(D);
/* x = a, y = b */
if ((err = fp_mod(a, b, x)) != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_copy(b, y);
/* 2. [modified] if x,y are both even then return an error! */
if (fp_iseven(x) == FP_YES && fp_iseven(y) == FP_YES) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
fp_copy (x, u);
fp_copy (y, v);
fp_set (A, 1);
fp_set (D, 1);
top:
/* 4. while u is even do */
while (fp_iseven (u) == FP_YES) {
/* 4.1 u = u/2 */
fp_div_2 (u, u);
/* 4.2 if A or B is odd then */
if (fp_isodd (A) == FP_YES || fp_isodd (B) == FP_YES) {
/* A = (A+y)/2, B = (B-x)/2 */
fp_add (A, y, A);
fp_sub (B, x, B);
}
/* A = A/2, B = B/2 */
fp_div_2 (A, A);
fp_div_2 (B, B);
}
/* 5. while v is even do */
while (fp_iseven (v) == FP_YES) {
/* 5.1 v = v/2 */
fp_div_2 (v, v);
/* 5.2 if C or D is odd then */
if (fp_isodd (C) == FP_YES || fp_isodd (D) == FP_YES) {
/* C = (C+y)/2, D = (D-x)/2 */
fp_add (C, y, C);
fp_sub (D, x, D);
}
/* C = C/2, D = D/2 */
fp_div_2 (C, C);
fp_div_2 (D, D);
}
/* 6. if u >= v then */
if (fp_cmp (u, v) != FP_LT) {
/* u = u - v, A = A - C, B = B - D */
fp_sub (u, v, u);
fp_sub (A, C, A);
fp_sub (B, D, B);
} else {
/* v - v - u, C = C - A, D = D - B */
fp_sub (v, u, v);
fp_sub (C, A, C);
fp_sub (D, B, D);
}
/* if not zero goto step 4 */
if (fp_iszero (u) == FP_NO)
goto top;
/* now a = C, b = D, gcd == g*v */
/* if v != 1 then there is no inverse */
if (fp_cmp_d (v, 1) != FP_EQ) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* if its too low */
while (fp_cmp_d(C, 0) == FP_LT) {
fp_add(C, b, C);
}
/* too big */
while (fp_cmp_mag(C, b) != FP_LT) {
fp_sub(C, b, C);
}
/* C is now the inverse */
fp_copy(C, c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* c = 1/a (mod b) for odd b only */
int fp_invmod(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int x[1], y[1], u[1], v[1], B[1], D[1];
#else
fp_int *x, *y, *u, *v, *B, *D;
#endif
int neg;
int err;
if (b->sign == FP_NEG || fp_iszero(b) == FP_YES) {
return FP_VAL;
}
/* [modified] sanity check on "a" */
if (fp_iszero(a) == FP_YES) {
return FP_VAL; /* can not divide by 0 here */
}
/* 2. [modified] b must be odd */
if (fp_iseven(b) == FP_YES) {
return fp_invmod_slow(a,b,c);
}
#ifdef WOLFSSL_SMALL_STACK
x = (fp_int*)XMALLOC(sizeof(fp_int) * 6, NULL, DYNAMIC_TYPE_BIGINT);
if (x == NULL) {
return FP_MEM;
}
y = &x[1]; u = &x[2]; v = &x[3]; B = &x[4]; D = &x[5];
#endif
/* init all our temps */
fp_init(x); fp_init(y);
fp_init(u); fp_init(v);
fp_init(B); fp_init(D);
if (fp_cmp(a, b) != MP_LT) {
err = mp_mod(a, b, y);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
a = y;
}
if (fp_iszero(a) == FP_YES) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* x == modulus, y == value to invert */
fp_copy(b, x);
/* we need y = |a| */
fp_abs(a, y);
/* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
fp_copy(x, u);
fp_copy(y, v);
fp_set (D, 1);
top:
/* 4. while u is even do */
while (fp_iseven (u) == FP_YES) {
/* 4.1 u = u/2 */
fp_div_2 (u, u);
/* 4.2 if B is odd then */
if (fp_isodd (B) == FP_YES) {
fp_sub (B, x, B);
}
/* B = B/2 */
fp_div_2 (B, B);
}
/* 5. while v is even do */
while (fp_iseven (v) == FP_YES) {
/* 5.1 v = v/2 */
fp_div_2 (v, v);
/* 5.2 if D is odd then */
if (fp_isodd (D) == FP_YES) {
/* D = (D-x)/2 */
fp_sub (D, x, D);
}
/* D = D/2 */
fp_div_2 (D, D);
}
/* 6. if u >= v then */
if (fp_cmp (u, v) != FP_LT) {
/* u = u - v, B = B - D */
fp_sub (u, v, u);
fp_sub (B, D, B);
} else {
/* v - v - u, D = D - B */
fp_sub (v, u, v);
fp_sub (D, B, D);
}
/* if not zero goto step 4 */
if (fp_iszero (u) == FP_NO) {
goto top;
}
/* now a = C, b = D, gcd == g*v */
/* if v != 1 then there is no inverse */
if (fp_cmp_d (v, 1) != FP_EQ) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* b is now the inverse */
neg = a->sign;
while (D->sign == FP_NEG) {
fp_add (D, b, D);
}
/* too big */
while (fp_cmp_mag(D, b) != FP_LT) {
fp_sub(D, b, D);
}
fp_copy (D, c);
c->sign = neg;
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* d = a * b (mod c) */
int fp_mulmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_mul(a, b, t);
if (err == FP_OKAY) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* d = a - b (mod c) */
int fp_submod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
fp_sub(a, b, t);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* d = a + b (mod c) */
int fp_addmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
fp_add(a, b, t);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#ifdef TFM_TIMING_RESISTANT
#ifdef WC_RSA_NONBLOCK
#ifdef WC_RSA_NONBLOCK_TIME
/* User can override the check-time at build-time using the
* FP_EXPTMOD_NB_CHECKTIME macro to define your own function */
#ifndef FP_EXPTMOD_NB_CHECKTIME
/* instruction count for each type of operation */
/* array lookup is using TFM_EXPTMOD_NB_* states */
static const word32 exptModNbInst[TFM_EXPTMOD_NB_COUNT] = {
#ifdef TFM_PPC32
#ifdef _DEBUG
11098, 8701, 3971, 178394, 858093, 1040, 822, 178056, 181574, 90883, 184339, 236813
#else
7050, 2554, 3187, 43178, 200422, 384, 275, 43024, 43550, 30450, 46270, 61376
#endif
#elif defined(TFM_X86_64)
#ifdef _DEBUG
954, 2377, 858, 19027, 90840, 287, 407, 20140, 7874, 11385, 8005, 6151
#else
765, 1007, 771, 5216, 34993, 248, 193, 4975, 4201, 3947, 4275, 3811
#endif
#else /* software only fast math */
#ifdef _DEBUG
798, 2245, 802, 16657, 66920, 352, 186, 16997, 16145, 12789, 16742, 15006
#else
775, 1084, 783, 4692, 37510, 207, 183, 4374, 4392, 3097, 4442, 4079
#endif
#endif
};
static int fp_exptmod_nb_checktime(exptModNb_t* nb)
{
word32 totalInst;
/* if no max time has been set then stop (do not block) */
if (nb->maxBlockInst == 0 || nb->state >= TFM_EXPTMOD_NB_COUNT) {
return TFM_EXPTMOD_NB_STOP;
}
/* if instruction table not set then use maxBlockInst as simple counter */
if (exptModNbInst[nb->state] == 0) {
if (++nb->totalInst < nb->maxBlockInst)
return TFM_EXPTMOD_NB_CONTINUE;
nb->totalInst = 0; /* reset counter */
return TFM_EXPTMOD_NB_STOP;
}
/* get total instruction count including next operation */
totalInst = nb->totalInst + exptModNbInst[nb->state];
/* if the next operation can completed within the maximum then continue */
if (totalInst <= nb->maxBlockInst) {
return TFM_EXPTMOD_NB_CONTINUE;
}
return TFM_EXPTMOD_NB_STOP;
}
#define FP_EXPTMOD_NB_CHECKTIME(nb) fp_exptmod_nb_checktime((nb))
#endif /* !FP_EXPTMOD_NB_CHECKTIME */
#endif /* WC_RSA_NONBLOCK_TIME */
/* non-blocking version of timing resistant fp_exptmod function */
/* supports cache resistance */
int fp_exptmod_nb(exptModNb_t* nb, fp_int* G, fp_int* X, fp_int* P, fp_int* Y)
{
int err, ret = FP_WOULDBLOCK;
if (nb == NULL)
return FP_VAL;
#ifdef WC_RSA_NONBLOCK_TIME
nb->totalInst = 0;
do {
nb->totalInst += exptModNbInst[nb->state];
#endif
switch (nb->state) {
case TFM_EXPTMOD_NB_INIT:
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &nb->mp)) != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
/* init ints */
fp_init(&nb->R[0]);
fp_init(&nb->R[1]);
#ifndef WC_NO_CACHE_RESISTANT
fp_init(&nb->R[2]);
#endif
nb->state = TFM_EXPTMOD_NB_MONT;
break;
case TFM_EXPTMOD_NB_MONT:
/* mod m -> R[0] */
fp_montgomery_calc_normalization(&nb->R[0], P);
nb->state = TFM_EXPTMOD_NB_MONT_RED;
break;
case TFM_EXPTMOD_NB_MONT_RED:
/* reduce G -> R[1] */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &nb->R[1]);
} else {
fp_copy(G, &nb->R[1]);
}
nb->state = TFM_EXPTMOD_NB_MONT_MUL;
break;
case TFM_EXPTMOD_NB_MONT_MUL:
/* G (R[1]) * m (R[0]) */
err = fp_mul(&nb->R[1], &nb->R[0], &nb->R[1]);
if (err != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
nb->state = TFM_EXPTMOD_NB_MONT_MOD;
break;
case TFM_EXPTMOD_NB_MONT_MOD:
/* mod m */
err = fp_div(&nb->R[1], P, NULL, &nb->R[1]);
if (err != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
nb->state = TFM_EXPTMOD_NB_MONT_MODCHK;
break;
case TFM_EXPTMOD_NB_MONT_MODCHK:
/* m matches sign of (G * R mod m) */
if (nb->R[1].sign != P->sign) {
fp_add(&nb->R[1], P, &nb->R[1]);
}
/* set initial mode and bit cnt */
nb->bitcnt = 1;
nb->buf = 0;
nb->digidx = X->used - 1;
nb->state = TFM_EXPTMOD_NB_NEXT;
break;
case TFM_EXPTMOD_NB_NEXT:
/* grab next digit as required */
if (--nb->bitcnt == 0) {
/* if nb->digidx == -1 we are out of digits so break */
if (nb->digidx == -1) {
nb->state = TFM_EXPTMOD_NB_RED;
break;
}
/* read next digit and reset nb->bitcnt */
nb->buf = X->dp[nb->digidx--];
nb->bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
nb->y = (int)(nb->buf >> (DIGIT_BIT - 1)) & 1;
nb->buf <<= (fp_digit)1;
nb->state = TFM_EXPTMOD_NB_MUL;
FALL_THROUGH;
case TFM_EXPTMOD_NB_MUL:
fp_mul(&nb->R[0], &nb->R[1], &nb->R[nb->y^1]);
nb->state = TFM_EXPTMOD_NB_MUL_RED;
break;
case TFM_EXPTMOD_NB_MUL_RED:
fp_montgomery_reduce(&nb->R[nb->y^1], P, nb->mp);
nb->state = TFM_EXPTMOD_NB_SQR;
break;
case TFM_EXPTMOD_NB_SQR:
#ifdef WC_NO_CACHE_RESISTANT
fp_sqr(&nb->R[nb->y], &nb->R[nb->y]);
#else
fp_copy((fp_int*) ( ((wolfssl_word)&nb->R[0] & wc_off_on_addr[nb->y^1]) +
((wolfssl_word)&nb->R[1] & wc_off_on_addr[nb->y]) ),
&nb->R[2]);
fp_sqr(&nb->R[2], &nb->R[2]);
#endif /* WC_NO_CACHE_RESISTANT */
nb->state = TFM_EXPTMOD_NB_SQR_RED;
break;
case TFM_EXPTMOD_NB_SQR_RED:
#ifdef WC_NO_CACHE_RESISTANT
fp_montgomery_reduce(&nb->R[nb->y], P, nb->mp);
#else
fp_montgomery_reduce(&nb->R[2], P, nb->mp);
fp_copy(&nb->R[2],
(fp_int*) ( ((wolfssl_word)&nb->R[0] & wc_off_on_addr[nb->y^1]) +
((wolfssl_word)&nb->R[1] & wc_off_on_addr[nb->y]) ) );
#endif /* WC_NO_CACHE_RESISTANT */
nb->state = TFM_EXPTMOD_NB_NEXT;
break;
case TFM_EXPTMOD_NB_RED:
/* final reduce */
fp_montgomery_reduce(&nb->R[0], P, nb->mp);
fp_copy(&nb->R[0], Y);
nb->state = TFM_EXPTMOD_NB_INIT;
ret = FP_OKAY;
break;
} /* switch */
#ifdef WC_RSA_NONBLOCK_TIME
/* determine if maximum blocking time has been reached */
} while (ret == FP_WOULDBLOCK &&
FP_EXPTMOD_NB_CHECKTIME(nb) == TFM_EXPTMOD_NB_CONTINUE);
#endif
return ret;
}
#endif /* WC_RSA_NONBLOCK */
/* timing resistant montgomery ladder based exptmod
Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder",
Cryptographic Hardware and Embedded Systems, CHES 2002
*/
static int _fp_exptmod(fp_int * G, fp_int * X, int digits, fp_int * P, fp_int * Y)
{
#ifndef WOLFSSL_SMALL_STACK
#ifdef WC_NO_CACHE_RESISTANT
fp_int R[2];
#else
fp_int R[3]; /* need a temp for cache resistance */
#endif
#else
fp_int *R;
#endif
fp_digit buf, mp;
int err, bitcnt, digidx, y;
/* now setup montgomery */
if ((err = fp_montgomery_setup (P, &mp)) != FP_OKAY) {
return err;
}
#ifdef WOLFSSL_SMALL_STACK
#ifndef WC_NO_CACHE_RESISTANT
R = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
#else
R = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
#endif
if (R == NULL)
return FP_MEM;
#endif
fp_init(&R[0]);
fp_init(&R[1]);
#ifndef WC_NO_CACHE_RESISTANT
fp_init(&R[2]);
#endif
/* now we need R mod m */
fp_montgomery_calc_normalization (&R[0], P);
/* now set R[0][1] to G * R mod m */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &R[1]);
} else {
fp_copy(G, &R[1]);
}
fp_mulmod (&R[1], &R[0], P, &R[1]);
/* for j = t-1 downto 0 do
r_!k = R0*R1; r_k = r_k^2
*/
/* set initial mode and bit cnt */
bitcnt = 1;
buf = 0;
digidx = digits - 1;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* do ops */
err = fp_mul(&R[0], &R[1], &R[y^1]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[y^1], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#ifdef WC_NO_CACHE_RESISTANT
err = fp_sqr(&R[y], &R[y]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[y], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#else
/* instead of using R[y] for sqr, which leaks key bit to cache monitor,
* use R[2] as temp, make sure address calc is constant, keep
* &R[0] and &R[1] in cache */
fp_copy((fp_int*) ( ((wolfssl_word)&R[0] & wc_off_on_addr[y^1]) +
((wolfssl_word)&R[1] & wc_off_on_addr[y]) ),
&R[2]);
err = fp_sqr(&R[2], &R[2]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[2], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_copy(&R[2],
(fp_int*) ( ((wolfssl_word)&R[0] & wc_off_on_addr[y^1]) +
((wolfssl_word)&R[1] & wc_off_on_addr[y]) ) );
#endif /* WC_NO_CACHE_RESISTANT */
}
err = fp_montgomery_reduce(&R[0], P, mp);
fp_copy(&R[0], Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#else /* TFM_TIMING_RESISTANT */
/* y = g**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod(fp_int * G, fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
fp_int *M;
#else
fp_int res[1];
fp_int M[64];
#endif
(void)digits;
/* find window size */
x = fp_count_bits (X);
if (x <= 21) {
winsize = 1;
} else if (x <= 36) {
winsize = 3;
} else if (x <= 140) {
winsize = 4;
} else if (x <= 450) {
winsize = 5;
} else {
winsize = 6;
}
/* now setup montgomery */
if ((err = fp_montgomery_setup (P, &mp)) != FP_OKAY) {
return err;
}
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
M = (fp_int*)XMALLOC(sizeof(fp_int)*((1 << winsize) + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (M == NULL) {
return FP_MEM;
}
res = &M[1 << winsize];
#endif
/* init M array */
for(x = 0; x < (1 << winsize); x++)
fp_init(&M[x]);
/* setup result */
fp_init(res);
/* create M table
*
* The M table contains powers of the input base, e.g. M[x] = G^x mod P
*
* The first half of the table is not computed though except for M[0] and M[1]
*/
/* now we need R mod m */
fp_montgomery_calc_normalization (res, P);
/* now set M[1] to G * R mod m */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &M[1]);
} else {
fp_copy(G, &M[1]);
}
fp_mulmod (&M[1], res, P, &M[1]);
/* compute the value at M[1<<(winsize-1)] by
* squaring M[1] (winsize-1) times */
fp_copy (&M[1], &M[1 << (winsize - 1)]);
for (x = 0; x < (winsize - 1); x++) {
fp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)]);
err = fp_montgomery_reduce (&M[1 << (winsize - 1)], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* create upper table */
for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
err = fp_mul(&M[x - 1], &M[1], &M[x]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&M[x], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* set initial mode and bit cnt */
mode = 0;
bitcnt = 1;
buf = 0;
digidx = X->used - 1;
bitcpy = 0;
bitbuf = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* if the bit is zero and mode == 0 then we ignore it
* These represent the leading zero bits before the first 1 bit
* in the exponent. Technically this opt is not required but it
* does lower the # of trivial squaring/reductions used
*/
if (mode == 0 && y == 0) {
continue;
}
/* if the bit is zero and mode == 1 then we square */
if (mode == 1 && y == 0) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
continue;
}
/* else we add it to the window */
bitbuf |= (y << (winsize - ++bitcpy));
mode = 2;
if (bitcpy == winsize) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < winsize; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* then multiply */
err = fp_mul(res, &M[bitbuf], res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
mode = 1;
}
}
/* if bits remain then square/multiply */
if (mode == 2 && bitcpy > 0) {
/* square then multiply if the bit is set */
for (x = 0; x < bitcpy; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* get next bit of the window */
bitbuf <<= 1;
if ((bitbuf & (1 << winsize)) != 0) {
/* then multiply */
err = fp_mul(res, &M[1], res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy (res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#endif /* TFM_TIMING_RESISTANT */
#ifdef TFM_TIMING_RESISTANT
#if DIGIT_BIT <= 16
#define WINSIZE 2
#elif DIGIT_BIT <= 32
#define WINSIZE 3
#elif DIGIT_BIT <= 64
#define WINSIZE 4
#elif DIGIT_BIT <= 128
#define WINSIZE 5
#endif
/* y = 2**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod_base_2(fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, digidx, x, y;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
fp_int *tmp;
#else
fp_int res[1];
fp_int tmp[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
res = (fp_int*)XMALLOC(2*sizeof(fp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (res == NULL) {
return FP_MEM;
}
tmp = &res[1];
#endif
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &mp)) != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* setup result */
fp_init(res);
fp_init(tmp);
fp_mul_2d(P, 1 << WINSIZE, tmp);
/* now we need R mod m */
fp_montgomery_calc_normalization(res, P);
/* Get the top bits left over after taking WINSIZE bits starting at the
* least-significant.
*/
digidx = digits - 1;
bitcpy = (digits * DIGIT_BIT) % WINSIZE;
if (bitcpy > 0) {
bitcnt = (int)DIGIT_BIT - bitcpy;
buf = X->dp[digidx--];
bitbuf = (int)(buf >> bitcnt);
/* Multiply montgomery representation of 1 by 2 ^ top */
fp_mul_2d(res, bitbuf, res);
fp_add(res, tmp, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* Move out bits used */
buf <<= bitcpy;
bitcnt++;
}
else {
bitcnt = 1;
buf = 0;
}
/* empty window and reset */
bitbuf = 0;
bitcpy = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* add bit to the window */
bitbuf |= (y << (WINSIZE - ++bitcpy));
if (bitcpy == WINSIZE) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < WINSIZE; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
}
/* then multiply by 2^bitbuf */
fp_mul_2d(res, bitbuf, res);
/* Add in value to make mod operation take same time */
fp_add(res, tmp, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy(res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
#undef WINSIZE
#else
#if DIGIT_BIT < 16
#define WINSIZE 3
#elif DIGIT_BIT < 32
#define WINSIZE 4
#elif DIGIT_BIT < 64
#define WINSIZE 5
#elif DIGIT_BIT < 128
#define WINSIZE 6
#elif DIGIT_BIT == 128
#define WINSIZE 7
#endif
/* y = 2**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod_base_2(fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, digidx, x, y;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
#else
fp_int res[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
res = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (res == NULL) {
return FP_MEM;
}
#endif
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &mp)) != FP_OKAY) {
return err;
}
/* setup result */
fp_init(res);
/* now we need R mod m */
fp_montgomery_calc_normalization(res, P);
/* Get the top bits left over after taking WINSIZE bits starting at the
* least-significant.
*/
digidx = digits - 1;
bitcpy = (digits * DIGIT_BIT) % WINSIZE;
if (bitcpy > 0) {
bitcnt = (int)DIGIT_BIT - bitcpy;
buf = X->dp[digidx--];
bitbuf = (int)(buf >> bitcnt);
/* Multiply montgomery representation of 1 by 2 ^ top */
fp_mul_2d(res, bitbuf, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* Move out bits used */
buf <<= bitcpy;
bitcnt++;
}
else {
bitcnt = 1;
buf = 0;
}
/* empty window and reset */
bitbuf = 0;
bitcpy = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* add bit to the window */
bitbuf |= (y << (WINSIZE - ++bitcpy));
if (bitcpy == WINSIZE) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < WINSIZE; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
}
/* then multiply by 2^bitbuf */
fp_mul_2d(res, bitbuf, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy(res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
#undef WINSIZE
#endif
int fp_exptmod(fp_int * G, fp_int * X, fp_int * P, fp_int * Y)
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int x = fp_count_bits (X);
#endif
/* handle modulus of zero and prevent overflows */
if (fp_iszero(P) || (P->used > (FP_SIZE/2))) {
return FP_VAL;
}
if (fp_isone(P)) {
fp_set(Y, 0);
return FP_OKAY;
}
if (fp_iszero(X)) {
fp_set(Y, 1);
return FP_OKAY;
}
if (fp_iszero(G)) {
fp_set(Y, 0);
return FP_OKAY;
}
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
if(x > EPS_RSA_EXPT_XBTIS) {
return esp_mp_exptmod(G, X, x, P, Y);
}
#endif
if (X->sign == FP_NEG) {
#ifndef POSITIVE_EXP_ONLY /* reduce stack if assume no negatives */
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[2];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* yes, copy G and invmod it */
fp_init_copy(&tmp[0], G);
fp_init_copy(&tmp[1], P);
tmp[1].sign = FP_ZPOS;
err = fp_invmod(&tmp[0], &tmp[1], &tmp[0]);
if (err == FP_OKAY) {
fp_copy(X, &tmp[1]);
tmp[1].sign = FP_ZPOS;
err = _fp_exptmod(&tmp[0], &tmp[1], tmp[1].used, P, Y);
if (P->sign == FP_NEG) {
fp_add(Y, P, Y);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
#else
return FP_VAL;
#endif
}
else if (G->used == 1 && G->dp[0] == 2) {
return _fp_exptmod_base_2(X, X->used, P, Y);
}
else {
/* Positive exponent so just exptmod */
return _fp_exptmod(G, X, X->used, P, Y);
}
}
int fp_exptmod_ex(fp_int * G, fp_int * X, int digits, fp_int * P, fp_int * Y)
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int x = fp_count_bits (X);
#endif
if (fp_iszero(G)) {
fp_set(G, 0);
return FP_OKAY;
}
/* prevent overflows */
if (P->used > (FP_SIZE/2)) {
return FP_VAL;
}
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
if(x > EPS_RSA_EXPT_XBTIS) {
return esp_mp_exptmod(G, X, x, P, Y);
}
#endif
if (X->sign == FP_NEG) {
#ifndef POSITIVE_EXP_ONLY /* reduce stack if assume no negatives */
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[2];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (tmp == NULL)
return FP_MEM;
#endif
/* yes, copy G and invmod it */
fp_init_copy(&tmp[0], G);
fp_init_copy(&tmp[1], P);
tmp[1].sign = FP_ZPOS;
err = fp_invmod(&tmp[0], &tmp[1], &tmp[0]);
if (err == FP_OKAY) {
X->sign = FP_ZPOS;
err = _fp_exptmod(&tmp[0], X, digits, P, Y);
if (X != Y) {
X->sign = FP_NEG;
}
if (P->sign == FP_NEG) {
fp_add(Y, P, Y);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
#else
return FP_VAL;
#endif
}
else {
/* Positive exponent so just exptmod */
return _fp_exptmod(G, X, digits, P, Y);
}
}
/* computes a = 2**b */
void fp_2expt(fp_int *a, int b)
{
int z;
/* zero a as per default */
fp_zero (a);
if (b < 0) {
return;
}
z = b / DIGIT_BIT;
if (z >= FP_SIZE) {
return;
}
/* set the used count of where the bit will go */
a->used = z + 1;
/* put the single bit in its place */
a->dp[z] = ((fp_digit)1) << (b % DIGIT_BIT);
}
/* b = a*a */
int fp_sqr(fp_int *A, fp_int *B)
{
int err;
int y, oldused;
oldused = B->used;
y = A->used;
/* call generic if we're out of range */
if (y + y > FP_SIZE) {
err = fp_sqr_comba(A, B);
goto clean;
}
#if defined(TFM_SQR3) && FP_SIZE >= 6
if (y <= 3) {
err = fp_sqr_comba3(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR4) && FP_SIZE >= 8
if (y == 4) {
err = fp_sqr_comba4(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR6) && FP_SIZE >= 12
if (y <= 6) {
err = fp_sqr_comba6(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR7) && FP_SIZE >= 14
if (y == 7) {
err = fp_sqr_comba7(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR8) && FP_SIZE >= 16
if (y == 8) {
err = fp_sqr_comba8(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR9) && FP_SIZE >= 18
if (y == 9) {
err = fp_sqr_comba9(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR12) && FP_SIZE >= 24
if (y <= 12) {
err = fp_sqr_comba12(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR17) && FP_SIZE >= 34
if (y <= 17) {
err = fp_sqr_comba17(A,B);
goto clean;
}
#endif
#if defined(TFM_SMALL_SET)
if (y <= 16) {
err = fp_sqr_comba_small(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR20) && FP_SIZE >= 40
if (y <= 20) {
err = fp_sqr_comba20(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR24) && FP_SIZE >= 48
if (y <= 24) {
err = fp_sqr_comba24(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR28) && FP_SIZE >= 56
if (y <= 28) {
err = fp_sqr_comba28(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR32) && FP_SIZE >= 64
if (y <= 32) {
err = fp_sqr_comba32(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR48) && FP_SIZE >= 96
if (y <= 48) {
err = fp_sqr_comba48(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR64) && FP_SIZE >= 128
if (y <= 64) {
err = fp_sqr_comba64(A,B);
goto clean;
}
#endif
err = fp_sqr_comba(A, B);
clean:
/* zero any excess digits on the destination that we didn't write to */
for (y = B->used; y >= 0 && y < oldused; y++) {
B->dp[y] = 0;
}
return err;
}
/* generic comba squarer */
int fp_sqr_comba(fp_int *A, fp_int *B)
{
int pa, ix, iz;
fp_digit c0, c1, c2;
#ifdef TFM_ISO
fp_word tt;
#endif
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)c0; (void)c1; (void)c2;
#ifdef TFM_ISO
(void)tt;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* get size of output and trim */
pa = A->used + A->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* number of output digits to produce */
COMBA_START;
COMBA_CLEAR;
if (A == B) {
fp_init(tmp);
dst = tmp;
} else {
fp_zero(B);
dst = B;
}
for (ix = 0; ix < pa; ix++) {
int tx, ty, iy;
fp_digit *tmpy, *tmpx;
/* get offsets into the two bignums */
ty = MIN(A->used-1, ix);
tx = ix - ty;
/* setup temp aliases */
tmpx = A->dp + tx;
tmpy = A->dp + ty;
/* this is the number of times the loop will iterate,
while (tx++ < a->used && ty-- >= 0) { ... }
*/
iy = MIN(A->used-tx, ty+1);
/* now for squaring tx can never equal ty
* we halve the distance since they approach
* at a rate of 2x and we have to round because
* odd cases need to be executed
*/
iy = MIN(iy, (ty-tx+1)>>1);
/* forward carries */
COMBA_FORWARD;
/* execute loop */
for (iz = 0; iz < iy; iz++) {
SQRADD2(*tmpx++, *tmpy--);
}
/* even columns have the square term in them */
if ((ix&1) == 0) {
/* TAO change COMBA_ADD back to SQRADD */
SQRADD(A->dp[ix>>1], A->dp[ix>>1]);
}
/* store it */
COMBA_STORE(dst->dp[ix]);
}
COMBA_FINI;
/* setup dest */
dst->used = pa;
fp_clamp (dst);
if (dst != B) {
fp_copy(dst, B);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int fp_cmp(fp_int *a, fp_int *b)
{
if (a->sign == FP_NEG && b->sign == FP_ZPOS) {
return FP_LT;
} else if (a->sign == FP_ZPOS && b->sign == FP_NEG) {
return FP_GT;
} else {
/* compare digits */
if (a->sign == FP_NEG) {
/* if negative compare opposite direction */
return fp_cmp_mag(b, a);
} else {
return fp_cmp_mag(a, b);
}
}
}
/* compare against a single digit */
int fp_cmp_d(fp_int *a, fp_digit b)
{
/* special case for zero*/
if (a->used == 0 && b == 0)
return FP_EQ;
/* compare based on sign */
if ((b && a->used == 0) || a->sign == FP_NEG) {
return FP_LT;
}
/* compare based on magnitude */
if (a->used > 1) {
return FP_GT;
}
/* compare the only digit of a to b */
if (a->dp[0] > b) {
return FP_GT;
} else if (a->dp[0] < b) {
return FP_LT;
} else {
return FP_EQ;
}
}
int fp_cmp_mag(fp_int *a, fp_int *b)
{
int x;
if (a->used > b->used) {
return FP_GT;
} else if (a->used < b->used) {
return FP_LT;
} else {
for (x = a->used - 1; x >= 0; x--) {
if (a->dp[x] > b->dp[x]) {
return FP_GT;
} else if (a->dp[x] < b->dp[x]) {
return FP_LT;
}
}
}
return FP_EQ;
}
/* sets up the montgomery reduction */
int fp_montgomery_setup(fp_int *a, fp_digit *rho)
{
fp_digit x, b;
/* fast inversion mod 2**k
*
* Based on the fact that
*
* XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
* => 2*X*A - X*X*A*A = 1
* => 2*(1) - (1) = 1
*/
b = a->dp[0];
if ((b & 1) == 0) {
return FP_VAL;
}
x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
x *= 2 - b * x; /* here x*a==1 mod 2**8 */
x *= 2 - b * x; /* here x*a==1 mod 2**16 */
x *= 2 - b * x; /* here x*a==1 mod 2**32 */
#ifdef FP_64BIT
x *= 2 - b * x; /* here x*a==1 mod 2**64 */
#endif
/* rho = -1/m mod b */
*rho = (fp_digit) (((fp_word) 1 << ((fp_word) DIGIT_BIT)) - ((fp_word)x));
return FP_OKAY;
}
/* computes a = B**n mod b without division or multiplication useful for
* normalizing numbers in a Montgomery system.
*/
void fp_montgomery_calc_normalization(fp_int *a, fp_int *b)
{
int x, bits;
/* how many bits of last digit does b use */
bits = fp_count_bits (b) % DIGIT_BIT;
if (!bits) bits = DIGIT_BIT;
/* compute A = B^(n-1) * 2^(bits-1) */
if (b->used > 1) {
fp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1);
} else {
fp_set(a, 1);
bits = 1;
}
/* now compute C = A * B mod b */
for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
fp_mul_2 (a, a);
if (fp_cmp_mag (a, b) != FP_LT) {
s_fp_sub (a, b, a);
}
}
}
#ifdef TFM_SMALL_MONT_SET
#include "fp_mont_small.i"
#endif
#ifdef HAVE_INTEL_MULX
static WC_INLINE void innermul8_mulx(fp_digit *c_mulx, fp_digit *cy_mulx, fp_digit *tmpm, fp_digit mu)
{
fp_digit cy = *cy_mulx ;
INNERMUL8_MULX ;
*cy_mulx = cy ;
}
/* computes x/R == x (mod N) via Montgomery Reduction */
static int fp_montgomery_reduce_mulx(fp_int *a, fp_int *m, fp_digit mp)
{
#ifndef WOLFSSL_SMALL_STACK
fp_digit c[FP_SIZE+1];
#else
fp_digit *c;
#endif
fp_digit *_c, *tmpm, mu = 0;
int oldused, x, y, pa;
/* bail if too large */
if (m->used > (FP_SIZE/2)) {
(void)mu; /* shut up compiler */
return FP_OKAY;
}
#ifdef TFM_SMALL_MONT_SET
if (m->used <= 16) {
return fp_montgomery_reduce_small(a, m, mp);
}
#endif
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
c = (fp_digit*)XMALLOC(sizeof(fp_digit)*(FP_SIZE + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (c == NULL) {
return FP_MEM;
}
#endif
/* now zero the buff */
XMEMSET(c, 0, sizeof(fp_digit)*(FP_SIZE + 1));
pa = m->used;
/* copy the input */
oldused = a->used;
for (x = 0; x < oldused; x++) {
c[x] = a->dp[x];
}
MONT_START;
for (x = 0; x < pa; x++) {
fp_digit cy = 0;
/* get Mu for this round */
LOOP_START;
_c = c + x;
tmpm = m->dp;
y = 0;
for (; y < (pa & ~7); y += 8) {
innermul8_mulx(_c, &cy, tmpm, mu) ;
_c += 8;
tmpm += 8;
}
for (; y < pa; y++) {
INNERMUL;
++_c;
}
LOOP_END;
while (cy) {
PROPCARRY;
++_c;
}
}
/* now copy out */
_c = c + pa;
tmpm = a->dp;
for (x = 0; x < pa+1; x++) {
*tmpm++ = *_c++;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
*tmpm++ = 0;
}
MONT_FINI;
a->used = pa+1;
fp_clamp(a);
/* if A >= m then A = A - m */
if (fp_cmp_mag (a, m) != FP_LT) {
s_fp_sub (a, m, a);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
/* computes x/R == x (mod N) via Montgomery Reduction */
int fp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp)
{
#ifndef WOLFSSL_SMALL_STACK
fp_digit c[FP_SIZE+1];
#else
fp_digit *c;
#endif
fp_digit *_c, *tmpm, mu = 0;
int oldused, x, y, pa, err = 0;
IF_HAVE_INTEL_MULX(err = fp_montgomery_reduce_mulx(a, m, mp), return err) ;
(void)err;
/* bail if too large */
if (m->used > (FP_SIZE/2)) {
(void)mu; /* shut up compiler */
return FP_OKAY;
}
#ifdef TFM_SMALL_MONT_SET
if (m->used <= 16) {
return fp_montgomery_reduce_small(a, m, mp);
}
#endif
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
c = (fp_digit*)XMALLOC(sizeof(fp_digit)*(FP_SIZE + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (c == NULL) {
return FP_MEM;
}
#endif
/* now zero the buff */
XMEMSET(c, 0, sizeof(fp_digit)*(FP_SIZE + 1));
pa = m->used;
/* copy the input */
oldused = a->used;
for (x = 0; x < oldused; x++) {
c[x] = a->dp[x];
}
MONT_START;
for (x = 0; x < pa; x++) {
fp_digit cy = 0;
/* get Mu for this round */
LOOP_START;
_c = c + x;
tmpm = m->dp;
y = 0;
#if defined(INNERMUL8)
for (; y < (pa & ~7); y += 8) {
INNERMUL8 ;
_c += 8;
tmpm += 8;
}
#endif
for (; y < pa; y++) {
INNERMUL;
++_c;
}
LOOP_END;
while (cy) {
PROPCARRY;
++_c;
}
}
/* now copy out */
_c = c + pa;
tmpm = a->dp;
for (x = 0; x < pa+1; x++) {
*tmpm++ = *_c++;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
*tmpm++ = 0;
}
MONT_FINI;
a->used = pa+1;
fp_clamp(a);
/* if A >= m then A = A - m */
if (fp_cmp_mag (a, m) != FP_LT) {
s_fp_sub (a, m, a);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
void fp_read_unsigned_bin(fp_int *a, const unsigned char *b, int c)
{
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
const word32 maxC = (a->size * sizeof(fp_digit));
#else
const word32 maxC = (FP_SIZE * sizeof(fp_digit));
#endif
/* zero the int */
fp_zero (a);
/* if input b excess max, then truncate */
if (c > 0 && (word32)c > maxC) {
int excess = (c - maxC);
c -= excess;
b += excess;
}
/* If we know the endianness of this architecture, and we're using
32-bit fp_digits, we can optimize this */
#if (defined(LITTLE_ENDIAN_ORDER) || defined(BIG_ENDIAN_ORDER)) && \
defined(FP_32BIT)
/* But not for both simultaneously */
#if defined(LITTLE_ENDIAN_ORDER) && defined(BIG_ENDIAN_ORDER)
#error Both LITTLE_ENDIAN_ORDER and BIG_ENDIAN_ORDER defined.
#endif
{
unsigned char *pd = (unsigned char *)a->dp;
a->used = (c + sizeof(fp_digit) - 1)/sizeof(fp_digit);
/* read the bytes in */
#ifdef BIG_ENDIAN_ORDER
{
/* Use Duff's device to unroll the loop. */
int idx = (c - 1) & ~3;
switch (c % 4) {
case 0: do { pd[idx+0] = *b++; // fallthrough
case 3: pd[idx+1] = *b++; // fallthrough
case 2: pd[idx+2] = *b++; // fallthrough
case 1: pd[idx+3] = *b++; // fallthrough
idx -= 4;
} while ((c -= 4) > 0);
}
}
#else
for (c -= 1; c >= 0; c -= 1) {
pd[c] = *b++;
}
#endif
}
#else
/* read the bytes in */
for (; c > 0; c--) {
fp_mul_2d (a, 8, a);
a->dp[0] |= *b++;
if (a->used == 0) {
a->used = 1;
}
}
#endif
fp_clamp (a);
}
int fp_to_unsigned_bin_at_pos(int x, fp_int *t, unsigned char *b)
{
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
int i, j;
fp_digit n;
for (j=0,i=0; i<t->used-1; ) {
b[x++] = (unsigned char)(t->dp[i] >> j);
j += 8;
i += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
n = t->dp[i];
while (n != 0) {
b[x++] = (unsigned char)n;
n >>= 8;
}
return x;
#else
while (fp_iszero (t) == FP_NO) {
b[x++] = (unsigned char) (t->dp[0] & 255);
fp_div_2d (t, 8, t, NULL);
}
return x;
#endif
}
int fp_to_unsigned_bin(fp_int *a, unsigned char *b)
{
int x;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init_copy(t, a);
x = fp_to_unsigned_bin_at_pos(0, t, b);
fp_reverse (b, x);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int fp_to_unsigned_bin_len(fp_int *a, unsigned char *b, int c)
{
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
int i, j, x;
for (x=c-1,j=0,i=0; x >= 0; x--) {
b[x] = (unsigned char)(a->dp[i] >> j);
j += 8;
i += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
return FP_OKAY;
#else
int x;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init_copy(t, a);
for (x = 0; x < c; x++) {
b[x] = (unsigned char) (t->dp[0] & 255);
fp_div_2d (t, 8, t, NULL);
}
fp_reverse (b, x);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
#endif
}
int fp_unsigned_bin_size(fp_int *a)
{
int size = fp_count_bits (a);
return (size / 8 + ((size & 7) != 0 ? 1 : 0));
}
void fp_set(fp_int *a, fp_digit b)
{
fp_zero(a);
a->dp[0] = b;
a->used = a->dp[0] ? 1 : 0;
}
#ifndef MP_SET_CHUNK_BITS
#define MP_SET_CHUNK_BITS 4
#endif
void fp_set_int(fp_int *a, unsigned long b)
{
int x;
/* use direct fp_set if b is less than fp_digit max */
if (b < FP_DIGIT_MAX) {
fp_set (a, (fp_digit)b);
return;
}
fp_zero (a);
/* set chunk bits at a time */
for (x = 0; x < (int)(sizeof(b) * 8) / MP_SET_CHUNK_BITS; x++) {
fp_mul_2d (a, MP_SET_CHUNK_BITS, a);
/* OR in the top bits of the source */
a->dp[0] |= (b >> ((sizeof(b) * 8) - MP_SET_CHUNK_BITS)) &
((1 << MP_SET_CHUNK_BITS) - 1);
/* shift the source up to the next chunk bits */
b <<= MP_SET_CHUNK_BITS;
/* ensure that digits are not clamped off */
a->used += 1;
}
/* clamp digits */
fp_clamp(a);
}
/* check if a bit is set */
int fp_is_bit_set (fp_int *a, fp_digit b)
{
fp_digit i;
if (b > FP_MAX_BITS)
return 0;
else
i = b/DIGIT_BIT;
if ((fp_digit)a->used < i)
return 0;
return (int)((a->dp[i] >> b%DIGIT_BIT) & (fp_digit)1);
}
/* set the b bit of a */
int fp_set_bit (fp_int * a, fp_digit b)
{
fp_digit i;
if (b > FP_MAX_BITS)
return 0;
else
i = b/DIGIT_BIT;
/* set the used count of where the bit will go if required */
if (a->used < (int)(i+1))
a->used = (int)(i+1);
/* put the single bit in its place */
a->dp[i] |= ((fp_digit)1) << (b % DIGIT_BIT);
return MP_OKAY;
}
int fp_count_bits (fp_int * a)
{
int r;
fp_digit q;
/* shortcut */
if (a->used == 0) {
return 0;
}
/* get number of digits and add that */
r = (a->used - 1) * DIGIT_BIT;
/* take the last digit and count the bits in it */
q = a->dp[a->used - 1];
while (q > ((fp_digit) 0)) {
++r;
q >>= ((fp_digit) 1);
}
return r;
}
int fp_leading_bit(fp_int *a)
{
int bit = 0;
if (a->used != 0) {
fp_digit q = a->dp[a->used - 1];
int qSz = sizeof(fp_digit);
while (qSz > 0) {
if ((unsigned char)q != 0)
bit = (q & 0x80) != 0;
q >>= 8;
qSz--;
}
}
return bit;
}
void fp_lshd(fp_int *a, int x)
{
int y;
/* move up and truncate as required */
y = MIN(a->used + x - 1, (int)(FP_SIZE-1));
/* store new size */
a->used = y + 1;
/* move digits */
for (; y >= x; y--) {
a->dp[y] = a->dp[y-x];
}
/* zero lower digits */
for (; y >= 0; y--) {
a->dp[y] = 0;
}
/* clamp digits */
fp_clamp(a);
}
/* right shift by bit count */
void fp_rshb(fp_int *c, int x)
{
fp_digit *tmpc, mask, shift;
fp_digit r, rr;
fp_digit D = x;
if (fp_iszero(c)) return;
/* mask */
mask = (((fp_digit)1) << D) - 1;
/* shift for lsb */
shift = DIGIT_BIT - D;
/* alias */
tmpc = c->dp + (c->used - 1);
/* carry */
r = 0;
for (x = c->used - 1; x >= 0; x--) {
/* get the lower bits of this word in a temp */
rr = *tmpc & mask;
/* shift the current word and mix in the carry bits from previous word */
*tmpc = (*tmpc >> D) | (r << shift);
--tmpc;
/* set the carry to the carry bits of the current word found above */
r = rr;
}
/* clamp digits */
fp_clamp(c);
}
void fp_rshd(fp_int *a, int x)
{
int y;
/* too many digits just zero and return */
if (x >= a->used) {
fp_zero(a);
return;
}
/* shift */
for (y = 0; y < a->used - x; y++) {
a->dp[y] = a->dp[y+x];
}
/* zero rest */
for (; y < a->used; y++) {
a->dp[y] = 0;
}
/* decrement count */
a->used -= x;
fp_clamp(a);
}
/* reverse an array, used for radix code */
void fp_reverse (unsigned char *s, int len)
{
int ix, iy;
unsigned char t;
ix = 0;
iy = len - 1;
while (ix < iy) {
t = s[ix];
s[ix] = s[iy];
s[iy] = t;
++ix;
--iy;
}
}
/* c = a - b */
int fp_sub_d(fp_int *a, fp_digit b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
fp_init(tmp);
fp_set(tmp, b);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (c->size < FP_SIZE) {
fp_sub(a, tmp, tmp);
fp_copy(tmp, c);
} else
#endif
{
fp_sub(a, tmp, c);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* wolfSSL callers from normal lib */
/* init a new mp_int */
int mp_init (mp_int * a)
{
if (a)
fp_init(a);
return MP_OKAY;
}
void fp_init(fp_int *a)
{
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
a->size = FP_SIZE;
#endif
#ifdef HAVE_WOLF_BIGINT
wc_bigint_init(&a->raw);
#endif
fp_zero(a);
}
void fp_zero(fp_int *a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
XMEMSET(a->dp, 0, size * sizeof(fp_digit));
}
void fp_clear(fp_int *a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
XMEMSET(a->dp, 0, size * sizeof(fp_digit));
fp_free(a);
}
void fp_forcezero (mp_int * a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
ForceZero(a->dp, size * sizeof(fp_digit));
#ifdef HAVE_WOLF_BIGINT
wc_bigint_zero(&a->raw);
#endif
fp_free(a);
}
void mp_forcezero (mp_int * a)
{
fp_forcezero(a);
}
void fp_free(fp_int* a)
{
#ifdef HAVE_WOLF_BIGINT
wc_bigint_free(&a->raw);
#else
(void)a;
#endif
}
/* clear one (frees) */
void mp_clear (mp_int * a)
{
if (a == NULL)
return;
fp_clear(a);
}
void mp_free(mp_int* a)
{
fp_free(a);
}
/* handle up to 6 inits */
int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d,
mp_int* e, mp_int* f)
{
if (a)
fp_init(a);
if (b)
fp_init(b);
if (c)
fp_init(c);
if (d)
fp_init(d);
if (e)
fp_init(e);
if (f)
fp_init(f);
return MP_OKAY;
}
/* high level addition (handles signs) */
int mp_add (mp_int * a, mp_int * b, mp_int * c)
{
fp_add(a, b, c);
return MP_OKAY;
}
/* high level subtraction (handles signs) */
int mp_sub (mp_int * a, mp_int * b, mp_int * c)
{
fp_sub(a, b, c);
return MP_OKAY;
}
/* high level multiplication (handles sign) */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mul(mp_int * a, mp_int * b, mp_int * c)
#else
int mp_mul (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_mul(a, b, c);
}
int mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
{
fp_mul_d(a, b, c);
return MP_OKAY;
}
/* d = a * b (mod c) */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
#else
int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
#endif
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int A = fp_count_bits (a);
int B = fp_count_bits (b);
if( A >= ESP_RSA_MULM_BITS && B >= ESP_RSA_MULM_BITS)
return esp_mp_mulmod(a, b, c, d);
else
#endif
return fp_mulmod(a, b, c, d);
}
/* d = a - b (mod c) */
int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
{
return fp_submod(a, b, c, d);
}
/* d = a + b (mod c) */
int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
{
return fp_addmod(a, b, c, d);
}
/* c = a mod b, 0 <= c < b */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mod (mp_int * a, mp_int * b, mp_int * c)
#else
int mp_mod (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_mod (a, b, c);
}
/* hac 14.61, pp608 */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_invmod (mp_int * a, mp_int * b, mp_int * c)
#else
int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_invmod(a, b, c);
}
/* this is a shell function that calls either the normal or Montgomery
* exptmod functions. Originally the call to the montgomery code was
* embedded in the normal function but that wasted a lot of stack space
* for nothing (since 99% of the time the Montgomery code would be called)
*/
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
#else
int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
#endif
{
return fp_exptmod(G, X, P, Y);
}
int mp_exptmod_ex (mp_int * G, mp_int * X, int digits, mp_int * P, mp_int * Y)
{
return fp_exptmod_ex(G, X, digits, P, Y);
}
/* compare two ints (signed)*/
int mp_cmp (mp_int * a, mp_int * b)
{
return fp_cmp(a, b);
}
/* compare a digit */
int mp_cmp_d(mp_int * a, mp_digit b)
{
return fp_cmp_d(a, b);
}
/* get the size for an unsigned equivalent */
int mp_unsigned_bin_size (mp_int * a)
{
return fp_unsigned_bin_size(a);
}
int mp_to_unsigned_bin_at_pos(int x, fp_int *t, unsigned char *b)
{
return fp_to_unsigned_bin_at_pos(x, t, b);
}
/* store in unsigned [big endian] format */
int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
{
return fp_to_unsigned_bin(a,b);
}
int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c)
{
return fp_to_unsigned_bin_len(a, b, c);
}
/* reads a unsigned char array, assumes the msb is stored first [big endian] */
int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
{
fp_read_unsigned_bin(a, b, c);
return MP_OKAY;
}
int mp_sub_d(fp_int *a, fp_digit b, fp_int *c)
{
return fp_sub_d(a, b, c);
}
int mp_mul_2d(fp_int *a, int b, fp_int *c)
{
fp_mul_2d(a, b, c);
return MP_OKAY;
}
int mp_2expt(fp_int* a, int b)
{
fp_2expt(a, b);
return MP_OKAY;
}
int mp_div(fp_int * a, fp_int * b, fp_int * c, fp_int * d)
{
return fp_div(a, b, c, d);
}
int mp_div_2d(fp_int* a, int b, fp_int* c, fp_int* d)
{
fp_div_2d(a, b, c, d);
return MP_OKAY;
}
void fp_copy(fp_int *a, fp_int *b)
{
/* if source and destination are different */
if (a != b) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
/* verify a will fit in b */
if (b->size >= a->used) {
int x, oldused;
oldused = b->used;
b->used = a->used;
b->sign = a->sign;
XMEMCPY(b->dp, a->dp, a->used * sizeof(fp_digit));
/* zero any excess digits on the destination that we didn't write to */
for (x = b->used; x >= 0 && x < oldused; x++) {
b->dp[x] = 0;
}
}
else {
/* TODO: Handle error case */
}
#else
/* all dp's are same size, so do straight copy */
b->used = a->used;
b->sign = a->sign;
XMEMCPY(b->dp, a->dp, FP_SIZE * sizeof(fp_digit));
#endif
}
}
void fp_init_copy(fp_int *a, fp_int* b)
{
if (a != b) {
fp_init(a);
fp_copy(b, a);
}
}
/* fast math wrappers */
int mp_copy(fp_int* a, fp_int* b)
{
fp_copy(a, b);
return MP_OKAY;
}
int mp_isodd(mp_int* a)
{
return fp_isodd(a);
}
int mp_iszero(mp_int* a)
{
return fp_iszero(a);
}
int mp_count_bits (mp_int* a)
{
return fp_count_bits(a);
}
int mp_leading_bit (mp_int* a)
{
return fp_leading_bit(a);
}
void mp_rshb (mp_int* a, int x)
{
fp_rshb(a, x);
}
void mp_rshd (mp_int* a, int x)
{
fp_rshd(a, x);
}
int mp_set_int(mp_int *a, unsigned long b)
{
fp_set_int(a, b);
return MP_OKAY;
}
int mp_is_bit_set (mp_int *a, mp_digit b)
{
return fp_is_bit_set(a, b);
}
int mp_set_bit(mp_int *a, mp_digit b)
{
return fp_set_bit(a, b);
}
#if defined(WOLFSSL_KEY_GEN) || defined (HAVE_ECC) || !defined(NO_DH) || \
!defined(NO_DSA) || !defined(NO_RSA)
/* c = a * a (mod b) */
int fp_sqrmod(fp_int *a, fp_int *b, fp_int *c)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_sqr(a, t);
if (err == FP_OKAY) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (c->size < FP_SIZE) {
err = fp_mod(t, b, t);
fp_copy(t, c);
}
else
#endif
{
err = fp_mod(t, b, c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* fast math conversion */
int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c)
{
return fp_sqrmod(a, b, c);
}
/* fast math conversion */
int mp_montgomery_calc_normalization(mp_int *a, mp_int *b)
{
fp_montgomery_calc_normalization(a, b);
return MP_OKAY;
}
#endif /* WOLFSSL_KEYGEN || HAVE_ECC */
#if defined(WC_MP_TO_RADIX) || !defined(NO_DH) || !defined(NO_DSA) || \
!defined(NO_RSA)
#ifdef WOLFSSL_KEY_GEN
/* swap the elements of two integers, for cases where you can't simply swap the
* mp_int pointers around
*/
static int fp_exch (fp_int * a, fp_int * b)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
*t = *a;
*a = *b;
*b = *t;
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
static const int lnz[16] = {
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
};
/* Counts the number of lsbs which are zero before the first zero bit */
int fp_cnt_lsb(fp_int *a)
{
int x;
fp_digit q, qq;
/* easy out */
if (fp_iszero(a) == FP_YES) {
return 0;
}
/* scan lower digits until non-zero */
for (x = 0; x < a->used && a->dp[x] == 0; x++) {}
q = a->dp[x];
x *= DIGIT_BIT;
/* now scan this digit until a 1 is found */
if ((q & 1) == 0) {
do {
qq = q & 15;
x += lnz[qq];
q >>= 4;
} while (qq == 0);
}
return x;
}
static int s_is_power_of_two(fp_digit b, int *p)
{
int x;
/* fast return if no power of two */
if ((b==0) || (b & (b-1))) {
return FP_NO;
}
for (x = 0; x < DIGIT_BIT; x++) {
if (b == (((fp_digit)1)<<x)) {
*p = x;
return FP_YES;
}
}
return FP_NO;
}
/* a/b => cb + d == a */
static int fp_div_d(fp_int *a, fp_digit b, fp_int *c, fp_digit *d)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int q[1];
#else
fp_int *q;
#endif
fp_word w;
fp_digit t;
int ix;
/* cannot divide by zero */
if (b == 0) {
return FP_VAL;
}
/* quick outs */
if (b == 1 || fp_iszero(a) == FP_YES) {
if (d != NULL) {
*d = 0;
}
if (c != NULL) {
fp_copy(a, c);
}
return FP_OKAY;
}
/* power of two ? */
if (s_is_power_of_two(b, &ix) == FP_YES) {
if (d != NULL) {
*d = a->dp[0] & ((((fp_digit)1)<<ix) - 1);
}
if (c != NULL) {
fp_div_2d(a, ix, c, NULL);
}
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
q = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (q == NULL)
return FP_MEM;
#endif
fp_init(q);
if (c != NULL) {
q->used = a->used;
q->sign = a->sign;
}
w = 0;
for (ix = a->used - 1; ix >= 0; ix--) {
w = (w << ((fp_word)DIGIT_BIT)) | ((fp_word)a->dp[ix]);
if (w >= b) {
t = (fp_digit)(w / b);
w -= ((fp_word)t) * ((fp_word)b);
} else {
t = 0;
}
if (c != NULL)
q->dp[ix] = (fp_digit)t;
}
if (d != NULL) {
*d = (fp_digit)w;
}
if (c != NULL) {
fp_clamp(q);
fp_copy(q, c);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(q, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* c = a mod b, 0 <= c < b */
static int fp_mod_d(fp_int *a, fp_digit b, fp_digit *c)
{
return fp_div_d(a, b, NULL, c);
}
int mp_mod_d(fp_int *a, fp_digit b, fp_digit *c)
{
return fp_mod_d(a, b, c);
}
#endif /* WC_MP_TO_RADIX || !NO_DH || !NO_DSA || !NO_RSA */
#if !defined(NO_DH) || !defined(NO_DSA) || !defined(NO_RSA) || \
defined(WOLFSSL_KEY_GEN)
static int fp_isprime_ex(fp_int *a, int t, int* result);
int mp_prime_is_prime(mp_int* a, int t, int* result)
{
return fp_isprime_ex(a, t, result);
}
/* Miller-Rabin test of "a" to the base of "b" as described in
* HAC pp. 139 Algorithm 4.24
*
* Sets result to 0 if definitely composite or 1 if probably prime.
* Randomly the chance of error is no more than 1/4 and often
* very much lower.
*/
static int fp_prime_miller_rabin_ex(fp_int * a, fp_int * b, int *result,
fp_int *n1, fp_int *y, fp_int *r)
{
int s, j;
int err;
/* default */
*result = FP_NO;
/* ensure b > 1 */
if (fp_cmp_d(b, 1) != FP_GT) {
return FP_OKAY;
}
/* get n1 = a - 1 */
fp_copy(a, n1);
err = fp_sub_d(n1, 1, n1);
if (err != FP_OKAY) {
return err;
}
/* set 2**s * r = n1 */
fp_copy(n1, r);
/* count the number of least significant bits
* which are zero
*/
s = fp_cnt_lsb(r);
/* now divide n - 1 by 2**s */
fp_div_2d (r, s, r, NULL);
/* compute y = b**r mod a */
fp_zero(y);
#if (defined(WOLFSSL_HAVE_SP_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || \
defined(WOLFSSL_HAVE_SP_DH)
#ifndef WOLFSSL_SP_NO_2048
if (fp_count_bits(a) == 1024)
sp_ModExp_1024(b, r, a, y);
else if (fp_count_bits(a) == 2048)
sp_ModExp_2048(b, r, a, y);
else
#endif
#ifndef WOLFSSL_SP_NO_3072
if (fp_count_bits(a) == 1536)
sp_ModExp_1536(b, r, a, y);
else if (fp_count_bits(a) == 3072)
sp_ModExp_3072(b, r, a, y);
else
#endif
#ifdef WOLFSSL_SP_4096
if (fp_count_bits(a) == 4096)
sp_ModExp_4096(b, r, a, y);
else
#endif
#endif
fp_exptmod(b, r, a, y);
/* if y != 1 and y != n1 do */
if (fp_cmp_d (y, 1) != FP_EQ && fp_cmp (y, n1) != FP_EQ) {
j = 1;
/* while j <= s-1 and y != n1 */
while ((j <= (s - 1)) && fp_cmp (y, n1) != FP_EQ) {
fp_sqrmod (y, a, y);
/* if y == 1 then composite */
if (fp_cmp_d (y, 1) == FP_EQ) {
return FP_OKAY;
}
++j;
}
/* if y != n1 then composite */
if (fp_cmp (y, n1) != FP_EQ) {
return FP_OKAY;
}
}
/* probably prime now */
*result = FP_YES;
return FP_OKAY;
}
static int fp_prime_miller_rabin(fp_int * a, fp_int * b, int *result)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int n1[1], y[1], r[1];
#else
fp_int *n1, *y, *r;
#endif
#ifdef WOLFSSL_SMALL_STACK
n1 = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
if (n1 == NULL) {
return FP_MEM;
}
y = &n1[1]; r = &n1[2];
#endif
fp_init(n1);
fp_init(y);
fp_init(r);
err = fp_prime_miller_rabin_ex(a, b, result, n1, y, r);
fp_clear(n1);
fp_clear(y);
fp_clear(r);
#ifdef WOLFSSL_SMALL_STACK
XFREE(n1, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* a few primes */
static const fp_digit primes[FP_PRIME_SIZE] = {
0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F, 0x0083,
0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
};
int fp_isprime_ex(fp_int *a, int t, int* result)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int b[1];
#else
fp_int *b;
#endif
fp_digit d;
int r, res;
if (t <= 0 || t > FP_PRIME_SIZE) {
*result = FP_NO;
return FP_VAL;
}
if (fp_isone(a)) {
*result = FP_NO;
return FP_OKAY;
}
/* check against primes table */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_cmp_d(a, primes[r]) == FP_EQ) {
*result = FP_YES;
return FP_OKAY;
}
}
/* do trial division */
for (r = 0; r < FP_PRIME_SIZE; r++) {
res = fp_mod_d(a, primes[r], &d);
if (res != MP_OKAY || d == 0) {
*result = FP_NO;
return FP_OKAY;
}
}
#ifdef WOLFSSL_SMALL_STACK
b = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (b == NULL)
return FP_MEM;
#endif
/* now do 't' miller rabins */
fp_init(b);
for (r = 0; r < t; r++) {
fp_set(b, primes[r]);
fp_prime_miller_rabin(a, b, &res);
if (res == FP_NO) {
*result = FP_NO;
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
}
*result = FP_YES;
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int mp_prime_is_prime_ex(mp_int* a, int t, int* result, WC_RNG* rng)
{
int ret = FP_YES;
if (a == NULL || result == NULL || rng == NULL)
return FP_VAL;
if (fp_isone(a)) {
*result = FP_NO;
return FP_OKAY;
}
if (ret == FP_YES) {
fp_digit d;
int r;
/* check against primes table */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_cmp_d(a, primes[r]) == FP_EQ) {
*result = FP_YES;
return FP_OKAY;
}
}
/* do trial division */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_mod_d(a, primes[r], &d) == MP_OKAY) {
if (d == 0) {
*result = FP_NO;
return FP_OKAY;
}
}
else
return FP_VAL;
}
}
#ifndef WC_NO_RNG
/* now do a miller rabin with up to t random numbers, this should
* give a (1/4)^t chance of a false prime. */
if (ret == FP_YES) {
#ifndef WOLFSSL_SMALL_STACK
fp_int b[1], c[1], n1[1], y[1], r[1];
byte base[FP_MAX_PRIME_SIZE];
#else
fp_int *b, *c, *n1, *y, *r;
byte* base;
#endif
word32 baseSz;
int err;
baseSz = fp_count_bits(a);
/* The base size is the number of bits / 8. One is added if the number
* of bits isn't an even 8. */
baseSz = (baseSz / 8) + ((baseSz % 8) ? 1 : 0);
#ifndef WOLFSSL_SMALL_STACK
if (baseSz > sizeof(base))
return FP_MEM;
#else
base = (byte*)XMALLOC(baseSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (base == NULL)
return FP_MEM;
b = (fp_int*)XMALLOC(sizeof(fp_int) * 5, NULL, DYNAMIC_TYPE_BIGINT);
if (b == NULL) {
return FP_MEM;
}
c = &b[1]; n1 = &b[2]; y= &b[3]; r = &b[4];
#endif
fp_init(b);
fp_init(c);
fp_init(n1);
fp_init(y);
fp_init(r);
err = fp_sub_d(a, 2, c);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
while (t > 0) {
if ((err = wc_RNG_GenerateBlock(rng, base, baseSz)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
fp_read_unsigned_bin(b, base, baseSz);
if (fp_cmp_d(b, 2) != FP_GT || fp_cmp(b, c) != FP_LT) {
continue;
}
fp_prime_miller_rabin_ex(a, b, &ret, n1, y, r);
if (ret == FP_NO)
break;
fp_zero(b);
t--;
}
fp_clear(n1);
fp_clear(y);
fp_clear(r);
fp_clear(b);
fp_clear(c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
}
#else
(void)t;
#endif /* !WC_NO_RNG */
*result = ret;
return FP_OKAY;
}
#endif /* !NO_RSA || !NO_DSA || !NO_DH || WOLFSSL_KEY_GEN */
#ifdef WOLFSSL_KEY_GEN
static int fp_gcd(fp_int *a, fp_int *b, fp_int *c);
static int fp_lcm(fp_int *a, fp_int *b, fp_int *c);
static int fp_randprime(fp_int* N, int len, WC_RNG* rng, void* heap);
int mp_gcd(fp_int *a, fp_int *b, fp_int *c)
{
return fp_gcd(a, b, c);
}
int mp_lcm(fp_int *a, fp_int *b, fp_int *c)
{
return fp_lcm(a, b, c);
}
int mp_rand_prime(mp_int* N, int len, WC_RNG* rng, void* heap)
{
int err;
err = fp_randprime(N, len, rng, heap);
switch(err) {
case FP_VAL:
return MP_VAL;
case FP_MEM:
return MP_MEM;
default:
break;
}
return MP_OKAY;
}
int mp_exch (mp_int * a, mp_int * b)
{
return fp_exch(a, b);
}
int fp_randprime(fp_int* N, int len, WC_RNG* rng, void* heap)
{
static const int USE_BBS = 1;
int err, type;
int isPrime = FP_YES;
/* Assume the candidate is probably prime and then test until
* it is proven composite. */
byte* buf;
(void)heap;
/* get type */
if (len < 0) {
type = USE_BBS;
len = -len;
} else {
type = 0;
}
/* allow sizes between 2 and 512 bytes for a prime size */
if (len < 2 || len > 512) {
return FP_VAL;
}
/* allocate buffer to work with */
buf = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_TMP_BUFFER);
if (buf == NULL) {
return FP_MEM;
}
XMEMSET(buf, 0, len);
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, len);
if (err != 0) {
XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
return FP_VAL;
}
/* munge bits */
buf[0] |= 0x80 | 0x40;
buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00);
/* load value */
fp_read_unsigned_bin(N, buf, len);
/* test */
/* Running Miller-Rabin up to 3 times gives us a 2^{-80} chance
* of a 1024-bit candidate being a false positive, when it is our
* prime candidate. (Note 4.49 of Handbook of Applied Cryptography.)
* Using 8 because we've always used 8 */
mp_prime_is_prime_ex(N, 8, &isPrime, rng);
} while (isPrime == FP_NO);
XMEMSET(buf, 0, len);
XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
return FP_OKAY;
}
/* c = [a, b] */
int fp_lcm(fp_int *a, fp_int *b, fp_int *c)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[2];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL) {
return FP_MEM;
}
#endif
fp_init(&t[0]);
fp_init(&t[1]);
err = fp_gcd(a, b, &t[0]);
if (err == FP_OKAY) {
if (fp_cmp_mag(a, b) == FP_GT) {
err = fp_div(a, &t[0], &t[1], NULL);
if (err == FP_OKAY)
err = fp_mul(b, &t[1], c);
} else {
err = fp_div(b, &t[0], &t[1], NULL);
if (err == FP_OKAY)
err = fp_mul(a, &t[1], c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* c = (a, b) */
int fp_gcd(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int u[1], v[1], r[1];
#else
fp_int *u, *v, *r;
#endif
/* either zero than gcd is the largest */
if (fp_iszero (a) == FP_YES && fp_iszero (b) == FP_NO) {
fp_abs (b, c);
return FP_OKAY;
}
if (fp_iszero (a) == FP_NO && fp_iszero (b) == FP_YES) {
fp_abs (a, c);
return FP_OKAY;
}
/* optimized. At this point if a == 0 then
* b must equal zero too
*/
if (fp_iszero (a) == FP_YES) {
fp_zero(c);
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
u = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
if (u == NULL) {
return FP_MEM;
}
v = &u[1]; r = &u[2];
#endif
/* sort inputs */
if (fp_cmp_mag(a, b) != FP_LT) {
fp_init_copy(u, a);
fp_init_copy(v, b);
} else {
fp_init_copy(u, b);
fp_init_copy(v, a);
}
u->sign = FP_ZPOS;
v->sign = FP_ZPOS;
fp_init(r);
while (fp_iszero(v) == FP_NO) {
fp_mod(u, v, r);
fp_copy(v, u);
fp_copy(r, v);
}
fp_copy(u, c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(u, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif /* WOLFSSL_KEY_GEN */
#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(OPENSSL_EXTRA) || \
defined(WC_RSA_BLINDING) || !defined(NO_DSA) || \
(!defined(NO_RSA) && !defined(NO_RSA_BOUNDS_CHECK))
/* c = a + b */
void fp_add_d(fp_int *a, fp_digit b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp;
fp_init(&tmp);
fp_set(&tmp, b);
fp_add(a, &tmp, c);
#else
int i;
fp_word t = b;
fp_copy(a, c);
for (i = 0; t != 0 && i < FP_SIZE && i < c->used; i++) {
t += c->dp[i];
c->dp[i] = (fp_digit)t;
t >>= DIGIT_BIT;
}
if (i == c->used && i < FP_SIZE && t != 0) {
c->dp[i] = t;
c->used++;
}
#endif
}
/* external compatibility */
int mp_add_d(fp_int *a, fp_digit b, fp_int *c)
{
fp_add_d(a, b, c);
return MP_OKAY;
}
#endif /* HAVE_ECC || !NO_PWDBASED || OPENSSL_EXTRA || WC_RSA_BLINDING ||
!NO_DSA || (!NO_RSA && !NO_RSA_BOUNDS_CHECK) */
#if !defined(NO_DSA) || defined(HAVE_ECC) || defined(WOLFSSL_KEY_GEN) || \
defined(HAVE_COMP_KEY) || defined(WOLFSSL_DEBUG_MATH) || \
defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA) || defined(WC_MP_TO_RADIX)
/* chars used in radix conversions */
static const char* const fp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz+/";
#endif
#if !defined(NO_DSA) || defined(HAVE_ECC)
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
static int fp_read_radix_16(fp_int *a, const char *str)
{
int i, j, k, neg;
char ch;
/* if the leading digit is a
* minus set the sign to negative.
*/
if (*str == '-') {
++str;
neg = FP_NEG;
} else {
neg = FP_ZPOS;
}
j = 0;
k = 0;
for (i = (int)(XSTRLEN(str) - 1); i >= 0; i--) {
ch = str[i];
if (ch >= '0' && ch <= '9')
ch -= '0';
else if (ch >= 'A' && ch <= 'F')
ch -= 'A' - 10;
else if (ch >= 'a' && ch <= 'f')
ch -= 'a' - 10;
else
return FP_VAL;
a->dp[k] |= ((fp_digit)ch) << j;
j += 4;
k += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
a->used = k + 1;
fp_clamp(a);
/* set the sign only if a != 0 */
if (fp_iszero(a) != FP_YES) {
a->sign = neg;
}
return FP_OKAY;
}
#endif
static int fp_read_radix(fp_int *a, const char *str, int radix)
{
int y, neg;
char ch;
/* set the integer to the default of zero */
fp_zero (a);
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
if (radix == 16)
return fp_read_radix_16(a, str);
#endif
/* make sure the radix is ok */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
/* if the leading digit is a
* minus set the sign to negative.
*/
if (*str == '-') {
++str;
neg = FP_NEG;
} else {
neg = FP_ZPOS;
}
/* process each digit of the string */
while (*str) {
/* if the radix <= 36 the conversion is case insensitive
* this allows numbers like 1AB and 1ab to represent the same value
* [e.g. in hex]
*/
ch = (char)((radix <= 36) ? XTOUPPER((unsigned char)*str) : *str);
for (y = 0; y < 64; y++) {
if (ch == fp_s_rmap[y]) {
break;
}
}
/* if the char was found in the map
* and is less than the given radix add it
* to the number, otherwise exit the loop.
*/
if (y < radix) {
fp_mul_d (a, (fp_digit) radix, a);
fp_add_d (a, (fp_digit) y, a);
} else {
break;
}
++str;
}
/* set the sign only if a != 0 */
if (fp_iszero(a) != FP_YES) {
a->sign = neg;
}
return FP_OKAY;
}
/* fast math conversion */
int mp_read_radix(mp_int *a, const char *str, int radix)
{
return fp_read_radix(a, str, radix);
}
#endif /* !defined(NO_DSA) || defined(HAVE_ECC) */
#ifdef HAVE_ECC
/* fast math conversion */
int mp_sqr(fp_int *A, fp_int *B)
{
return fp_sqr(A, B);
}
/* fast math conversion */
int mp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp)
{
return fp_montgomery_reduce(a, m, mp);
}
/* fast math conversion */
int mp_montgomery_setup(fp_int *a, fp_digit *rho)
{
return fp_montgomery_setup(a, rho);
}
int mp_div_2(fp_int * a, fp_int * b)
{
fp_div_2(a, b);
return MP_OKAY;
}
int mp_init_copy(fp_int * a, fp_int * b)
{
fp_init_copy(a, b);
return MP_OKAY;
}
#ifdef HAVE_COMP_KEY
int mp_cnt_lsb(fp_int* a)
{
return fp_cnt_lsb(a);
}
#endif /* HAVE_COMP_KEY */
#endif /* HAVE_ECC */
#if defined(HAVE_ECC) || !defined(NO_RSA) || !defined(NO_DSA) || \
defined(WOLFSSL_KEY_GEN)
/* fast math conversion */
int mp_set(fp_int *a, fp_digit b)
{
fp_set(a,b);
return MP_OKAY;
}
#endif
#ifdef WC_MP_TO_RADIX
/* returns size of ASCII representation */
int mp_radix_size (mp_int *a, int radix, int *size)
{
int res, digs;
fp_digit d;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
*size = 0;
/* special case for binary */
if (radix == 2) {
*size = fp_count_bits (a) + (a->sign == FP_NEG ? 1 : 0) + 1;
return FP_YES;
}
/* make sure the radix is in range */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
if (fp_iszero(a) == MP_YES) {
*size = 2;
return FP_OKAY;
}
/* digs is the digit count */
digs = 0;
/* if it's negative add one for the sign */
if (a->sign == FP_NEG) {
++digs;
}
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
/* init a copy of the input */
fp_init_copy (t, a);
/* force temp to positive */
t->sign = FP_ZPOS;
/* fetch out all of the digits */
while (fp_iszero (t) == FP_NO) {
if ((res = fp_div_d (t, (mp_digit) radix, t, &d)) != FP_OKAY) {
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return res;
}
++digs;
}
fp_zero (t);
/* return digs + 1, the 1 is for the NULL byte that would be required. */
*size = digs + 1;
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* stores a bignum as a ASCII string in a given radix (2..64) */
int mp_toradix (mp_int *a, char *str, int radix)
{
int res, digs;
fp_digit d;
char *_s = str;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
/* check range of the radix */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
/* quick out if its zero */
if (fp_iszero(a) == FP_YES) {
*str++ = '0';
*str = '\0';
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
/* init a copy of the input */
fp_init_copy (t, a);
/* if it is negative output a - */
if (t->sign == FP_NEG) {
++_s;
*str++ = '-';
t->sign = FP_ZPOS;
}
digs = 0;
while (fp_iszero (t) == FP_NO) {
if ((res = fp_div_d (t, (fp_digit) radix, t, &d)) != FP_OKAY) {
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return res;
}
*str++ = fp_s_rmap[d];
++digs;
}
#ifndef WC_DISABLE_RADIX_ZERO_PAD
/* For hexadecimal output, add zero padding when number of digits is odd */
if ((digs & 1) && (radix == 16)) {
*str++ = fp_s_rmap[0];
++digs;
}
#endif
/* reverse the digits of the string. In this case _s points
* to the first digit [excluding the sign] of the number]
*/
fp_reverse ((unsigned char *)_s, digs);
/* append a NULL so the string is properly terminated */
*str = '\0';
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#ifdef WOLFSSL_DEBUG_MATH
void mp_dump(const char* desc, mp_int* a, byte verbose)
{
char buffer[FP_SIZE * sizeof(fp_digit) * 2];
int size;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
printf("%s: ptr=%p, used=%d, sign=%d, size=%d, fpd=%d\n",
desc, a, a->used, a->sign, size, (int)sizeof(fp_digit));
mp_tohex(a, buffer);
printf(" %s\n ", buffer);
if (verbose) {
int i;
for(i=0; i<size * (int)sizeof(fp_digit); i++) {
printf("%x ", *(((byte*)a->dp) + i));
}
printf("\n");
}
}
#endif /* WOLFSSL_DEBUG_MATH */
#endif /* WC_MP_TO_RADIX */
int mp_abs(mp_int* a, mp_int* b)
{
fp_abs(a, b);
return FP_OKAY;
}
int mp_lshd (mp_int * a, int b)
{
fp_lshd(a, b);
return FP_OKAY;
}
#endif /* USE_FAST_MATH */
| ./CrossVul/dataset_final_sorted/CWE-326/c/bad_3970_1 |
crossvul-cpp_data_bad_3970_0 | /* ecc.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* in case user set HAVE_ECC there */
#include <wolfssl/wolfcrypt/settings.h>
/* public ASN interface */
#include <wolfssl/wolfcrypt/asn_public.h>
/*
Possible ECC enable options:
* HAVE_ECC: Overall control of ECC default: on
* HAVE_ECC_ENCRYPT: ECC encrypt/decrypt w/AES and HKDF default: off
* HAVE_ECC_SIGN: ECC sign default: on
* HAVE_ECC_VERIFY: ECC verify default: on
* HAVE_ECC_DHE: ECC build shared secret default: on
* HAVE_ECC_CDH: ECC cofactor DH shared secret default: off
* HAVE_ECC_KEY_IMPORT: ECC Key import default: on
* HAVE_ECC_KEY_EXPORT: ECC Key export default: on
* ECC_SHAMIR: Enables Shamir calc method default: on
* HAVE_COMP_KEY: Enables compressed key default: off
* WOLFSSL_VALIDATE_ECC_IMPORT: Validate ECC key on import default: off
* WOLFSSL_VALIDATE_ECC_KEYGEN: Validate ECC key gen default: off
* WOLFSSL_CUSTOM_CURVES: Allow non-standard curves. default: off
* Includes the curve "a" variable in calculation
* ECC_DUMP_OID: Enables dump of OID encoding and sum default: off
* ECC_CACHE_CURVE: Enables cache of curve info to improve perofrmance
default: off
* FP_ECC: ECC Fixed Point Cache default: off
* USE_ECC_B_PARAM: Enable ECC curve B param default: off
(on for HAVE_COMP_KEY)
* WOLFSSL_ECC_CURVE_STATIC: default off (on for windows)
For the ECC curve paramaters `ecc_set_type` use fixed
array for hex string
*/
/*
ECC Curve Types:
* NO_ECC_SECP Disables SECP curves default: off (not defined)
* HAVE_ECC_SECPR2 Enables SECP R2 curves default: off
* HAVE_ECC_SECPR3 Enables SECP R3 curves default: off
* HAVE_ECC_BRAINPOOL Enables Brainpool curves default: off
* HAVE_ECC_KOBLITZ Enables Koblitz curves default: off
*/
/*
ECC Curve Sizes:
* ECC_USER_CURVES: Allows custom combination of key sizes below
* HAVE_ALL_CURVES: Enable all key sizes (on unless ECC_USER_CURVES is defined)
* HAVE_ECC112: 112 bit key
* HAVE_ECC128: 128 bit key
* HAVE_ECC160: 160 bit key
* HAVE_ECC192: 192 bit key
* HAVE_ECC224: 224 bit key
* HAVE_ECC239: 239 bit key
* NO_ECC256: Disables 256 bit key (on by default)
* HAVE_ECC320: 320 bit key
* HAVE_ECC384: 384 bit key
* HAVE_ECC512: 512 bit key
* HAVE_ECC521: 521 bit key
*/
#ifdef HAVE_ECC
/* Make sure custom curves is enabled for Brainpool or Koblitz curve types */
#if (defined(HAVE_ECC_BRAINPOOL) || defined(HAVE_ECC_KOBLITZ)) &&\
!defined(WOLFSSL_CUSTOM_CURVES)
#error Brainpool and Koblitz curves requires WOLFSSL_CUSTOM_CURVES
#endif
#if defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
/* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
#define FIPS_NO_WRAPPERS
#ifdef USE_WINDOWS_API
#pragma code_seg(".fipsA$f")
#pragma const_seg(".fipsB$f")
#endif
#endif
#include <wolfssl/wolfcrypt/ecc.h>
#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/logging.h>
#include <wolfssl/wolfcrypt/types.h>
#ifdef WOLFSSL_HAVE_SP_ECC
#include <wolfssl/wolfcrypt/sp.h>
#endif
#ifdef HAVE_ECC_ENCRYPT
#include <wolfssl/wolfcrypt/hmac.h>
#include <wolfssl/wolfcrypt/aes.h>
#endif
#ifdef HAVE_X963_KDF
#include <wolfssl/wolfcrypt/hash.h>
#endif
#ifdef WOLF_CRYPTO_CB
#include <wolfssl/wolfcrypt/cryptocb.h>
#endif
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#if defined(FREESCALE_LTC_ECC)
#include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
#endif
#if defined(WOLFSSL_STM32_PKA)
#include <wolfssl/wolfcrypt/port/st/stm32.h>
#endif
#ifdef WOLFSSL_SP_MATH
#define GEN_MEM_ERR MP_MEM
#elif defined(USE_FAST_MATH)
#define GEN_MEM_ERR FP_MEM
#else
#define GEN_MEM_ERR MP_MEM
#endif
/* internal ECC states */
enum {
ECC_STATE_NONE = 0,
ECC_STATE_SHARED_SEC_GEN,
ECC_STATE_SHARED_SEC_RES,
ECC_STATE_SIGN_DO,
ECC_STATE_SIGN_ENCODE,
ECC_STATE_VERIFY_DECODE,
ECC_STATE_VERIFY_DO,
ECC_STATE_VERIFY_RES,
};
/* map
ptmul -> mulmod
*/
/* 256-bit curve on by default whether user curves or not */
#if defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES)
#define ECC112
#endif
#if defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES)
#define ECC128
#endif
#if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES)
#define ECC160
#endif
#if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES)
#define ECC192
#endif
#if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)
#define ECC224
#endif
#if defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES)
#define ECC239
#endif
#if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES)
#define ECC256
#endif
#if defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES)
#define ECC320
#endif
#if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES)
#define ECC384
#endif
#if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES)
#define ECC512
#endif
#if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES)
#define ECC521
#endif
/* The encoded OID's for ECC curves */
#ifdef ECC112
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP112R1 {1,3,132,0,6}
#define CODED_SECP112R1_SZ 5
#else
#define CODED_SECP112R1 {0x2B,0x81,0x04,0x00,0x06}
#define CODED_SECP112R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp112r1[] = CODED_SECP112R1;
#else
#define ecc_oid_secp112r1 CODED_SECP112R1
#endif
#define ecc_oid_secp112r1_sz CODED_SECP112R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP112R2 {1,3,132,0,7}
#define CODED_SECP112R2_SZ 5
#else
#define CODED_SECP112R2 {0x2B,0x81,0x04,0x00,0x07}
#define CODED_SECP112R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp112r2[] = CODED_SECP112R2;
#else
#define ecc_oid_secp112r2 CODED_SECP112R2
#endif
#define ecc_oid_secp112r2_sz CODED_SECP112R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC112 */
#ifdef ECC128
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP128R1 {1,3,132,0,28}
#define CODED_SECP128R1_SZ 5
#else
#define CODED_SECP128R1 {0x2B,0x81,0x04,0x00,0x1C}
#define CODED_SECP128R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp128r1[] = CODED_SECP128R1;
#else
#define ecc_oid_secp128r1 CODED_SECP128R1
#endif
#define ecc_oid_secp128r1_sz CODED_SECP128R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP128R2 {1,3,132,0,29}
#define CODED_SECP128R2_SZ 5
#else
#define CODED_SECP128R2 {0x2B,0x81,0x04,0x00,0x1D}
#define CODED_SECP128R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp128r2[] = CODED_SECP128R2;
#else
#define ecc_oid_secp128r2 CODED_SECP128R2
#endif
#define ecc_oid_secp128r2_sz CODED_SECP128R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC128 */
#ifdef ECC160
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160R1 {1,3,132,0,8}
#define CODED_SECP160R1_SZ 5
#else
#define CODED_SECP160R1 {0x2B,0x81,0x04,0x00,0x08}
#define CODED_SECP160R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160r1[] = CODED_SECP160R1;
#else
#define ecc_oid_secp160r1 CODED_SECP160R1
#endif
#define ecc_oid_secp160r1_sz CODED_SECP160R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160R2 {1,3,132,0,30}
#define CODED_SECP160R2_SZ 5
#else
#define CODED_SECP160R2 {0x2B,0x81,0x04,0x00,0x1E}
#define CODED_SECP160R2_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160r2[] = CODED_SECP160R2;
#else
#define ecc_oid_secp160r2 CODED_SECP160R2
#endif
#define ecc_oid_secp160r2_sz CODED_SECP160R2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP160K1 {1,3,132,0,9}
#define CODED_SECP160K1_SZ 5
#else
#define CODED_SECP160K1 {0x2B,0x81,0x04,0x00,0x09}
#define CODED_SECP160K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp160k1[] = CODED_SECP160K1;
#else
#define ecc_oid_secp160k1 CODED_SECP160K1
#endif
#define ecc_oid_secp160k1_sz CODED_SECP160K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP160R1 {1,3,36,3,3,2,8,1,1,1}
#define CODED_BRAINPOOLP160R1_SZ 10
#else
#define CODED_BRAINPOOLP160R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01}
#define CODED_BRAINPOOLP160R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp160r1[] = CODED_BRAINPOOLP160R1;
#else
#define ecc_oid_brainpoolp160r1 CODED_BRAINPOOLP160R1
#endif
#define ecc_oid_brainpoolp160r1_sz CODED_BRAINPOOLP160R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC160 */
#ifdef ECC192
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP192R1 {1,2,840,10045,3,1,1}
#define CODED_SECP192R1_SZ 7
#else
#define CODED_SECP192R1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x01}
#define CODED_SECP192R1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp192r1[] = CODED_SECP192R1;
#else
#define ecc_oid_secp192r1 CODED_SECP192R1
#endif
#define ecc_oid_secp192r1_sz CODED_SECP192R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME192V2 {1,2,840,10045,3,1,2}
#define CODED_PRIME192V2_SZ 7
#else
#define CODED_PRIME192V2 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x02}
#define CODED_PRIME192V2_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime192v2[] = CODED_PRIME192V2;
#else
#define ecc_oid_prime192v2 CODED_PRIME192V2
#endif
#define ecc_oid_prime192v2_sz CODED_PRIME192V2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME192V3 {1,2,840,10045,3,1,3}
#define CODED_PRIME192V3_SZ 7
#else
#define CODED_PRIME192V3 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x03}
#define CODED_PRIME192V3_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime192v3[] = CODED_PRIME192V3;
#else
#define ecc_oid_prime192v3 CODED_PRIME192V3
#endif
#define ecc_oid_prime192v3_sz CODED_PRIME192V3_SZ
#endif /* HAVE_ECC_SECPR3 */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP192K1 {1,3,132,0,31}
#define CODED_SECP192K1_SZ 5
#else
#define CODED_SECP192K1 {0x2B,0x81,0x04,0x00,0x1F}
#define CODED_SECP192K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp192k1[] = CODED_SECP192K1;
#else
#define ecc_oid_secp192k1 CODED_SECP192K1
#endif
#define ecc_oid_secp192k1_sz CODED_SECP192K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP192R1 {1,3,36,3,3,2,8,1,1,3}
#define CODED_BRAINPOOLP192R1_SZ 10
#else
#define CODED_BRAINPOOLP192R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03}
#define CODED_BRAINPOOLP192R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp192r1[] = CODED_BRAINPOOLP192R1;
#else
#define ecc_oid_brainpoolp192r1 CODED_BRAINPOOLP192R1
#endif
#define ecc_oid_brainpoolp192r1_sz CODED_BRAINPOOLP192R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC192 */
#ifdef ECC224
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP224R1 {1,3,132,0,33}
#define CODED_SECP224R1_SZ 5
#else
#define CODED_SECP224R1 {0x2B,0x81,0x04,0x00,0x21}
#define CODED_SECP224R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp224r1[] = CODED_SECP224R1;
#else
#define ecc_oid_secp224r1 CODED_SECP224R1
#endif
#define ecc_oid_secp224r1_sz CODED_SECP224R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP224K1 {1,3,132,0,32}
#define CODED_SECP224K1_SZ 5
#else
#define CODED_SECP224K1 {0x2B,0x81,0x04,0x00,0x20}
#define CODED_SECP224K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp224k1[] = CODED_SECP224K1;
#else
#define ecc_oid_secp224k1 CODED_SECP224K1
#endif
#define ecc_oid_secp224k1_sz CODED_SECP224K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP224R1 {1,3,36,3,3,2,8,1,1,5}
#define CODED_BRAINPOOLP224R1_SZ 10
#else
#define CODED_BRAINPOOLP224R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05}
#define CODED_BRAINPOOLP224R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp224r1[] = CODED_BRAINPOOLP224R1;
#else
#define ecc_oid_brainpoolp224r1 CODED_BRAINPOOLP224R1
#endif
#define ecc_oid_brainpoolp224r1_sz CODED_BRAINPOOLP224R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC224 */
#ifdef ECC239
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V1 {1,2,840,10045,3,1,4}
#define CODED_PRIME239V1_SZ 7
#else
#define CODED_PRIME239V1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x04}
#define CODED_PRIME239V1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v1[] = CODED_PRIME239V1;
#else
#define ecc_oid_prime239v1 CODED_PRIME239V1
#endif
#define ecc_oid_prime239v1_sz CODED_PRIME239V1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V2 {1,2,840,10045,3,1,5}
#define CODED_PRIME239V2_SZ 7
#else
#define CODED_PRIME239V2 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x05}
#define CODED_PRIME239V2_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v2[] = CODED_PRIME239V2;
#else
#define ecc_oid_prime239v2 CODED_PRIME239V2
#endif
#define ecc_oid_prime239v2_sz CODED_PRIME239V2_SZ
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
#ifdef HAVE_OID_ENCODING
#define CODED_PRIME239V3 {1,2,840,10045,3,1,6}
#define CODED_PRIME239V3_SZ 7
#else
#define CODED_PRIME239V3 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x06}
#define CODED_PRIME239V3_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_prime239v3[] = CODED_PRIME239V3;
#else
#define ecc_oid_prime239v3 CODED_PRIME239V3
#endif
#define ecc_oid_prime239v3_sz CODED_PRIME239V3_SZ
#endif /* HAVE_ECC_SECPR3 */
#endif /* ECC239 */
#ifdef ECC256
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP256R1 {1,2,840,10045,3,1,7}
#define CODED_SECP256R1_SZ 7
#else
#define CODED_SECP256R1 {0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07}
#define CODED_SECP256R1_SZ 8
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp256r1[] = CODED_SECP256R1;
#else
#define ecc_oid_secp256r1 CODED_SECP256R1
#endif
#define ecc_oid_secp256r1_sz CODED_SECP256R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
#ifdef HAVE_OID_ENCODING
#define CODED_SECP256K1 {1,3,132,0,10}
#define CODED_SECP256K1_SZ 5
#else
#define CODED_SECP256K1 {0x2B,0x81,0x04,0x00,0x0A}
#define CODED_SECP256K1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp256k1[] = CODED_SECP256K1;
#else
#define ecc_oid_secp256k1 CODED_SECP256K1
#endif
#define ecc_oid_secp256k1_sz CODED_SECP256K1_SZ
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP256R1 {1,3,36,3,3,2,8,1,1,7}
#define CODED_BRAINPOOLP256R1_SZ 10
#else
#define CODED_BRAINPOOLP256R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07}
#define CODED_BRAINPOOLP256R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp256r1[] = CODED_BRAINPOOLP256R1;
#else
#define ecc_oid_brainpoolp256r1 CODED_BRAINPOOLP256R1
#endif
#define ecc_oid_brainpoolp256r1_sz CODED_BRAINPOOLP256R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC256 */
#ifdef ECC320
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP320R1 {1,3,36,3,3,2,8,1,1,9}
#define CODED_BRAINPOOLP320R1_SZ 10
#else
#define CODED_BRAINPOOLP320R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09}
#define CODED_BRAINPOOLP320R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp320r1[] = CODED_BRAINPOOLP320R1;
#else
#define ecc_oid_brainpoolp320r1 CODED_BRAINPOOLP320R1
#endif
#define ecc_oid_brainpoolp320r1_sz CODED_BRAINPOOLP320R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC320 */
#ifdef ECC384
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP384R1 {1,3,132,0,34}
#define CODED_SECP384R1_SZ 5
#else
#define CODED_SECP384R1 {0x2B,0x81,0x04,0x00,0x22}
#define CODED_SECP384R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp384r1[] = CODED_SECP384R1;
#define CODED_SECP384R1_OID ecc_oid_secp384r1
#else
#define ecc_oid_secp384r1 CODED_SECP384R1
#endif
#define ecc_oid_secp384r1_sz CODED_SECP384R1_SZ
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP384R1 {1,3,36,3,3,2,8,1,1,11}
#define CODED_BRAINPOOLP384R1_SZ 10
#else
#define CODED_BRAINPOOLP384R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0B}
#define CODED_BRAINPOOLP384R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp384r1[] = CODED_BRAINPOOLP384R1;
#else
#define ecc_oid_brainpoolp384r1 CODED_BRAINPOOLP384R1
#endif
#define ecc_oid_brainpoolp384r1_sz CODED_BRAINPOOLP384R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC384 */
#ifdef ECC512
#ifdef HAVE_ECC_BRAINPOOL
#ifdef HAVE_OID_ENCODING
#define CODED_BRAINPOOLP512R1 {1,3,36,3,3,2,8,1,1,13}
#define CODED_BRAINPOOLP512R1_SZ 10
#else
#define CODED_BRAINPOOLP512R1 {0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0D}
#define CODED_BRAINPOOLP512R1_SZ 9
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_brainpoolp512r1[] = CODED_BRAINPOOLP512R1;
#else
#define ecc_oid_brainpoolp512r1 CODED_BRAINPOOLP512R1
#endif
#define ecc_oid_brainpoolp512r1_sz CODED_BRAINPOOLP512R1_SZ
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC512 */
#ifdef ECC521
#ifndef NO_ECC_SECP
#ifdef HAVE_OID_ENCODING
#define CODED_SECP521R1 {1,3,132,0,35}
#define CODED_SECP521R1_SZ 5
#else
#define CODED_SECP521R1 {0x2B,0x81,0x04,0x00,0x23}
#define CODED_SECP521R1_SZ 5
#endif
#ifndef WOLFSSL_ECC_CURVE_STATIC
static const ecc_oid_t ecc_oid_secp521r1[] = CODED_SECP521R1;
#else
#define ecc_oid_secp521r1 CODED_SECP521R1
#endif
#define ecc_oid_secp521r1_sz CODED_SECP521R1_SZ
#endif /* !NO_ECC_SECP */
#endif /* ECC521 */
/* This holds the key settings.
***MUST*** be organized by size from smallest to largest. */
const ecc_set_type ecc_sets[] = {
#ifdef ECC112
#ifndef NO_ECC_SECP
{
14, /* size/bytes */
ECC_SECP112R1, /* ID */
"SECP112R1", /* curve name */
"DB7C2ABF62E35E668076BEAD208B", /* prime */
"DB7C2ABF62E35E668076BEAD2088", /* A */
"659EF8BA043916EEDE8911702B22", /* B */
"DB7C2ABF62E35E7628DFAC6561C5", /* order */
"9487239995A5EE76B55F9C2F098", /* Gx */
"A89CE5AF8724C0A23E0E0FF77500", /* Gy */
ecc_oid_secp112r1, /* oid/oidSz */
ecc_oid_secp112r1_sz,
ECC_SECP112R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
14, /* size/bytes */
ECC_SECP112R2, /* ID */
"SECP112R2", /* curve name */
"DB7C2ABF62E35E668076BEAD208B", /* prime */
"6127C24C05F38A0AAAF65C0EF02C", /* A */
"51DEF1815DB5ED74FCC34C85D709", /* B */
"36DF0AAFD8B8D7597CA10520D04B", /* order */
"4BA30AB5E892B4E1649DD0928643", /* Gx */
"ADCD46F5882E3747DEF36E956E97", /* Gy */
ecc_oid_secp112r2, /* oid/oidSz */
ecc_oid_secp112r2_sz,
ECC_SECP112R2_OID, /* oid sum */
4, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC112 */
#ifdef ECC128
#ifndef NO_ECC_SECP
{
16, /* size/bytes */
ECC_SECP128R1, /* ID */
"SECP128R1", /* curve name */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"E87579C11079F43DD824993C2CEE5ED3", /* B */
"FFFFFFFE0000000075A30D1B9038A115", /* order */
"161FF7528B899B2D0C28607CA52C5B86", /* Gx */
"CF5AC8395BAFEB13C02DA292DDED7A83", /* Gy */
ecc_oid_secp128r1, /* oid/oidSz */
ecc_oid_secp128r1_sz,
ECC_SECP128R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
16, /* size/bytes */
ECC_SECP128R2, /* ID */
"SECP128R2", /* curve name */
"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"D6031998D1B3BBFEBF59CC9BBFF9AEE1", /* A */
"5EEEFCA380D02919DC2C6558BB6D8A5D", /* B */
"3FFFFFFF7FFFFFFFBE0024720613B5A3", /* order */
"7B6AA5D85E572983E6FB32A7CDEBC140", /* Gx */
"27B6916A894D3AEE7106FE805FC34B44", /* Gy */
ecc_oid_secp128r2, /* oid/oidSz */
ecc_oid_secp128r2_sz,
ECC_SECP128R2_OID, /* oid sum */
4, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#endif /* ECC128 */
#ifdef ECC160
#ifndef NO_ECC_SECP
{
20, /* size/bytes */
ECC_SECP160R1, /* ID */
"SECP160R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", /* A */
"1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", /* B */
"100000000000000000001F4C8F927AED3CA752257",/* order */
"4A96B5688EF573284664698968C38BB913CBFC82", /* Gx */
"23A628553168947D59DCC912042351377AC5FB32", /* Gy */
ecc_oid_secp160r1, /* oid/oidSz */
ecc_oid_secp160r1_sz,
ECC_SECP160R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
20, /* size/bytes */
ECC_SECP160R2, /* ID */
"SECP160R2", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70", /* A */
"B4E134D3FB59EB8BAB57274904664D5AF50388BA", /* B */
"100000000000000000000351EE786A818F3A1A16B",/* order */
"52DCB034293A117E1F4FF11B30F7199D3144CE6D", /* Gx */
"FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E", /* Gy */
ecc_oid_secp160r2, /* oid/oidSz */
ecc_oid_secp160r2_sz,
ECC_SECP160R2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_KOBLITZ
{
20, /* size/bytes */
ECC_SECP160K1, /* ID */
"SECP160K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */
"0000000000000000000000000000000000000000", /* A */
"0000000000000000000000000000000000000007", /* B */
"100000000000000000001B8FA16DFAB9ACA16B6B3",/* order */
"3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", /* Gx */
"938CF935318FDCED6BC28286531733C3F03C4FEE", /* Gy */
ecc_oid_secp160k1, /* oid/oidSz */
ecc_oid_secp160k1_sz,
ECC_SECP160K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
20, /* size/bytes */
ECC_BRAINPOOLP160R1, /* ID */
"BRAINPOOLP160R1", /* curve name */
"E95E4A5F737059DC60DFC7AD95B3D8139515620F", /* prime */
"340E7BE2A280EB74E2BE61BADA745D97E8F7C300", /* A */
"1E589A8595423412134FAA2DBDEC95C8D8675E58", /* B */
"E95E4A5F737059DC60DF5991D45029409E60FC09", /* order */
"BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC3", /* Gx */
"1667CB477A1A8EC338F94741669C976316DA6321", /* Gy */
ecc_oid_brainpoolp160r1, /* oid/oidSz */
ecc_oid_brainpoolp160r1_sz,
ECC_BRAINPOOLP160R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC160 */
#ifdef ECC192
#ifndef NO_ECC_SECP
{
24, /* size/bytes */
ECC_SECP192R1, /* ID */
"SECP192R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", /* order */
"188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", /* Gx */
"7192B95FFC8DA78631011ED6B24CDD573F977A11E794811", /* Gy */
ecc_oid_secp192r1, /* oid/oidSz */
ecc_oid_secp192r1_sz,
ECC_SECP192R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
24, /* size/bytes */
ECC_PRIME192V2, /* ID */
"PRIME192V2", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"CC22D6DFB95C6B25E49C0D6364A4E5980C393AA21668D953", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFE5FB1A724DC80418648D8DD31", /* order */
"EEA2BAE7E1497842F2DE7769CFE9C989C072AD696F48034A", /* Gx */
"6574D11D69B6EC7A672BB82A083DF2F2B0847DE970B2DE15", /* Gy */
ecc_oid_prime192v2, /* oid/oidSz */
ecc_oid_prime192v2_sz,
ECC_PRIME192V2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
{
24, /* size/bytes */
ECC_PRIME192V3, /* ID */
"PRIME192V3", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */
"22123DC2395A05CAA7423DAECCC94760A7D462256BD56916", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFF7A62D031C83F4294F640EC13", /* order */
"7D29778100C65A1DA1783716588DCE2B8B4AEE8E228F1896", /* Gx */
"38A90F22637337334B49DCB66A6DC8F9978ACA7648A943B0", /* Gy */
ecc_oid_prime192v3, /* oid/oidSz */
ecc_oid_prime192v3_sz,
ECC_PRIME192V3_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR3 */
#ifdef HAVE_ECC_KOBLITZ
{
24, /* size/bytes */
ECC_SECP192K1, /* ID */
"SECP192K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", /* prime */
"000000000000000000000000000000000000000000000000", /* A */
"000000000000000000000000000000000000000000000003", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", /* order */
"DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", /* Gx */
"9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", /* Gy */
ecc_oid_secp192k1, /* oid/oidSz */
ecc_oid_secp192k1_sz,
ECC_SECP192K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
24, /* size/bytes */
ECC_BRAINPOOLP192R1, /* ID */
"BRAINPOOLP192R1", /* curve name */
"C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", /* prime */
"6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", /* A */
"469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", /* B */
"C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", /* order */
"C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD6", /* Gx */
"14B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F", /* Gy */
ecc_oid_brainpoolp192r1, /* oid/oidSz */
ecc_oid_brainpoolp192r1_sz,
ECC_BRAINPOOLP192R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC192 */
#ifdef ECC224
#ifndef NO_ECC_SECP
{
28, /* size/bytes */
ECC_SECP224R1, /* ID */
"SECP224R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", /* A */
"B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", /* order */
"B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", /* Gx */
"BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", /* Gy */
ecc_oid_secp224r1, /* oid/oidSz */
ecc_oid_secp224r1_sz,
ECC_SECP224R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
{
28, /* size/bytes */
ECC_SECP224K1, /* ID */
"SECP224K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", /* prime */
"00000000000000000000000000000000000000000000000000000000", /* A */
"00000000000000000000000000000000000000000000000000000005", /* B */
"10000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7",/* order */
"A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", /* Gx */
"7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", /* Gy */
ecc_oid_secp224k1, /* oid/oidSz */
ecc_oid_secp224k1_sz,
ECC_SECP224K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
28, /* size/bytes */
ECC_BRAINPOOLP224R1, /* ID */
"BRAINPOOLP224R1", /* curve name */
"D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", /* prime */
"68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", /* A */
"2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", /* B */
"D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", /* order */
"0D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D", /* Gx */
"58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD", /* Gy */
ecc_oid_brainpoolp224r1, /* oid/oidSz */
ecc_oid_brainpoolp224r1_sz,
ECC_BRAINPOOLP224R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC224 */
#ifdef ECC239
#ifndef NO_ECC_SECP
{
30, /* size/bytes */
ECC_PRIME239V1, /* ID */
"PRIME239V1", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"6B016C3BDCF18941D0D654921475CA71A9DB2FB27D1D37796185C2942C0A", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF9E5E9A9F5D9071FBD1522688909D0B", /* order */
"0FFA963CDCA8816CCC33B8642BEDF905C3D358573D3F27FBBD3B3CB9AAAF", /* Gx */
"7DEBE8E4E90A5DAE6E4054CA530BA04654B36818CE226B39FCCB7B02F1AE", /* Gy */
ecc_oid_prime239v1, /* oid/oidSz */
ecc_oid_prime239v1_sz,
ECC_PRIME239V1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_SECPR2
{
30, /* size/bytes */
ECC_PRIME239V2, /* ID */
"PRIME239V2", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"617FAB6832576CBBFED50D99F0249C3FEE58B94BA0038C7AE84C8C832F2C", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF800000CFA7E8594377D414C03821BC582063", /* order */
"38AF09D98727705120C921BB5E9E26296A3CDCF2F35757A0EAFD87B830E7", /* Gx */
"5B0125E4DBEA0EC7206DA0FC01D9B081329FB555DE6EF460237DFF8BE4BA", /* Gy */
ecc_oid_prime239v2, /* oid/oidSz */
ecc_oid_prime239v2_sz,
ECC_PRIME239V2_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR2 */
#ifdef HAVE_ECC_SECPR3
{
30, /* size/bytes */
ECC_PRIME239V3, /* ID */
"PRIME239V3", /* curve name */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */
"255705FA2A306654B1F4CB03D6A750A30C250102D4988717D9BA15AB6D3E", /* B */
"7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF975DEB41B3A6057C3C432146526551", /* order */
"6768AE8E18BB92CFCF005C949AA2C6D94853D0E660BBF854B1C9505FE95A", /* Gx */
"1607E6898F390C06BC1D552BAD226F3B6FCFE48B6E818499AF18E3ED6CF3", /* Gy */
ecc_oid_prime239v3, /* oid/oidSz */
ecc_oid_prime239v3_sz,
ECC_PRIME239V3_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_SECPR3 */
#endif /* ECC239 */
#ifdef ECC256
#ifndef NO_ECC_SECP
{
32, /* size/bytes */
ECC_SECP256R1, /* ID */
"SECP256R1", /* curve name */
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", /* B */
"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", /* order */
"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", /* Gx */
"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", /* Gy */
ecc_oid_secp256r1, /* oid/oidSz */
ecc_oid_secp256r1_sz,
ECC_SECP256R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_KOBLITZ
{
32, /* size/bytes */
ECC_SECP256K1, /* ID */
"SECP256K1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", /* prime */
"0000000000000000000000000000000000000000000000000000000000000000", /* A */
"0000000000000000000000000000000000000000000000000000000000000007", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", /* order */
"79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", /* Gx */
"483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", /* Gy */
ecc_oid_secp256k1, /* oid/oidSz */
ecc_oid_secp256k1_sz,
ECC_SECP256K1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_KOBLITZ */
#ifdef HAVE_ECC_BRAINPOOL
{
32, /* size/bytes */
ECC_BRAINPOOLP256R1, /* ID */
"BRAINPOOLP256R1", /* curve name */
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", /* prime */
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", /* A */
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", /* B */
"A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", /* order */
"8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", /* Gx */
"547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", /* Gy */
ecc_oid_brainpoolp256r1, /* oid/oidSz */
ecc_oid_brainpoolp256r1_sz,
ECC_BRAINPOOLP256R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC256 */
#ifdef ECC320
#ifdef HAVE_ECC_BRAINPOOL
{
40, /* size/bytes */
ECC_BRAINPOOLP320R1, /* ID */
"BRAINPOOLP320R1", /* curve name */
"D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", /* prime */
"3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", /* A */
"520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", /* B */
"D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", /* order */
"43BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E20611", /* Gx */
"14FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1", /* Gy */
ecc_oid_brainpoolp320r1, ecc_oid_brainpoolp320r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP320R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC320 */
#ifdef ECC384
#ifndef NO_ECC_SECP
{
48, /* size/bytes */
ECC_SECP384R1, /* ID */
"SECP384R1", /* curve name */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", /* prime */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", /* A */
"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", /* B */
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", /* order */
"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", /* Gx */
"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", /* Gy */
ecc_oid_secp384r1, ecc_oid_secp384r1_sz, /* oid/oidSz */
ECC_SECP384R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#ifdef HAVE_ECC_BRAINPOOL
{
48, /* size/bytes */
ECC_BRAINPOOLP384R1, /* ID */
"BRAINPOOLP384R1", /* curve name */
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", /* prime */
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", /* A */
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", /* B */
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", /* order */
"1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", /* Gx */
"8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", /* Gy */
ecc_oid_brainpoolp384r1, ecc_oid_brainpoolp384r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP384R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC384 */
#ifdef ECC512
#ifdef HAVE_ECC_BRAINPOOL
{
64, /* size/bytes */
ECC_BRAINPOOLP512R1, /* ID */
"BRAINPOOLP512R1", /* curve name */
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", /* prime */
"7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", /* A */
"3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", /* B */
"AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", /* order */
"81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", /* Gx */
"7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", /* Gy */
ecc_oid_brainpoolp512r1, ecc_oid_brainpoolp512r1_sz, /* oid/oidSz */
ECC_BRAINPOOLP512R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* HAVE_ECC_BRAINPOOL */
#endif /* ECC512 */
#ifdef ECC521
#ifndef NO_ECC_SECP
{
66, /* size/bytes */
ECC_SECP521R1, /* ID */
"SECP521R1", /* curve name */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", /* A */
"51953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", /* B */
"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", /* order */
"C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", /* Gx */
"11839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", /* Gy */
ecc_oid_secp521r1, ecc_oid_secp521r1_sz, /* oid/oidSz */
ECC_SECP521R1_OID, /* oid sum */
1, /* cofactor */
},
#endif /* !NO_ECC_SECP */
#endif /* ECC521 */
#if defined(WOLFSSL_CUSTOM_CURVES) && defined(ECC_CACHE_CURVE)
/* place holder for custom curve index for cache */
{
1, /* non-zero */
ECC_CURVE_CUSTOM,
#ifndef WOLFSSL_ECC_CURVE_STATIC
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
#else
{0},{0},{0},{0},{0},{0},{0},{0},
#endif
0, 0, 0
},
#endif
{
0,
ECC_CURVE_INVALID,
#ifndef WOLFSSL_ECC_CURVE_STATIC
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
#else
{0},{0},{0},{0},{0},{0},{0},{0},
#endif
0, 0, 0
}
};
#define ECC_SET_COUNT (sizeof(ecc_sets)/sizeof(ecc_set_type))
#ifdef HAVE_OID_ENCODING
/* encoded OID cache */
typedef struct {
word32 oidSz;
byte oid[ECC_MAX_OID_LEN];
} oid_cache_t;
static oid_cache_t ecc_oid_cache[ECC_SET_COUNT];
#endif
#ifdef HAVE_COMP_KEY
static int wc_ecc_export_x963_compressed(ecc_key*, byte* out, word32* outLen);
#endif
#if (defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH)) && \
!defined(WOLFSSL_ATECC508A)
static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a,
mp_int* prime, mp_int* order);
#endif
int mp_jacobi(mp_int* a, mp_int* n, int* c);
int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret);
/* Curve Specs */
typedef struct ecc_curve_spec {
const ecc_set_type* dp;
mp_int* prime;
mp_int* Af;
#ifdef USE_ECC_B_PARAM
mp_int* Bf;
#endif
mp_int* order;
mp_int* Gx;
mp_int* Gy;
#ifdef ECC_CACHE_CURVE
mp_int prime_lcl;
mp_int Af_lcl;
#ifdef USE_ECC_B_PARAM
mp_int Bf_lcl;
#endif
mp_int order_lcl;
mp_int Gx_lcl;
mp_int Gy_lcl;
#else
mp_int* spec_ints;
word32 spec_count;
word32 spec_use;
#endif
byte load_mask;
} ecc_curve_spec;
enum ecc_curve_load_mask {
ECC_CURVE_FIELD_NONE = 0x00,
ECC_CURVE_FIELD_PRIME = 0x01,
ECC_CURVE_FIELD_AF = 0x02,
#ifdef USE_ECC_B_PARAM
ECC_CURVE_FIELD_BF = 0x04,
#endif
ECC_CURVE_FIELD_ORDER = 0x08,
ECC_CURVE_FIELD_GX = 0x10,
ECC_CURVE_FIELD_GY = 0x20,
#ifdef USE_ECC_B_PARAM
ECC_CURVE_FIELD_ALL = 0x3F,
ECC_CURVE_FIELD_COUNT = 6,
#else
ECC_CURVE_FIELD_ALL = 0x3B,
ECC_CURVE_FIELD_COUNT = 5,
#endif
};
#ifdef ECC_CACHE_CURVE
/* cache (mp_int) of the curve parameters */
static ecc_curve_spec* ecc_curve_spec_cache[ECC_SET_COUNT];
#ifndef SINGLE_THREADED
static wolfSSL_Mutex ecc_curve_cache_mutex;
#endif
#define DECLARE_CURVE_SPECS(curve, intcount) ecc_curve_spec* curve = NULL
#define ALLOC_CURVE_SPECS(intcount)
#define FREE_CURVE_SPECS()
#elif defined(WOLFSSL_SMALL_STACK)
#define DECLARE_CURVE_SPECS(curve, intcount) \
mp_int* spec_ints = NULL; \
ecc_curve_spec curve_lcl; \
ecc_curve_spec* curve = &curve_lcl; \
XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \
curve->spec_count = intcount
#define ALLOC_CURVE_SPECS(intcount) \
spec_ints = (mp_int*)XMALLOC(sizeof(mp_int) * (intcount), NULL, \
DYNAMIC_TYPE_ECC); \
if (spec_ints == NULL) \
return MEMORY_E; \
curve->spec_ints = spec_ints
#define FREE_CURVE_SPECS() \
XFREE(spec_ints, NULL, DYNAMIC_TYPE_ECC)
#else
#define DECLARE_CURVE_SPECS(curve, intcount) \
mp_int spec_ints[(intcount)]; \
ecc_curve_spec curve_lcl; \
ecc_curve_spec* curve = &curve_lcl; \
XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \
curve->spec_ints = spec_ints; \
curve->spec_count = intcount
#define ALLOC_CURVE_SPECS(intcount)
#define FREE_CURVE_SPECS()
#endif /* ECC_CACHE_CURVE */
static void _wc_ecc_curve_free(ecc_curve_spec* curve)
{
if (curve == NULL) {
return;
}
if (curve->load_mask & ECC_CURVE_FIELD_PRIME)
mp_clear(curve->prime);
if (curve->load_mask & ECC_CURVE_FIELD_AF)
mp_clear(curve->Af);
#ifdef USE_ECC_B_PARAM
if (curve->load_mask & ECC_CURVE_FIELD_BF)
mp_clear(curve->Bf);
#endif
if (curve->load_mask & ECC_CURVE_FIELD_ORDER)
mp_clear(curve->order);
if (curve->load_mask & ECC_CURVE_FIELD_GX)
mp_clear(curve->Gx);
if (curve->load_mask & ECC_CURVE_FIELD_GY)
mp_clear(curve->Gy);
curve->load_mask = 0;
}
static void wc_ecc_curve_free(ecc_curve_spec* curve)
{
/* don't free cached curves */
#ifndef ECC_CACHE_CURVE
_wc_ecc_curve_free(curve);
#endif
(void)curve;
}
static int wc_ecc_curve_load_item(const char* src, mp_int** dst,
ecc_curve_spec* curve, byte mask)
{
int err;
#ifndef ECC_CACHE_CURVE
/* get mp_int from temp */
if (curve->spec_use >= curve->spec_count) {
WOLFSSL_MSG("Invalid DECLARE_CURVE_SPECS count");
return ECC_BAD_ARG_E;
}
*dst = &curve->spec_ints[curve->spec_use++];
#endif
err = mp_init(*dst);
if (err == MP_OKAY) {
curve->load_mask |= mask;
err = mp_read_radix(*dst, src, MP_RADIX_HEX);
#ifdef HAVE_WOLF_BIGINT
if (err == MP_OKAY)
err = wc_mp_to_bigint(*dst, &(*dst)->raw);
#endif
}
return err;
}
static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve,
byte load_mask)
{
int ret = 0, x;
ecc_curve_spec* curve;
byte load_items = 0; /* mask of items to load */
if (dp == NULL || pCurve == NULL)
return BAD_FUNC_ARG;
#ifdef ECC_CACHE_CURVE
x = wc_ecc_get_curve_idx(dp->id);
if (x == ECC_CURVE_INVALID)
return ECC_BAD_ARG_E;
#if !defined(SINGLE_THREADED)
ret = wc_LockMutex(&ecc_curve_cache_mutex);
if (ret != 0) {
return ret;
}
#endif
/* make sure cache has been allocated */
if (ecc_curve_spec_cache[x] == NULL) {
ecc_curve_spec_cache[x] = (ecc_curve_spec*)XMALLOC(
sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC);
if (ecc_curve_spec_cache[x] == NULL) {
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_UnLockMutex(&ecc_curve_cache_mutex);
#endif
return MEMORY_E;
}
XMEMSET(ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec));
}
/* set curve pointer to cache */
*pCurve = ecc_curve_spec_cache[x];
#endif /* ECC_CACHE_CURVE */
curve = *pCurve;
/* make sure the curve is initialized */
if (curve->dp != dp) {
curve->load_mask = 0;
#ifdef ECC_CACHE_CURVE
curve->prime = &curve->prime_lcl;
curve->Af = &curve->Af_lcl;
#ifdef USE_ECC_B_PARAM
curve->Bf = &curve->Bf_lcl;
#endif
curve->order = &curve->order_lcl;
curve->Gx = &curve->Gx_lcl;
curve->Gy = &curve->Gy_lcl;
#endif
}
curve->dp = dp; /* set dp info */
/* determine items to load */
load_items = (((byte)~(word32)curve->load_mask) & load_mask);
curve->load_mask |= load_items;
/* load items */
x = 0;
if (load_items & ECC_CURVE_FIELD_PRIME)
x += wc_ecc_curve_load_item(dp->prime, &curve->prime, curve,
ECC_CURVE_FIELD_PRIME);
if (load_items & ECC_CURVE_FIELD_AF)
x += wc_ecc_curve_load_item(dp->Af, &curve->Af, curve,
ECC_CURVE_FIELD_AF);
#ifdef USE_ECC_B_PARAM
if (load_items & ECC_CURVE_FIELD_BF)
x += wc_ecc_curve_load_item(dp->Bf, &curve->Bf, curve,
ECC_CURVE_FIELD_BF);
#endif
if (load_items & ECC_CURVE_FIELD_ORDER)
x += wc_ecc_curve_load_item(dp->order, &curve->order, curve,
ECC_CURVE_FIELD_ORDER);
if (load_items & ECC_CURVE_FIELD_GX)
x += wc_ecc_curve_load_item(dp->Gx, &curve->Gx, curve,
ECC_CURVE_FIELD_GX);
if (load_items & ECC_CURVE_FIELD_GY)
x += wc_ecc_curve_load_item(dp->Gy, &curve->Gy, curve,
ECC_CURVE_FIELD_GY);
/* check for error */
if (x != 0) {
wc_ecc_curve_free(curve);
ret = MP_READ_E;
}
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_UnLockMutex(&ecc_curve_cache_mutex);
#endif
return ret;
}
#ifdef ECC_CACHE_CURVE
int wc_ecc_curve_cache_init(void)
{
int ret = 0;
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
ret = wc_InitMutex(&ecc_curve_cache_mutex);
#endif
return ret;
}
void wc_ecc_curve_cache_free(void)
{
int x;
/* free all ECC curve caches */
for (x = 0; x < (int)ECC_SET_COUNT; x++) {
if (ecc_curve_spec_cache[x]) {
_wc_ecc_curve_free(ecc_curve_spec_cache[x]);
XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC);
ecc_curve_spec_cache[x] = NULL;
}
}
#if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED)
wc_FreeMutex(&ecc_curve_cache_mutex);
#endif
}
#endif /* ECC_CACHE_CURVE */
/* Retrieve the curve name for the ECC curve id.
*
* curve_id The id of the curve.
* returns the name stored from the curve if available, otherwise NULL.
*/
const char* wc_ecc_get_name(int curve_id)
{
int curve_idx = wc_ecc_get_curve_idx(curve_id);
if (curve_idx == ECC_CURVE_INVALID)
return NULL;
return ecc_sets[curve_idx].name;
}
int wc_ecc_set_curve(ecc_key* key, int keysize, int curve_id)
{
if (keysize <= 0 && curve_id < 0) {
return BAD_FUNC_ARG;
}
if (keysize > ECC_MAXSIZE) {
return ECC_BAD_ARG_E;
}
/* handle custom case */
if (key->idx != ECC_CUSTOM_IDX) {
int x;
/* default values */
key->idx = 0;
key->dp = NULL;
/* find ecc_set based on curve_id or key size */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (curve_id > ECC_CURVE_DEF) {
if (curve_id == ecc_sets[x].id)
break;
}
else if (keysize <= ecc_sets[x].size) {
break;
}
}
if (ecc_sets[x].size == 0) {
WOLFSSL_MSG("ECC Curve not found");
return ECC_CURVE_OID_E;
}
key->idx = x;
key->dp = &ecc_sets[x];
}
return 0;
}
#ifdef ALT_ECC_SIZE
static void alt_fp_init(mp_int* a)
{
a->size = FP_SIZE_ECC;
mp_zero(a);
}
#endif /* ALT_ECC_SIZE */
#ifndef WOLFSSL_ATECC508A
#if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_PUBLIC_ECC_ADD_DBL)
/**
Add two ECC points
P The point to add
Q The point to add
R [out] The destination of the double
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
return MP_OKAY on success
*/
int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R,
mp_int* a, mp_int* modulus, mp_digit mp)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif
mp_int *x, *y, *z;
int err;
if (P == NULL || Q == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* if Q == R then swap P and Q, so we don't require a local x,y,z */
if (Q == R) {
ecc_point* tPt = P;
P = Q;
Q = tPt;
}
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key != NULL) {
t1 = R->key->t1;
t2 = R->key->t2;
#ifdef ALT_ECC_SIZE
rx = R->key->x;
ry = R->key->y;
rz = R->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif /* WOLFSSL_SMALL_STACK */
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
/* should we dbl instead? */
if (err == MP_OKAY)
err = mp_sub(modulus, Q->y, t1);
if (err == MP_OKAY) {
if ( (mp_cmp(P->x, Q->x) == MP_EQ) &&
(get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) &&
(mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, t1) == MP_EQ)) {
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return ecc_projective_dbl_point(P, R, a, modulus, mp);
}
}
if (err != MP_OKAY) {
goto done;
}
/* If use ALT_ECC_SIZE we need to use local stack variable since
ecc_point x,y,z is reduced size */
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
goto done;
}
#else
/* Use destination directly */
x = R->x;
y = R->y;
z = R->z;
#endif
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
/* if Z is one then these are no-operations */
if (err == MP_OKAY) {
if (!mp_iszero(Q->z)) {
/* T1 = Z' * Z' */
err = mp_sqr(Q->z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = X * T1 */
if (err == MP_OKAY)
err = mp_mul(t1, x, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* T1 = Z' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->z, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Y = Y * T1 */
if (err == MP_OKAY)
err = mp_mul(t1, y, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
}
}
/* T1 = Z*Z */
if (err == MP_OKAY)
err = mp_sqr(z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* T2 = X' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->x, t1, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = Z * T1 */
if (err == MP_OKAY)
err = mp_mul(z, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* T1 = Y' * T1 */
if (err == MP_OKAY)
err = mp_mul(Q->y, t1, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Y = Y - T1 */
if (err == MP_OKAY)
err = mp_sub(y, t1, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* T1 = 2T1 */
if (err == MP_OKAY)
err = mp_add(t1, t1, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = Y + T1 */
if (err == MP_OKAY)
err = mp_add(t1, y, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* X = X - T2 */
if (err == MP_OKAY)
err = mp_sub(x, t2, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* T2 = 2T2 */
if (err == MP_OKAY)
err = mp_add(t2, t2, t2);
if (err == MP_OKAY) {
if (mp_cmp(t2, modulus) != MP_LT)
err = mp_sub(t2, modulus, t2);
}
/* T2 = X + T2 */
if (err == MP_OKAY)
err = mp_add(t2, x, t2);
if (err == MP_OKAY) {
if (mp_cmp(t2, modulus) != MP_LT)
err = mp_sub(t2, modulus, t2);
}
if (err == MP_OKAY) {
if (!mp_iszero(Q->z)) {
/* Z = Z * Z' */
err = mp_mul(z, Q->z, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
}
}
/* Z = Z * X */
if (err == MP_OKAY)
err = mp_mul(z, x, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
/* T1 = T1 * X */
if (err == MP_OKAY)
err = mp_mul(t1, x, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = X * X */
if (err == MP_OKAY)
err = mp_sqr(x, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* T2 = T2 * x */
if (err == MP_OKAY)
err = mp_mul(t2, x, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T1 * X */
if (err == MP_OKAY)
err = mp_mul(t1, x, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* X = Y*Y */
if (err == MP_OKAY)
err = mp_sqr(y, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* X = X - T2 */
if (err == MP_OKAY)
err = mp_sub(x, t2, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* T2 = T2 - X */
if (err == MP_OKAY)
err = mp_sub(t2, x, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T2 = T2 - X */
if (err == MP_OKAY)
err = mp_sub(t2, x, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T2 = T2 * Y */
if (err == MP_OKAY)
err = mp_mul(t2, y, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* Y = T2 - T1 */
if (err == MP_OKAY)
err = mp_sub(t2, t1, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* Y = Y/2 */
if (err == MP_OKAY) {
if (mp_isodd(y) == MP_YES)
err = mp_add(y, modulus, y);
}
if (err == MP_OKAY)
err = mp_div_2(y, y);
#ifdef ALT_ECC_SIZE
if (err == MP_OKAY)
err = mp_copy(x, R->x);
if (err == MP_OKAY)
err = mp_copy(y, R->y);
if (err == MP_OKAY)
err = mp_copy(z, R->z);
#endif
done:
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || Q == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
(void)a;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_proj_add_point_256(P->x, P->y, P->z, Q->x, Q->y, Q->z,
R->x, R->y, R->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_proj_add_point_384(P->x, P->y, P->z, Q->x, Q->y, Q->z,
R->x, R->y, R->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
/* ### Point doubling in Jacobian coordinate system ###
*
* let us have a curve: y^2 = x^3 + a*x + b
* in Jacobian coordinates it becomes: y^2 = x^3 + a*x*z^4 + b*z^6
*
* The doubling of P = (Xp, Yp, Zp) is given by R = (Xr, Yr, Zr) where:
* Xr = M^2 - 2*S
* Yr = M * (S - Xr) - 8*T
* Zr = 2 * Yp * Zp
*
* M = 3 * Xp^2 + a*Zp^4
* T = Yp^4
* S = 4 * Xp * Yp^2
*
* SPECIAL CASE: when a == 3 we can compute M as
* M = 3 * (Xp^2 - Zp^4) = 3 * (Xp + Zp^2) * (Xp - Zp^2)
*/
/**
Double an ECC point
P The point to double
R [out] The destination of the double
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
return MP_OKAY on success
*/
int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif
mp_int *x, *y, *z;
int err;
if (P == NULL || R == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key != NULL) {
t1 = R->key->t1;
t2 = R->key->t2;
#ifdef ALT_ECC_SIZE
rx = R->key->x;
ry = R->key->y;
rz = R->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
/* If use ALT_ECC_SIZE we need to use local stack variable since
ecc_point x,y,z is reduced size */
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
}
#else
/* Use destination directly */
x = R->x;
y = R->y;
z = R->z;
#endif
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
/* T1 = Z * Z */
if (err == MP_OKAY)
err = mp_sqr(z, t1);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t1, modulus, mp);
/* Z = Y * Z */
if (err == MP_OKAY)
err = mp_mul(z, y, z);
if (err == MP_OKAY)
err = mp_montgomery_reduce(z, modulus, mp);
/* Z = 2Z */
if (err == MP_OKAY)
err = mp_add(z, z, z);
if (err == MP_OKAY) {
if (mp_cmp(z, modulus) != MP_LT)
err = mp_sub(z, modulus, z);
}
/* Determine if curve "a" should be used in calc */
#ifdef WOLFSSL_CUSTOM_CURVES
if (err == MP_OKAY) {
/* Use a and prime to determine if a == 3 */
err = mp_submod(modulus, a, modulus, t2);
}
if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
/* use "a" in calc */
/* T2 = T1 * T1 */
if (err == MP_OKAY)
err = mp_sqr(t1, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T2 * a */
if (err == MP_OKAY)
err = mp_mulmod(t2, a, modulus, t1);
/* T2 = X * X */
if (err == MP_OKAY)
err = mp_sqr(x, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T2 + T1 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
}
else
#endif /* WOLFSSL_CUSTOM_CURVES */
{
/* assumes "a" == 3 */
(void)a;
/* T2 = X - T1 */
if (err == MP_OKAY)
err = mp_sub(x, t1, t2);
if (err == MP_OKAY) {
if (mp_isneg(t2))
err = mp_add(t2, modulus, t2);
}
/* T1 = X + T1 */
if (err == MP_OKAY)
err = mp_add(t1, x, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T2 = T1 * T2 */
if (err == MP_OKAY)
err = mp_mul(t1, t2, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T1 = 2T2 */
if (err == MP_OKAY)
err = mp_add(t2, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
/* T1 = T1 + T2 */
if (err == MP_OKAY)
err = mp_add(t1, t2, t1);
if (err == MP_OKAY) {
if (mp_cmp(t1, modulus) != MP_LT)
err = mp_sub(t1, modulus, t1);
}
}
/* Y = 2Y */
if (err == MP_OKAY)
err = mp_add(y, y, y);
if (err == MP_OKAY) {
if (mp_cmp(y, modulus) != MP_LT)
err = mp_sub(y, modulus, y);
}
/* Y = Y * Y */
if (err == MP_OKAY)
err = mp_sqr(y, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* T2 = Y * Y */
if (err == MP_OKAY)
err = mp_sqr(y, t2);
if (err == MP_OKAY)
err = mp_montgomery_reduce(t2, modulus, mp);
/* T2 = T2/2 */
if (err == MP_OKAY) {
if (mp_isodd(t2) == MP_YES)
err = mp_add(t2, modulus, t2);
}
if (err == MP_OKAY)
err = mp_div_2(t2, t2);
/* Y = Y * X */
if (err == MP_OKAY)
err = mp_mul(y, x, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* X = T1 * T1 */
if (err == MP_OKAY)
err = mp_sqr(t1, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
/* X = X - Y */
if (err == MP_OKAY)
err = mp_sub(x, y, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* X = X - Y */
if (err == MP_OKAY)
err = mp_sub(x, y, x);
if (err == MP_OKAY) {
if (mp_isneg(x))
err = mp_add(x, modulus, x);
}
/* Y = Y - X */
if (err == MP_OKAY)
err = mp_sub(y, x, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
/* Y = Y * T1 */
if (err == MP_OKAY)
err = mp_mul(y, t1, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
/* Y = Y - T2 */
if (err == MP_OKAY)
err = mp_sub(y, t2, y);
if (err == MP_OKAY) {
if (mp_isneg(y))
err = mp_add(y, modulus, y);
}
#ifdef ALT_ECC_SIZE
if (err == MP_OKAY)
err = mp_copy(x, R->x);
if (err == MP_OKAY)
err = mp_copy(y, R->y);
if (err == MP_OKAY)
err = mp_copy(z, R->z);
#endif
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (R->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || R == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
(void)a;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_proj_dbl_point_256(P->x, P->y, P->z, R->x, R->y, R->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_proj_dbl_point_384(P->x, P->y, P->z, R->x, R->y, R->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
/**
Map a projective Jacobian point back to affine space
P [in/out] The point to map
modulus The modulus of the field the ECC curve is in
mp The "b" value from montgomery_setup()
return MP_OKAY on success
*/
int ecc_map(ecc_point* P, mp_int* modulus, mp_digit mp)
{
#ifndef WOLFSSL_SP_MATH
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1 = NULL;
mp_int* t2 = NULL;
#ifdef ALT_ECC_SIZE
mp_int* rx = NULL;
mp_int* ry = NULL;
mp_int* rz = NULL;
#endif
#else
mp_int t1[1], t2[1];
#ifdef ALT_ECC_SIZE
mp_int rx[1], ry[1], rz[1];
#endif
#endif /* WOLFSSL_SMALL_STACK */
mp_int *x, *y, *z;
int err;
if (P == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
/* special case for point at infinity */
if (mp_cmp_d(P->z, 0) == MP_EQ) {
err = mp_set(P->x, 0);
if (err == MP_OKAY)
err = mp_set(P->y, 0);
if (err == MP_OKAY)
err = mp_set(P->z, 1);
return err;
}
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key != NULL) {
t1 = P->key->t1;
t2 = P->key->t2;
#ifdef ALT_ECC_SIZE
rx = P->key->x;
ry = P->key->y;
rz = P->key->z;
#endif
}
else
#endif /* WOLFSSL_SMALL_STACK_CACHE */
{
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL || t2 == NULL) {
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
rx = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
ry = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
rz = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rx == NULL || ry == NULL || rz == NULL) {
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
}
#endif /* WOLFSSL_SMALL_STACK */
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return MEMORY_E;
}
#ifdef ALT_ECC_SIZE
/* Use local stack variable */
x = rx;
y = ry;
z = rz;
if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) {
goto done;
}
if (err == MP_OKAY)
err = mp_copy(P->x, x);
if (err == MP_OKAY)
err = mp_copy(P->y, y);
if (err == MP_OKAY)
err = mp_copy(P->z, z);
if (err != MP_OKAY) {
goto done;
}
#else
/* Use destination directly */
x = P->x;
y = P->y;
z = P->z;
#endif
/* first map z back to normal */
err = mp_montgomery_reduce(z, modulus, mp);
/* get 1/z */
if (err == MP_OKAY)
err = mp_invmod(z, modulus, t1);
/* get 1/z^2 and 1/z^3 */
if (err == MP_OKAY)
err = mp_sqr(t1, t2);
if (err == MP_OKAY)
err = mp_mod(t2, modulus, t2);
if (err == MP_OKAY)
err = mp_mul(t1, t2, t1);
if (err == MP_OKAY)
err = mp_mod(t1, modulus, t1);
/* multiply against x/y */
if (err == MP_OKAY)
err = mp_mul(x, t2, x);
if (err == MP_OKAY)
err = mp_montgomery_reduce(x, modulus, mp);
if (err == MP_OKAY)
err = mp_mul(y, t1, y);
if (err == MP_OKAY)
err = mp_montgomery_reduce(y, modulus, mp);
if (err == MP_OKAY)
err = mp_set(z, 1);
#ifdef ALT_ECC_SIZE
/* return result */
if (err == MP_OKAY)
err = mp_copy(x, P->x);
if (err == MP_OKAY)
err = mp_copy(y, P->y);
if (err == MP_OKAY)
err = mp_copy(z, P->z);
done:
#endif
/* clean up */
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
#ifdef WOLFSSL_SMALL_STACK_CACHE
if (P->key == NULL)
#endif
{
#ifdef ALT_ECC_SIZE
XFREE(rz, NULL, DYNAMIC_TYPE_ECC);
XFREE(ry, NULL, DYNAMIC_TYPE_ECC);
XFREE(rx, NULL, DYNAMIC_TYPE_ECC);
#endif
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
}
#endif
return err;
#else
if (P == NULL || modulus == NULL)
return ECC_BAD_ARG_E;
(void)mp;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_map_256(P->x, P->y, P->z);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_map_384(P->x, P->y, P->z);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
#endif /* !WOLFSSL_SP_MATH || WOLFSSL_PUBLIC_ECC_ADD_DBL */
#if !defined(FREESCALE_LTC_ECC) && !defined(WOLFSSL_STM32_PKA)
#if !defined(FP_ECC) || !defined(WOLFSSL_SP_MATH)
/**
Perform a point multiplication
k The scalar to multiply by
G The base point
R [out] Destination for kG
a ECC curve parameter a
modulus The modulus of the field the ECC curve is in
map Boolean whether to map back to affine or not
(1==map, 0 == leave in projective)
return MP_OKAY on success
*/
#ifdef FP_ECC
static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R,
mp_int* a, mp_int* modulus, int map,
void* heap)
#else
int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R,
mp_int* a, mp_int* modulus, int map,
void* heap)
#endif
{
#ifndef WOLFSSL_SP_MATH
#ifndef ECC_TIMING_RESISTANT
/* size of sliding window, don't change this! */
#define WINSIZE 4
#define M_POINTS 8
int first = 1, bitbuf = 0, bitcpy = 0, j;
#else
#define M_POINTS 4
#endif
ecc_point *tG, *M[M_POINTS];
int i, err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* mu = NULL;
#ifdef WOLFSSL_SMALL_STACK_CACHE
ecc_key key;
#endif
#else
mp_int mu[1];
#endif
mp_digit mp;
mp_digit buf;
int bitcnt = 0, mode = 0, digidx = 0;
if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* init variables */
tG = NULL;
XMEMSET(M, 0, sizeof(M));
#ifdef WOLFSSL_SMALL_STACK
mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
if (mu == NULL)
return MEMORY_E;
#endif
#ifdef WOLFSSL_SMALL_STACK_CACHE
key.t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#ifdef ALT_ECC_SIZE
key.x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#endif
if (key.t1 == NULL || key.t2 == NULL
#ifdef ALT_ECC_SIZE
|| key.x == NULL || key.y == NULL || key.z == NULL
#endif
) {
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif /* WOLFSSL_SMALL_STACK_CACHE */
/* init montgomery reduction */
if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if ((err = mp_init(mu)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if ((err = mp_montgomery_calc_normalization(mu, modulus)) != MP_OKAY) {
mp_clear(mu);
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* alloc ram for window temps */
for (i = 0; i < M_POINTS; i++) {
M[i] = wc_ecc_new_point_h(heap);
if (M[i] == NULL) {
mp_clear(mu);
err = MEMORY_E; goto exit;
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
M[i]->key = &key;
#endif
}
/* make a copy of G in case R==G */
tG = wc_ecc_new_point_h(heap);
if (tG == NULL)
err = MEMORY_E;
/* tG = G and convert to montgomery */
if (err == MP_OKAY) {
if (mp_cmp_d(mu, 1) == MP_EQ) {
err = mp_copy(G->x, tG->x);
if (err == MP_OKAY)
err = mp_copy(G->y, tG->y);
if (err == MP_OKAY)
err = mp_copy(G->z, tG->z);
} else {
err = mp_mulmod(G->x, mu, modulus, tG->x);
if (err == MP_OKAY)
err = mp_mulmod(G->y, mu, modulus, tG->y);
if (err == MP_OKAY)
err = mp_mulmod(G->z, mu, modulus, tG->z);
}
}
/* done with mu */
mp_clear(mu);
#ifdef WOLFSSL_SMALL_STACK_CACHE
R->key = &key;
#endif
#ifndef ECC_TIMING_RESISTANT
/* calc the M tab, which holds kG for k==8..15 */
/* M[0] == 8G */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(tG, M[0], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp);
/* now find (8+k)G for k=1..7 */
if (err == MP_OKAY)
for (j = 9; j < 16; j++) {
err = ecc_projective_add_point(M[j-9], tG, M[j-M_POINTS], a, modulus,
mp);
if (err != MP_OKAY) break;
}
/* setup sliding window */
if (err == MP_OKAY) {
mode = 0;
bitcnt = 1;
buf = 0;
digidx = get_digit_count(k) - 1;
bitcpy = bitbuf = 0;
first = 1;
/* perform ops */
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
if (digidx == -1) {
break;
}
buf = get_digit(k, digidx);
bitcnt = (int) DIGIT_BIT;
--digidx;
}
/* grab the next msb from the ltiplicand */
i = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= 1;
/* skip leading zero bits */
if (mode == 0 && i == 0)
continue;
/* if the bit is zero and mode == 1 then we double */
if (mode == 1 && i == 0) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
continue;
}
/* else we add it to the window */
bitbuf |= (i << (WINSIZE - ++bitcpy));
mode = 2;
if (bitcpy == WINSIZE) {
/* if this is the first window we do a simple copy */
if (first == 1) {
/* R = kG [k = first window] */
err = mp_copy(M[bitbuf-M_POINTS]->x, R->x);
if (err != MP_OKAY) break;
err = mp_copy(M[bitbuf-M_POINTS]->y, R->y);
if (err != MP_OKAY) break;
err = mp_copy(M[bitbuf-M_POINTS]->z, R->z);
first = 0;
} else {
/* normal window */
/* ok window is filled so double as required and add */
/* double first */
for (j = 0; j < WINSIZE; j++) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
if (err != MP_OKAY) break; /* out of first for(;;) */
/* then add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */
err = ecc_projective_add_point(R, M[bitbuf-M_POINTS], R, a,
modulus, mp);
}
if (err != MP_OKAY) break;
/* empty window and reset */
bitcpy = bitbuf = 0;
mode = 1;
}
}
}
/* if bits remain then double/add */
if (err == MP_OKAY) {
if (mode == 2 && bitcpy > 0) {
/* double then add */
for (j = 0; j < bitcpy; j++) {
/* only double if we have had at least one add first */
if (first == 0) {
err = ecc_projective_dbl_point(R, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
bitbuf <<= 1;
if ((bitbuf & (1 << WINSIZE)) != 0) {
if (first == 1) {
/* first add, so copy */
err = mp_copy(tG->x, R->x);
if (err != MP_OKAY) break;
err = mp_copy(tG->y, R->y);
if (err != MP_OKAY) break;
err = mp_copy(tG->z, R->z);
if (err != MP_OKAY) break;
first = 0;
} else {
/* then add */
err = ecc_projective_add_point(R, tG, R, a, modulus, mp);
if (err != MP_OKAY) break;
}
}
}
}
}
#undef WINSIZE
#else /* ECC_TIMING_RESISTANT */
/* calc the M tab */
/* M[0] == G */
if (err == MP_OKAY)
err = mp_copy(tG->x, M[0]->x);
if (err == MP_OKAY)
err = mp_copy(tG->y, M[0]->y);
if (err == MP_OKAY)
err = mp_copy(tG->z, M[0]->z);
/* M[1] == 2G */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(tG, M[1], a, modulus, mp);
#ifdef WC_NO_CACHE_RESISTANT
if (err == MP_OKAY)
err = wc_ecc_copy_point(M[0], M[2]);
#endif
/* setup sliding window */
mode = 0;
bitcnt = 1;
buf = 0;
digidx = get_digit_count(modulus) - 1;
/* The order MAY be 1 bit longer than the modulus. */
digidx += (modulus->dp[digidx] >> (DIGIT_BIT-1));
/* perform ops */
if (err == MP_OKAY) {
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
if (digidx == -1) {
break;
}
buf = get_digit(k, digidx);
bitcnt = (int)DIGIT_BIT;
--digidx;
}
/* grab the next msb from the multiplicand */
i = (buf >> (DIGIT_BIT - 1)) & 1;
buf <<= 1;
#ifdef WC_NO_CACHE_RESISTANT
if (mode == 0) {
/* timing resistant - dummy operations */
if (err == MP_OKAY)
err = ecc_projective_add_point(M[1], M[2], M[2], a, modulus,
mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[2], M[3], a, modulus, mp);
}
else {
if (err == MP_OKAY)
err = ecc_projective_add_point(M[0], M[1], M[i^1], a,
modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[i], M[i], a, modulus, mp);
}
mode |= i;
#else
if (err == MP_OKAY)
err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus,
mp);
if (err == MP_OKAY)
err = mp_copy(M[2]->x,
(mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->x & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->x & wc_off_on_addr[mode^1])) );
if (err == MP_OKAY)
err = mp_copy(M[2]->y,
(mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->y & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->y & wc_off_on_addr[mode^1])) );
if (err == MP_OKAY)
err = mp_copy(M[2]->z,
(mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[mode&(i )]) +
((size_t)M[1]->z & wc_off_on_addr[mode&(i^1)]) +
((size_t)M[2]->z & wc_off_on_addr[mode^1])) );
/* instead of using M[i] for double, which leaks key bit to cache
* monitor, use M[2] as temp, make sure address calc is constant,
* keep M[0] and M[1] in cache */
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[i^1]) +
((size_t)M[1]->x & wc_off_on_addr[i])),
M[2]->x);
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[i^1]) +
((size_t)M[1]->y & wc_off_on_addr[i])),
M[2]->y);
if (err == MP_OKAY)
err = mp_copy((mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[i^1]) +
((size_t)M[1]->z & wc_off_on_addr[i])),
M[2]->z);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(M[2], M[3], a, modulus, mp);
/* copy M[2] back to M[i] */
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->x & wc_off_on_addr[mode^1]) +
((size_t)M[3]->x & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->x & wc_off_on_addr[i^1]) +
((size_t)M[1]->x & wc_off_on_addr[i])) );
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->y & wc_off_on_addr[mode^1]) +
((size_t)M[3]->y & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->y & wc_off_on_addr[i^1]) +
((size_t)M[1]->y & wc_off_on_addr[i])) );
if (err == MP_OKAY)
err = mp_copy((mp_int*)
(((size_t)M[2]->z & wc_off_on_addr[mode^1]) +
((size_t)M[3]->z & wc_off_on_addr[mode])),
(mp_int*)
( ((size_t)M[0]->z & wc_off_on_addr[i^1]) +
((size_t)M[1]->z & wc_off_on_addr[i])) );
if (err != MP_OKAY)
break;
mode |= i;
#endif /* WC_NO_CACHE_RESISTANT */
} /* end for */
}
/* copy result out */
if (err == MP_OKAY)
err = mp_copy(M[0]->x, R->x);
if (err == MP_OKAY)
err = mp_copy(M[0]->y, R->y);
if (err == MP_OKAY)
err = mp_copy(M[0]->z, R->z);
#endif /* ECC_TIMING_RESISTANT */
/* map R back from projective space */
if (err == MP_OKAY && map)
err = ecc_map(R, modulus, mp);
exit:
/* done */
wc_ecc_del_point_h(tG, heap);
for (i = 0; i < M_POINTS; i++) {
wc_ecc_del_point_h(M[i], heap);
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
R->key = NULL;
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
#endif /* WOLFSSL_SMALL_STACK_CACHE */
#ifdef WOLFSSL_SMALL_STACK
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
#endif
return err;
#else
if (k == NULL || G == NULL || R == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
(void)a;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_mulmod_256(k, G, R, map, heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_mulmod_384(k, G, R, map, heap);
}
#endif
return ECC_BAD_ARG_E;
#endif
}
#endif /* !FP_ECC || !WOLFSSL_SP_MATH */
#endif /* !FREESCALE_LTC_ECC && !WOLFSSL_STM32_PKA */
/** ECC Fixed Point mulmod global
k The multiplicand
G Base point to multiply
R [out] Destination of product
a ECC curve parameter a
modulus The modulus for the curve
map [boolean] If non-zero maps the point back to affine coordinates,
otherwise it's left in jacobian-montgomery form
return MP_OKAY if successful
*/
int wc_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
mp_int* modulus, int map)
{
return wc_ecc_mulmod_ex(k, G, R, a, modulus, map, NULL);
}
#endif /* !WOLFSSL_ATECC508A */
/**
* use a heap hint when creating new ecc_point
* return an allocated point on success or NULL on failure
*/
ecc_point* wc_ecc_new_point_h(void* heap)
{
ecc_point* p;
(void)heap;
p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC);
if (p == NULL) {
return NULL;
}
XMEMSET(p, 0, sizeof(ecc_point));
#ifndef ALT_ECC_SIZE
if (mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL) != MP_OKAY) {
XFREE(p, heap, DYNAMIC_TYPE_ECC);
return NULL;
}
#else
p->x = (mp_int*)&p->xyz[0];
p->y = (mp_int*)&p->xyz[1];
p->z = (mp_int*)&p->xyz[2];
alt_fp_init(p->x);
alt_fp_init(p->y);
alt_fp_init(p->z);
#endif
return p;
}
/**
Allocate a new ECC point
return A newly allocated point or NULL on error
*/
ecc_point* wc_ecc_new_point(void)
{
return wc_ecc_new_point_h(NULL);
}
void wc_ecc_del_point_h(ecc_point* p, void* heap)
{
/* prevents free'ing null arguments */
if (p != NULL) {
mp_clear(p->x);
mp_clear(p->y);
mp_clear(p->z);
XFREE(p, heap, DYNAMIC_TYPE_ECC);
}
(void)heap;
}
/** Free an ECC point from memory
p The point to free
*/
void wc_ecc_del_point(ecc_point* p)
{
wc_ecc_del_point_h(p, NULL);
}
/** Copy the value of a point to an other one
p The point to copy
r The created point
*/
int wc_ecc_copy_point(ecc_point* p, ecc_point *r)
{
int ret;
/* prevents null arguments */
if (p == NULL || r == NULL)
return ECC_BAD_ARG_E;
ret = mp_copy(p->x, r->x);
if (ret != MP_OKAY)
return ret;
ret = mp_copy(p->y, r->y);
if (ret != MP_OKAY)
return ret;
ret = mp_copy(p->z, r->z);
if (ret != MP_OKAY)
return ret;
return MP_OKAY;
}
/** Compare the value of a point with an other one
a The point to compare
b The other point to compare
return MP_EQ if equal, MP_LT/MP_GT if not, < 0 in case of error
*/
int wc_ecc_cmp_point(ecc_point* a, ecc_point *b)
{
int ret;
/* prevents null arguments */
if (a == NULL || b == NULL)
return BAD_FUNC_ARG;
ret = mp_cmp(a->x, b->x);
if (ret != MP_EQ)
return ret;
ret = mp_cmp(a->y, b->y);
if (ret != MP_EQ)
return ret;
ret = mp_cmp(a->z, b->z);
if (ret != MP_EQ)
return ret;
return MP_EQ;
}
/** Returns whether an ECC idx is valid or not
n The idx number to check
return 1 if valid, 0 if not
*/
int wc_ecc_is_valid_idx(int n)
{
int x;
for (x = 0; ecc_sets[x].size != 0; x++)
;
/* -1 is a valid index --- indicating that the domain params
were supplied by the user */
if ((n >= ECC_CUSTOM_IDX) && (n < x)) {
return 1;
}
return 0;
}
int wc_ecc_get_curve_idx(int curve_id)
{
int curve_idx;
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (curve_id == ecc_sets[curve_idx].id)
break;
}
if (ecc_sets[curve_idx].size == 0) {
return ECC_CURVE_INVALID;
}
return curve_idx;
}
int wc_ecc_get_curve_id(int curve_idx)
{
if (wc_ecc_is_valid_idx(curve_idx)) {
return ecc_sets[curve_idx].id;
}
return ECC_CURVE_INVALID;
}
/* Returns the curve size that corresponds to a given ecc_curve_id identifier
*
* id curve id, from ecc_curve_id enum in ecc.h
* return curve size, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_size_from_id(int curve_id)
{
int curve_idx = wc_ecc_get_curve_idx(curve_id);
if (curve_idx == ECC_CURVE_INVALID)
return ECC_BAD_ARG_E;
return ecc_sets[curve_idx].size;
}
/* Returns the curve index that corresponds to a given curve name in
* ecc_sets[] of ecc.c
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve index in ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_idx_from_name(const char* curveName)
{
int curve_idx;
word32 len;
if (curveName == NULL)
return BAD_FUNC_ARG;
len = (word32)XSTRLEN(curveName);
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (
#ifndef WOLFSSL_ECC_CURVE_STATIC
ecc_sets[curve_idx].name &&
#endif
XSTRNCASECMP(ecc_sets[curve_idx].name, curveName, len) == 0) {
break;
}
}
if (ecc_sets[curve_idx].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
return ECC_CURVE_INVALID;
}
return curve_idx;
}
/* Returns the curve size that corresponds to a given curve name,
* as listed in ecc_sets[] of ecc.c.
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve size, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_size_from_name(const char* curveName)
{
int curve_idx;
if (curveName == NULL)
return BAD_FUNC_ARG;
curve_idx = wc_ecc_get_curve_idx_from_name(curveName);
if (curve_idx < 0)
return curve_idx;
return ecc_sets[curve_idx].size;
}
/* Returns the curve id that corresponds to a given curve name,
* as listed in ecc_sets[] of ecc.c.
*
* name curve name, from ecc_sets[].name in ecc.c
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_name(const char* curveName)
{
int curve_idx;
if (curveName == NULL)
return BAD_FUNC_ARG;
curve_idx = wc_ecc_get_curve_idx_from_name(curveName);
if (curve_idx < 0)
return curve_idx;
return ecc_sets[curve_idx].id;
}
/* Compares a curve parameter (hex, from ecc_sets[]) to given input
* parameter for equality.
* encType is WC_TYPE_UNSIGNED_BIN or WC_TYPE_HEX_STR
* Returns MP_EQ on success, negative on error */
static int wc_ecc_cmp_param(const char* curveParam,
const byte* param, word32 paramSz, int encType)
{
int err = MP_OKAY;
#ifdef WOLFSSL_SMALL_STACK
mp_int* a = NULL;
mp_int* b = NULL;
#else
mp_int a[1], b[1];
#endif
if (param == NULL || curveParam == NULL)
return BAD_FUNC_ARG;
if (encType == WC_TYPE_HEX_STR)
return XSTRNCMP(curveParam, (char*) param, paramSz);
#ifdef WOLFSSL_SMALL_STACK
a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (a == NULL)
return MEMORY_E;
b = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (b == NULL) {
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
if ((err = mp_init_multi(a, b, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
XFREE(b, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
if (err == MP_OKAY) {
err = mp_read_unsigned_bin(a, param, paramSz);
}
if (err == MP_OKAY)
err = mp_read_radix(b, curveParam, MP_RADIX_HEX);
if (err == MP_OKAY) {
if (mp_cmp(a, b) != MP_EQ) {
err = -1;
} else {
err = MP_EQ;
}
}
mp_clear(a);
mp_clear(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_ECC);
XFREE(a, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* Returns the curve id in ecc_sets[] that corresponds to a given set of
* curve parameters.
*
* fieldSize the field size in bits
* prime prime of the finite field
* primeSz size of prime in octets
* Af first coefficient a of the curve
* AfSz size of Af in octets
* Bf second coefficient b of the curve
* BfSz size of Bf in octets
* order curve order
* orderSz size of curve in octets
* Gx affine x coordinate of base point
* GxSz size of Gx in octets
* Gy affine y coordinate of base point
* GySz size of Gy in octets
* cofactor curve cofactor
*
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_params(int fieldSize,
const byte* prime, word32 primeSz, const byte* Af, word32 AfSz,
const byte* Bf, word32 BfSz, const byte* order, word32 orderSz,
const byte* Gx, word32 GxSz, const byte* Gy, word32 GySz, int cofactor)
{
int idx;
int curveSz;
if (prime == NULL || Af == NULL || Bf == NULL || order == NULL ||
Gx == NULL || Gy == NULL)
return BAD_FUNC_ARG;
curveSz = (fieldSize + 1) / 8; /* round up */
for (idx = 0; ecc_sets[idx].size != 0; idx++) {
if (curveSz == ecc_sets[idx].size) {
if ((wc_ecc_cmp_param(ecc_sets[idx].prime, prime,
primeSz, WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Af, Af, AfSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Bf, Bf, BfSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].order, order,
orderSz, WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gx, Gx, GxSz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gy, Gy, GySz,
WC_TYPE_UNSIGNED_BIN) == MP_EQ) &&
(cofactor == ecc_sets[idx].cofactor)) {
break;
}
}
}
if (ecc_sets[idx].size == 0)
return ECC_CURVE_INVALID;
return ecc_sets[idx].id;
}
/* Returns the curve id in ecc_sets[] that corresponds
* to a given domain parameters pointer.
*
* dp domain parameters pointer
*
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_dp_params(const ecc_set_type* dp)
{
int idx;
if (dp == NULL
#ifndef WOLFSSL_ECC_CURVE_STATIC
|| dp->prime == NULL || dp->Af == NULL ||
dp->Bf == NULL || dp->order == NULL || dp->Gx == NULL || dp->Gy == NULL
#endif
) {
return BAD_FUNC_ARG;
}
for (idx = 0; ecc_sets[idx].size != 0; idx++) {
if (dp->size == ecc_sets[idx].size) {
if ((wc_ecc_cmp_param(ecc_sets[idx].prime, (const byte*)dp->prime,
(word32)XSTRLEN(dp->prime), WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Af, (const byte*)dp->Af,
(word32)XSTRLEN(dp->Af),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Bf, (const byte*)dp->Bf,
(word32)XSTRLEN(dp->Bf),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].order, (const byte*)dp->order,
(word32)XSTRLEN(dp->order),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gx, (const byte*)dp->Gx,
(word32)XSTRLEN(dp->Gx),WC_TYPE_HEX_STR) == MP_EQ) &&
(wc_ecc_cmp_param(ecc_sets[idx].Gy, (const byte*)dp->Gy,
(word32)XSTRLEN(dp->Gy),WC_TYPE_HEX_STR) == MP_EQ) &&
(dp->cofactor == ecc_sets[idx].cofactor)) {
break;
}
}
}
if (ecc_sets[idx].size == 0)
return ECC_CURVE_INVALID;
return ecc_sets[idx].id;
}
/* Returns the curve id that corresponds to a given OID,
* as listed in ecc_sets[] of ecc.c.
*
* oid OID, from ecc_sets[].name in ecc.c
* len OID len, from ecc_sets[].name in ecc.c
* return curve id, from ecc_sets[] on success, negative on error
*/
int wc_ecc_get_curve_id_from_oid(const byte* oid, word32 len)
{
int curve_idx;
if (oid == NULL)
return BAD_FUNC_ARG;
for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) {
if (
#ifndef WOLFSSL_ECC_CURVE_STATIC
ecc_sets[curve_idx].oid &&
#endif
ecc_sets[curve_idx].oidSz == len &&
XMEMCMP(ecc_sets[curve_idx].oid, oid, len) == 0) {
break;
}
}
if (ecc_sets[curve_idx].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
return ECC_CURVE_INVALID;
}
return ecc_sets[curve_idx].id;
}
/* Get curve parameters using curve index */
const ecc_set_type* wc_ecc_get_curve_params(int curve_idx)
{
const ecc_set_type* ecc_set = NULL;
if (curve_idx >= 0 && curve_idx < (int)ECC_SET_COUNT) {
ecc_set = &ecc_sets[curve_idx];
}
return ecc_set;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static WC_INLINE int wc_ecc_alloc_mpint(ecc_key* key, mp_int** mp)
{
if (key == NULL || mp == NULL)
return BAD_FUNC_ARG;
if (*mp == NULL) {
*mp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_BIGINT);
if (*mp == NULL) {
return MEMORY_E;
}
XMEMSET(*mp, 0, sizeof(mp_int));
}
return 0;
}
static WC_INLINE void wc_ecc_free_mpint(ecc_key* key, mp_int** mp)
{
if (key && mp && *mp) {
mp_clear(*mp);
XFREE(*mp, key->heap, DYNAMIC_TYPE_BIGINT);
*mp = NULL;
}
}
static int wc_ecc_alloc_async(ecc_key* key)
{
int err = wc_ecc_alloc_mpint(key, &key->r);
if (err == 0)
err = wc_ecc_alloc_mpint(key, &key->s);
return err;
}
static void wc_ecc_free_async(ecc_key* key)
{
wc_ecc_free_mpint(key, &key->r);
wc_ecc_free_mpint(key, &key->s);
#ifdef HAVE_CAVIUM_V
wc_ecc_free_mpint(key, &key->e);
wc_ecc_free_mpint(key, &key->signK);
#endif /* HAVE_CAVIUM_V */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef HAVE_ECC_DHE
/**
Create an ECC shared secret between two keys
private_key The private ECC key (heap hint based off of private key)
public_key The public key
out [out] Destination of the shared secret
Conforms to EC-DH from ANSI X9.63
outlen [in/out] The max size and resulting size of the shared secret
return MP_OKAY if successful
*/
int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out,
word32* outlen)
{
int err;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
CRYS_ECDH_TempData_t tempBuff;
#endif
if (private_key == NULL || public_key == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
#ifdef WOLF_CRYPTO_CB
if (private_key->devId != INVALID_DEVID) {
err = wc_CryptoCb_Ecdh(private_key, public_key, out, outlen);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
/* type valid? */
if (private_key->type != ECC_PRIVATEKEY &&
private_key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* Verify domain params supplied */
if (wc_ecc_is_valid_idx(private_key->idx) == 0 ||
wc_ecc_is_valid_idx(public_key->idx) == 0) {
return ECC_BAD_ARG_E;
}
/* Verify curve id matches */
if (private_key->dp->id != public_key->dp->id) {
return ECC_BAD_ARG_E;
}
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 use hardware */
if (private_key->dp->id == ECC_SECP256R1) {
err = atmel_ecc_create_pms(private_key->slot, public_key->pubkey_raw, out);
*outlen = private_key->dp->size;
}
else {
err = NOT_COMPILED_IN;
}
#elif defined(WOLFSSL_CRYPTOCELL)
/* generate a secret*/
err = CRYS_ECDH_SVDP_DH(&public_key->ctx.pubKey,
&private_key->ctx.privKey,
out,
outlen,
&tempBuff);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECDH_SVDP_DH for secret failed");
return err;
}
#else
err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen);
#endif /* WOLFSSL_ATECC508A */
return err;
}
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point,
byte* out, word32* outlen, ecc_curve_spec* curve)
{
int err;
#ifndef WOLFSSL_SP_MATH
ecc_point* result = NULL;
word32 x = 0;
#endif
mp_int* k = &private_key->k;
#ifdef HAVE_ECC_CDH
mp_int k_lcl;
/* if cofactor flag has been set */
if (private_key->flags & WC_ECC_FLAG_COFACTOR) {
mp_digit cofactor = (mp_digit)private_key->dp->cofactor;
/* only perform cofactor calc if not equal to 1 */
if (cofactor != 1) {
k = &k_lcl;
if (mp_init(k) != MP_OKAY)
return MEMORY_E;
/* multiply cofactor times private key "k" */
err = mp_mul_d(&private_key->k, cofactor, k);
if (err != MP_OKAY) {
mp_clear(k);
return err;
}
}
}
#endif
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (private_key->idx != ECC_CUSTOM_IDX &&
ecc_sets[private_key->idx].id == ECC_SECP256R1) {
err = sp_ecc_secret_gen_256(k, point, out, outlen, private_key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (private_key->idx != ECC_CUSTOM_IDX &&
ecc_sets[private_key->idx].id == ECC_SECP384R1) {
err = sp_ecc_secret_gen_384(k, point, out, outlen, private_key->heap);
}
else
#endif
#endif
#ifdef WOLFSSL_SP_MATH
{
err = WC_KEY_SIZE_E;
(void)curve;
}
#else
{
/* make new point */
result = wc_ecc_new_point_h(private_key->heap);
if (result == NULL) {
#ifdef HAVE_ECC_CDH
if (k == &k_lcl)
mp_clear(k);
#endif
return MEMORY_E;
}
err = wc_ecc_mulmod_ex(k, point, result, curve->Af, curve->prime, 1,
private_key->heap);
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(curve->prime);
if (*outlen < x || (int)x < mp_unsigned_bin_size(result->x)) {
err = BUFFER_E;
}
}
if (err == MP_OKAY) {
XMEMSET(out, 0, x);
err = mp_to_unsigned_bin(result->x,out +
(x - mp_unsigned_bin_size(result->x)));
}
*outlen = x;
wc_ecc_del_point_h(result, private_key->heap);
}
#endif
#ifdef HAVE_ECC_CDH
if (k == &k_lcl)
mp_clear(k);
#endif
return err;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static int wc_ecc_shared_secret_gen_async(ecc_key* private_key,
ecc_point* point, byte* out, word32 *outlen,
ecc_curve_spec* curve)
{
int err;
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
/* verify the curve is supported by hardware */
if (NitroxEccIsCurveSupported(private_key))
#endif
{
word32 keySz = private_key->dp->size;
/* sync public key x/y */
err = wc_mp_to_bigint_sz(&private_key->k, &private_key->k.raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(point->y, &point->y->raw, keySz);
#ifdef HAVE_CAVIUM_V
/* allocate buffer for output */
if (err == MP_OKAY)
err = wc_ecc_alloc_mpint(private_key, &private_key->e);
if (err == MP_OKAY)
err = wc_bigint_alloc(&private_key->e->raw,
NitroxEccGetSize(private_key)*2);
if (err == MP_OKAY)
err = NitroxEcdh(private_key,
&private_key->k.raw, &point->x->raw, &point->y->raw,
private_key->e->raw.buf, &private_key->e->raw.len,
&curve->prime->raw);
#else
if (err == MP_OKAY)
err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF);
if (err == MP_OKAY)
err = IntelQaEcdh(&private_key->asyncDev,
&private_key->k.raw, &point->x->raw, &point->y->raw,
out, outlen,
&curve->Af->raw, &curve->Bf->raw, &curve->prime->raw,
private_key->dp->cofactor);
#endif
return err;
}
#elif defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (wc_AsyncTestInit(&private_key->asyncDev, ASYNC_TEST_ECC_SHARED_SEC)) {
WC_ASYNC_TEST* testDev = &private_key->asyncDev.test;
testDev->eccSharedSec.private_key = private_key;
testDev->eccSharedSec.public_point = point;
testDev->eccSharedSec.out = out;
testDev->eccSharedSec.outLen = outlen;
return WC_PENDING_E;
}
#endif
/* use sync in other cases */
err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve);
return err;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
int wc_ecc_shared_secret_gen(ecc_key* private_key, ecc_point* point,
byte* out, word32 *outlen)
{
int err;
DECLARE_CURVE_SPECS(curve, 2);
if (private_key == NULL || point == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
/* load curve info */
ALLOC_CURVE_SPECS(2);
err = wc_ecc_curve_load(private_key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
if (err != MP_OKAY) {
FREE_CURVE_SPECS();
return err;
}
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
err = wc_ecc_shared_secret_gen_async(private_key, point,
out, outlen, curve);
}
else
#endif
{
err = wc_ecc_shared_secret_gen_sync(private_key, point,
out, outlen, curve);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
/**
Create an ECC shared secret between private key and public point
private_key The private ECC key (heap hint based on private key)
point The point to use (public key)
out [out] Destination of the shared secret
Conforms to EC-DH from ANSI X9.63
outlen [in/out] The max size and resulting size of the shared secret
return MP_OKAY if successful
*/
int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point,
byte* out, word32 *outlen)
{
int err;
if (private_key == NULL || point == NULL || out == NULL ||
outlen == NULL) {
return BAD_FUNC_ARG;
}
/* type valid? */
if (private_key->type != ECC_PRIVATEKEY &&
private_key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* Verify domain params supplied */
if (wc_ecc_is_valid_idx(private_key->idx) == 0)
return ECC_BAD_ARG_E;
switch(private_key->state) {
case ECC_STATE_NONE:
case ECC_STATE_SHARED_SEC_GEN:
private_key->state = ECC_STATE_SHARED_SEC_GEN;
err = wc_ecc_shared_secret_gen(private_key, point, out, outlen);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_SHARED_SEC_RES:
private_key->state = ECC_STATE_SHARED_SEC_RES;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM_V
/* verify the curve is supported by hardware */
if (NitroxEccIsCurveSupported(private_key)) {
/* copy output */
*outlen = private_key->dp->size;
XMEMCPY(out, private_key->e->raw.buf, *outlen);
}
#endif /* HAVE_CAVIUM_V */
}
#endif /* WOLFSSL_ASYNC_CRYPT */
err = 0;
break;
default:
err = BAD_STATE_E;
} /* switch */
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
private_key->state++;
return err;
}
/* cleanup */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
wc_ecc_free_async(private_key);
#endif
private_key->state = ECC_STATE_NONE;
return err;
}
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
#endif /* HAVE_ECC_DHE */
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/* return 1 if point is at infinity, 0 if not, < 0 on error */
int wc_ecc_point_is_at_infinity(ecc_point* p)
{
if (p == NULL)
return BAD_FUNC_ARG;
if (get_digit_count(p->x) == 0 && get_digit_count(p->y) == 0)
return 1;
return 0;
}
/* generate random and ensure its greater than 0 and less than order */
int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
#ifndef WC_NO_RNG
int err;
byte buf[ECC_MAXSIZE_GEN];
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
ForceZero(buf, ECC_MAXSIZE);
return err;
#else
(void)rng;
(void)size;
(void)k;
(void)order;
return NOT_COMPILED_IN;
#endif /* !WC_NO_RNG */
}
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
static WC_INLINE void wc_ecc_reset(ecc_key* key)
{
/* make sure required key variables are reset */
key->state = ECC_STATE_NONE;
}
/* create the public ECC key from a private key
*
* key an initialized private key to generate public part from
* curveIn [in]curve for key, can be NULL
* pubOut [out]ecc_point holding the public key, if NULL then public key part
* is cached in key instead.
*
* Note this function is local to the file because of the argument type
* ecc_curve_spec. Having this argument allows for not having to load the
* curve type multiple times when generating a key with wc_ecc_make_key().
*
* returns MP_OKAY on success
*/
static int wc_ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn,
ecc_point* pubOut)
{
int err = MP_OKAY;
#ifndef WOLFSSL_ATECC508A
#ifndef WOLFSSL_SP_MATH
ecc_point* base = NULL;
#endif
ecc_point* pub;
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif /* !WOLFSSL_ATECC508A */
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifndef WOLFSSL_ATECC508A
/* if ecc_point passed in then use it as output for public key point */
if (pubOut != NULL) {
pub = pubOut;
}
else {
/* caching public key making it a ECC_PRIVATEKEY instead of
ECC_PRIVATEKEY_ONLY */
pub = &key->pubkey;
key->type = ECC_PRIVATEKEY_ONLY;
}
/* avoid loading the curve unless it is not passed in */
if (curveIn != NULL) {
curve = curveIn;
}
else {
/* load curve info */
if (err == MP_OKAY) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
}
if (err == MP_OKAY) {
#ifndef ALT_ECC_SIZE
err = mp_init_multi(pub->x, pub->y, pub->z, NULL, NULL, NULL);
#else
pub->x = (mp_int*)&pub->xyz[0];
pub->y = (mp_int*)&pub->xyz[1];
pub->z = (mp_int*)&pub->xyz[2];
alt_fp_init(pub->x);
alt_fp_init(pub->y);
alt_fp_init(pub->z);
#endif
}
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
if (err == MP_OKAY)
err = sp_ecc_mulmod_base_256(&key->k, pub, 1, key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
if (err == MP_OKAY)
err = sp_ecc_mulmod_base_384(&key->k, pub, 1, key->heap);
}
else
#endif
#endif
#ifdef WOLFSSL_SP_MATH
err = WC_KEY_SIZE_E;
#else
{
if (err == MP_OKAY) {
base = wc_ecc_new_point_h(key->heap);
if (base == NULL)
err = MEMORY_E;
}
/* read in the x/y for this key */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, base->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, base->y);
if (err == MP_OKAY)
err = mp_set(base->z, 1);
/* make the public key */
if (err == MP_OKAY) {
err = wc_ecc_mulmod_ex(&key->k, base, pub, curve->Af, curve->prime,
1, key->heap);
if (err == MP_MEM) {
err = MEMORY_E;
}
}
wc_ecc_del_point_h(base, key->heap);
}
#endif
#ifdef WOLFSSL_VALIDATE_ECC_KEYGEN
/* validate the public key, order * pubkey = point at infinity */
if (err == MP_OKAY)
err = ecc_check_pubkey_order(key, pub, curve->Af, curve->prime,
curve->order);
#endif /* WOLFSSL_VALIDATE_KEYGEN */
if (err != MP_OKAY) {
/* clean up if failed */
#ifndef ALT_ECC_SIZE
mp_clear(pub->x);
mp_clear(pub->y);
mp_clear(pub->z);
#endif
}
/* free up local curve */
if (curveIn == NULL) {
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
}
#else
(void)curveIn;
err = NOT_COMPILED_IN;
#endif /* WOLFSSL_ATECC508A */
/* change key state if public part is cached */
if (key->type == ECC_PRIVATEKEY_ONLY && pubOut == NULL) {
key->type = ECC_PRIVATEKEY;
}
return err;
}
/* create the public ECC key from a private key
*
* key an initialized private key to generate public part from
* pubOut [out]ecc_point holding the public key, if NULL then public key part
* is cached in key instead.
*
*
* returns MP_OKAY on success
*/
int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut)
{
WOLFSSL_ENTER("wc_ecc_make_pub");
return wc_ecc_make_pub_ex(key, NULL, pubOut);
}
WOLFSSL_ABI
int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id)
{
int err;
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifndef WOLFSSL_SP_MATH
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif
#endif /* !WOLFSSL_ATECC508A */
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_KG_TempData_t tempBuff;
CRYS_ECPKI_KG_FipsContext_t fipsCtx;
byte ucompressed_key[ECC_MAX_CRYPTO_HW_SIZE*2 + 1];
word32 raw_size = 0;
#endif
if (key == NULL || rng == NULL) {
return BAD_FUNC_ARG;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
err = wc_ecc_set_curve(key, keysize, curve_id);
if (err != 0) {
return err;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_MakeEccKey(rng, keysize, key, curve_id);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM
/* TODO: Not implemented */
#elif defined(HAVE_INTEL_QA)
/* TODO: Not implemented */
#else
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_MAKE)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccMake.rng = rng;
testDev->eccMake.key = key;
testDev->eccMake.size = keysize;
testDev->eccMake.curve_id = curve_id;
return WC_PENDING_E;
}
#endif
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_ATECC508A
if (key->dp->id == ECC_SECP256R1) {
key->type = ECC_PRIVATEKEY;
key->slot = atmel_ecc_alloc(ATMEL_SLOT_ECDHE);
err = atmel_ecc_create_key(key->slot, key->pubkey_raw);
/* populate key->pubkey */
if (err == 0
#ifdef ALT_ECC_SIZE
&& key->pubkey.x
#endif
) {
err = mp_read_unsigned_bin(key->pubkey.x, key->pubkey_raw,
ECC_MAX_CRYPTO_HW_SIZE);
}
if (err == 0
#ifdef ALT_ECC_SIZE
&& key->pubkey.y
#endif
) {
err = mp_read_unsigned_bin(key->pubkey.y,
key->pubkey_raw + ECC_MAX_CRYPTO_HW_SIZE,
ECC_MAX_CRYPTO_HW_SIZE);
}
}
else {
err = NOT_COMPILED_IN;
}
#elif defined(WOLFSSL_CRYPTOCELL)
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
raw_size = (word32)(key->dp->size)*2 + 1;
/* generate first key pair */
err = CRYS_ECPKI_GenKeyPair(&wc_rndState,
wc_rndGenVectFunc,
pDomain,
&key->ctx.privKey,
&key->ctx.pubKey,
&tempBuff,
&fipsCtx);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_GenKeyPair for key pair failed");
return err;
}
key->type = ECC_PRIVATEKEY;
err = CRYS_ECPKI_ExportPublKey(&key->ctx.pubKey,
CRYS_EC_PointUncompressed,
&ucompressed_key[0],
&raw_size);
if (err == SA_SILIB_RET_OK && key->pubkey.x && key->pubkey.y) {
err = mp_read_unsigned_bin(key->pubkey.x,
&ucompressed_key[1], key->dp->size);
if (err == MP_OKAY) {
err = mp_read_unsigned_bin(key->pubkey.y,
&ucompressed_key[1+key->dp->size],key->dp->size);
}
}
raw_size = key->dp->size;
if (err == MP_OKAY) {
err = CRYS_ECPKI_ExportPrivKey(&key->ctx.privKey,
ucompressed_key,
&raw_size);
}
if (err == SA_SILIB_RET_OK) {
err = mp_read_unsigned_bin(&key->k, ucompressed_key, raw_size);
}
#else
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap);
if (err == MP_OKAY) {
key->type = ECC_PRIVATEKEY;
}
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_make_key_384(rng, &key->k, &key->pubkey, key->heap);
if (err == MP_OKAY) {
key->type = ECC_PRIVATEKEY;
}
}
else
#endif
#endif /* WOLFSSL_HAVE_SP_ECC */
{ /* software key gen */
#ifdef WOLFSSL_SP_MATH
err = WC_KEY_SIZE_E;
#else
/* setup the key variables */
err = mp_init(&key->k);
/* load curve info */
if (err == MP_OKAY) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
/* generate k */
if (err == MP_OKAY)
err = wc_ecc_gen_k(rng, key->dp->size, &key->k, curve->order);
/* generate public key from k */
if (err == MP_OKAY)
err = wc_ecc_make_pub_ex(key, curve, NULL);
if (err == MP_OKAY)
key->type = ECC_PRIVATEKEY;
/* cleanup these on failure case only */
if (err != MP_OKAY) {
/* clean up */
mp_forcezero(&key->k);
}
/* cleanup allocations */
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
}
#ifdef HAVE_WOLF_BIGINT
if (err == MP_OKAY)
err = wc_mp_to_bigint(&key->k, &key->k.raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.x, &key->pubkey.x->raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.y, &key->pubkey.y->raw);
if (err == MP_OKAY)
err = wc_mp_to_bigint(key->pubkey.z, &key->pubkey.z->raw);
#endif
#endif /* WOLFSSL_ATECC508A */
return err;
}
#ifdef ECC_DUMP_OID
/* Optional dump of encoded OID for adding new curves */
static int mOidDumpDone;
static void wc_ecc_dump_oids(void)
{
int x;
if (mOidDumpDone) {
return;
}
/* find matching OID sum (based on encoded value) */
for (x = 0; ecc_sets[x].size != 0; x++) {
int i;
byte* oid;
word32 oidSz, sum = 0;
printf("ECC %s (%d):\n", ecc_sets[x].name, x);
#ifdef HAVE_OID_ENCODING
byte oidEnc[ECC_MAX_OID_LEN];
oid = oidEnc;
oidSz = ECC_MAX_OID_LEN;
printf("OID: ");
for (i = 0; i < (int)ecc_sets[x].oidSz; i++) {
printf("%d.", ecc_sets[x].oid[i]);
}
printf("\n");
EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, oidEnc, &oidSz);
#else
oid = (byte*)ecc_sets[x].oid;
oidSz = ecc_sets[x].oidSz;
#endif
printf("OID Encoded: ");
for (i = 0; i < (int)oidSz; i++) {
printf("0x%02X,", oid[i]);
}
printf("\n");
for (i = 0; i < (int)oidSz; i++) {
sum += oid[i];
}
printf("Sum: %d\n", sum);
/* validate sum */
if (ecc_sets[x].oidSum != sum) {
printf(" Sum %d Not Valid!\n", ecc_sets[x].oidSum);
}
}
mOidDumpDone = 1;
}
#endif /* ECC_DUMP_OID */
WOLFSSL_ABI
ecc_key* wc_ecc_key_new(void* heap)
{
ecc_key* key;
key = (ecc_key*)XMALLOC(sizeof(ecc_key), heap, DYNAMIC_TYPE_ECC);
if (key) {
if (wc_ecc_init_ex(key, heap, INVALID_DEVID) != 0) {
XFREE(key, heap, DYNAMIC_TYPE_ECC);
key = NULL;
}
}
return key;
}
WOLFSSL_ABI
void wc_ecc_key_free(ecc_key* key)
{
if (key) {
void* heap = key->heap;
wc_ecc_free(key);
ForceZero(key, sizeof(ecc_key));
XFREE(key, heap, DYNAMIC_TYPE_ECC);
(void)heap;
}
}
/**
Make a new ECC key
rng An active RNG state
keysize The keysize for the new key (in octets from 20 to 65 bytes)
key [out] Destination of the newly created key
return MP_OKAY if successful,
upon error all allocated memory will be freed
*/
int wc_ecc_make_key(WC_RNG* rng, int keysize, ecc_key* key)
{
return wc_ecc_make_key_ex(rng, keysize, key, ECC_CURVE_DEF);
}
/* Setup dynamic pointers if using normal math for proper freeing */
WOLFSSL_ABI
int wc_ecc_init_ex(ecc_key* key, void* heap, int devId)
{
int ret = 0;
if (key == NULL) {
return BAD_FUNC_ARG;
}
#ifdef ECC_DUMP_OID
wc_ecc_dump_oids();
#endif
XMEMSET(key, 0, sizeof(ecc_key));
key->state = ECC_STATE_NONE;
#if defined(PLUTON_CRYPTO_ECC) || defined(WOLF_CRYPTO_CB)
key->devId = devId;
#else
(void)devId;
#endif
#ifdef WOLFSSL_ATECC508A
key->slot = ATECC_INVALID_SLOT;
#else
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
ret = mp_init(&key->k);
if (ret != MP_OKAY) {
return MEMORY_E;
}
#else
ret = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z,
NULL, NULL);
if (ret != MP_OKAY) {
return MEMORY_E;
}
#endif /* ALT_ECC_SIZE */
#endif /* WOLFSSL_ATECC508A */
#ifdef WOLFSSL_HEAP_TEST
key->heap = (void*)WOLFSSL_HEAP_TEST;
#else
key->heap = heap;
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
/* handle as async */
ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC,
key->heap, devId);
#endif
#if defined(WOLFSSL_DSP)
key->handle = -1;
#endif
return ret;
}
int wc_ecc_init(ecc_key* key)
{
return wc_ecc_init_ex(key, NULL, INVALID_DEVID);
}
#ifdef HAVE_PKCS11
int wc_ecc_init_id(ecc_key* key, unsigned char* id, int len, void* heap,
int devId)
{
int ret = 0;
if (key == NULL)
ret = BAD_FUNC_ARG;
if (ret == 0 && (len < 0 || len > ECC_MAX_ID_LEN))
ret = BUFFER_E;
if (ret == 0)
ret = wc_ecc_init_ex(key, heap, devId);
if (ret == 0 && id != NULL && len != 0) {
XMEMCPY(key->id, id, len);
key->idLen = len;
}
return ret;
}
#endif
int wc_ecc_set_flags(ecc_key* key, word32 flags)
{
if (key == NULL) {
return BAD_FUNC_ARG;
}
key->flags |= flags;
return 0;
}
static int wc_ecc_get_curve_order_bit_count(const ecc_set_type* dp)
{
int err;
word32 orderBits;
DECLARE_CURVE_SPECS(curve, 1);
ALLOC_CURVE_SPECS(1);
err = wc_ecc_curve_load(dp, &curve, ECC_CURVE_FIELD_ORDER);
if (err != 0) {
FREE_CURVE_SPECS();
return err;
}
orderBits = mp_count_bits(curve->order);
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return (int)orderBits;
}
#ifdef HAVE_ECC_SIGN
#ifndef NO_ASN
#if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || \
defined(WOLFSSL_CRYPTOCELL)
static int wc_ecc_sign_hash_hw(const byte* in, word32 inlen,
mp_int* r, mp_int* s, byte* out, word32 *outlen, WC_RNG* rng,
ecc_key* key)
{
int err;
#ifdef PLUTON_CRYPTO_ECC
if (key->devId != INVALID_DEVID) /* use hardware */
#endif
{
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
CRYS_ECDSA_SignUserContext_t sigCtxTemp;
word32 raw_sig_size = *outlen;
word32 msgLenInBytes = inlen;
CRYS_ECPKI_HASH_OpMode_t hash_mode;
#endif
word32 keysize = (word32)key->dp->size;
word32 orderBits = wc_ecc_get_curve_order_bit_count(key->dp);
/* Check args */
if (keysize > ECC_MAX_CRYPTO_HW_SIZE || *outlen < keysize*2) {
return ECC_BAD_ARG_E;
}
#if defined(WOLFSSL_ATECC508A)
key->slot = atmel_ecc_alloc(ATMEL_SLOT_DEVICE);
if (key->slot == ATECC_INVALID_SLOT) {
return ECC_BAD_ARG_E;
}
/* Sign: Result is 32-bytes of R then 32-bytes of S */
err = atmel_ecc_sign(key->slot, in, out);
if (err != 0) {
return err;
}
#elif defined(PLUTON_CRYPTO_ECC)
{
/* if the input is larger than curve order, we must truncate */
if ((inlen * WOLFSSL_BIT_SIZE) > orderBits) {
inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
}
/* perform ECC sign */
word32 raw_sig_size = *outlen;
err = Crypto_EccSign(in, inlen, out, &raw_sig_size);
if (err != CRYPTO_RES_SUCCESS || raw_sig_size != keysize*2){
return BAD_COND_E;
}
}
#elif defined(WOLFSSL_CRYPTOCELL)
hash_mode = cc310_hashModeECC(msgLenInBytes);
if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
hash_mode = cc310_hashModeECC(keysize);
hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
}
/* truncate if hash is longer than key size */
if (msgLenInBytes > keysize) {
msgLenInBytes = keysize;
}
/* create signature from an input buffer using a private key*/
err = CRYS_ECDSA_Sign(&wc_rndState,
wc_rndGenVectFunc,
&sigCtxTemp,
&key->ctx.privKey,
hash_mode,
(byte*)in,
msgLenInBytes,
out,
&raw_sig_size);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECDSA_Sign failed");
return err;
}
#endif
/* Load R and S */
err = mp_read_unsigned_bin(r, &out[0], keysize);
if (err != MP_OKAY) {
return err;
}
err = mp_read_unsigned_bin(s, &out[keysize], keysize);
if (err != MP_OKAY) {
return err;
}
/* Check for zeros */
if (mp_iszero(r) || mp_iszero(s)) {
return MP_ZERO_E;
}
}
#ifdef PLUTON_CRYPTO_ECC
else {
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
}
#endif
(void)rng;
return err;
}
#endif /* WOLFSSL_ATECC508A || PLUTON_CRYPTO_ECC || WOLFSSL_CRYPTOCELL */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
static int wc_ecc_sign_hash_async(const byte* in, word32 inlen, byte* out,
word32 *outlen, WC_RNG* rng, ecc_key* key)
{
int err;
mp_int *r = NULL, *s = NULL;
if (in == NULL || out == NULL || outlen == NULL || key == NULL ||
rng == NULL) {
return ECC_BAD_ARG_E;
}
err = wc_ecc_alloc_async(key);
if (err != 0) {
return err;
}
r = key->r;
s = key->s;
switch(key->state) {
case ECC_STATE_NONE:
case ECC_STATE_SIGN_DO:
key->state = ECC_STATE_SIGN_DO;
if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){
break;
}
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_SIGN_ENCODE:
key->state = ECC_STATE_SIGN_ENCODE;
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#ifdef HAVE_CAVIUM_V
/* Nitrox requires r and s in sep buffer, so split it */
NitroxEccRsSplit(key, &r->raw, &s->raw);
#endif
#ifndef WOLFSSL_ASYNC_CRYPT_TEST
/* only do this if not simulator, since it overwrites result */
wc_bigint_to_mp(&r->raw, r);
wc_bigint_to_mp(&s->raw, s);
#endif
}
/* encoded with DSA header */
err = StoreECC_DSA_Sig(out, outlen, r, s);
/* done with R/S */
mp_clear(r);
mp_clear(s);
break;
default:
err = BAD_STATE_E;
break;
}
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
key->state++;
return err;
}
/* cleanup */
wc_ecc_free_async(key);
key->state = ECC_STATE_NONE;
return err;
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
/**
Sign a message digest
in The message digest to sign
inlen The length of the digest
out [out] The destination for the signature
outlen [in/out] The max size and resulting size of the signature
key A private ECC key
return MP_OKAY if successful
*/
WOLFSSL_ABI
int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen,
WC_RNG* rng, ecc_key* key)
{
int err;
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC)
#ifdef WOLFSSL_SMALL_STACK
mp_int *r = NULL, *s = NULL;
#else
mp_int r[1], s[1];
#endif
#endif
if (in == NULL || out == NULL || outlen == NULL || key == NULL ||
rng == NULL) {
return ECC_BAD_ARG_E;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_EccSign(in, inlen, out, outlen, rng, key);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
/* handle async cases */
err = wc_ecc_sign_hash_async(in, inlen, out, outlen, rng, key);
#else
#ifdef WOLFSSL_SMALL_STACK
r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (r == NULL)
return MEMORY_E;
s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (s == NULL) {
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
XMEMSET(r, 0, sizeof(mp_int));
XMEMSET(s, 0, sizeof(mp_int));
if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* hardware crypto */
#if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) || defined(WOLFSSL_CRYPTOCELL)
err = wc_ecc_sign_hash_hw(in, inlen, r, s, out, outlen, rng, key);
#else
err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
#endif
if (err < 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* encoded with DSA header */
err = StoreECC_DSA_Sig(out, outlen, r, s);
/* cleanup */
mp_clear(r);
mp_clear(s);
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif /* WOLFSSL_ASYNC_CRYPT */
return err;
}
#endif /* !NO_ASN */
#if defined(WOLFSSL_STM32_PKA)
int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng,
ecc_key* key, mp_int *r, mp_int *s)
{
return stm32_ecc_sign_hash_ex(in, inlen, rng, key, r, s);
}
#elif !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/**
Sign a message digest
in The message digest to sign
inlen The length of the digest
key A private ECC key
r [out] The destination for r component of the signature
s [out] The destination for s component of the signature
return MP_OKAY if successful
*/
int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng,
ecc_key* key, mp_int *r, mp_int *s)
{
int err = 0;
#ifndef WOLFSSL_SP_MATH
mp_int* e;
#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)) && \
!defined(WOLFSSL_SMALL_STACK)
mp_int e_lcl;
#endif
#if defined(WOLFSSL_ECDSA_SET_K) || \
(defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
(defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)))
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#else
DECLARE_CURVE_SPECS(curve, 1);
#endif
#endif /* !WOLFSSL_SP_MATH */
if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) {
return ECC_BAD_ARG_E;
}
/* is this a private key? */
if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) {
return ECC_BAD_ARG_E;
}
/* is the IDX valid ? */
if (wc_ecc_is_valid_idx(key->idx) != 1) {
return ECC_BAD_ARG_E;
}
#ifdef WOLFSSL_SP_MATH
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL, key->heap);
#else
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL, key->heap);
#else
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
return WC_KEY_SIZE_E;
#else
#ifdef WOLFSSL_HAVE_SP_ECC
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
#endif
{
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, NULL,
key->heap);
#else
return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
#ifndef WOLFSSL_ECDSA_SET_K
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, NULL,
key->heap);
#else
return sp_ecc_sign_384(in, inlen, rng, &key->k, r, s, key->sign_k,
key->heap);
#endif
}
#endif
}
#endif /* WOLFSSL_HAVE_SP_ECC */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_SIGN)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccSign.in = in;
testDev->eccSign.inSz = inlen;
testDev->eccSign.rng = rng;
testDev->eccSign.key = key;
testDev->eccSign.r = r;
testDev->eccSign.s = s;
return WC_PENDING_E;
}
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)
err = wc_ecc_alloc_mpint(key, &key->e);
if (err != 0) {
return err;
}
e = key->e;
#elif !defined(WOLFSSL_SMALL_STACK)
e = &e_lcl;
#else
e = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (e == NULL) {
return MEMORY_E;
}
#endif
/* get the hash and load it as a bignum into 'e' */
/* init the bignums */
if ((err = mp_init(e)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(e, key->heap, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* load curve info */
#if defined(WOLFSSL_ECDSA_SET_K)
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
#else
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
(defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA))
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
}
else
#endif
{
ALLOC_CURVE_SPECS(1);
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER);
}
#endif
/* load digest into e */
if (err == MP_OKAY) {
/* we may need to truncate if hash is longer than key size */
word32 orderBits = mp_count_bits(curve->order);
/* truncate down to byte size, may be all that's needed */
if ((WOLFSSL_BIT_SIZE * inlen) > orderBits)
inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
err = mp_read_unsigned_bin(e, (byte*)in, inlen);
/* may still need bit truncation too */
if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits)
mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7));
}
/* make up a key and export the public copy */
if (err == MP_OKAY) {
int loop_check = 0;
#ifdef WOLFSSL_SMALL_STACK
ecc_key* pubkey;
#else
ecc_key pubkey[1];
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
if (NitroxEccIsCurveSupported(key))
#endif
{
word32 keySz = key->dp->size;
mp_int* k;
#ifdef HAVE_CAVIUM_V
err = wc_ecc_alloc_mpint(key, &key->signK);
if (err != 0)
return err;
k = key->signK;
#else
mp_int k_lcl;
k = &k_lcl;
#endif
err = mp_init(k);
/* make sure r and s are allocated */
#ifdef HAVE_CAVIUM_V
/* Nitrox V needs single buffer for R and S */
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2);
/* Nitrox V only needs Prime and Order */
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER));
#else
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->r->raw, key->dp->size);
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
#endif
if (err == MP_OKAY)
err = wc_bigint_alloc(&key->s->raw, key->dp->size);
/* load e and k */
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(e, &e->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz);
if (err == MP_OKAY)
err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(k, &k->raw, keySz);
#ifdef HAVE_CAVIUM_V
if (err == MP_OKAY)
err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw,
&r->raw, &s->raw, &curve->prime->raw, &curve->order->raw);
#else
if (err == MP_OKAY)
err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw,
&k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw,
&curve->prime->raw, &curve->order->raw, &curve->Gx->raw,
&curve->Gy->raw);
#endif
#ifndef HAVE_CAVIUM_V
mp_clear(e);
mp_clear(k);
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
#endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_SMALL_STACK
pubkey = (ecc_key*)XMALLOC(sizeof(ecc_key), key->heap, DYNAMIC_TYPE_ECC);
if (pubkey == NULL)
err = MEMORY_E;
#endif
/* don't use async for key, since we don't support async return here */
if (err == MP_OKAY && (err = wc_ecc_init_ex(pubkey, key->heap,
INVALID_DEVID)) == MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* b = NULL;
#else
mp_int b[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
if (err == MP_OKAY) {
b = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
DYNAMIC_TYPE_ECC);
if (b == NULL)
err = MEMORY_E;
}
#endif
if (err == MP_OKAY) {
err = mp_init(b);
}
#ifdef WOLFSSL_CUSTOM_CURVES
/* if custom curve, apply params to pubkey */
if (err == MP_OKAY && key->idx == ECC_CUSTOM_IDX) {
err = wc_ecc_set_custom_curve(pubkey, key->dp);
}
#endif
if (err == MP_OKAY) {
/* Generate blinding value - non-zero value. */
do {
if (++loop_check > 64) {
err = RNG_FAILURE_E;
break;
}
err = wc_ecc_gen_k(rng, key->dp->size, b, curve->order);
}
while (err == MP_ZERO_E);
loop_check = 0;
}
for (; err == MP_OKAY;) {
if (++loop_check > 64) {
err = RNG_FAILURE_E;
break;
}
#ifdef WOLFSSL_ECDSA_SET_K
if (key->sign_k != NULL) {
if (loop_check > 1) {
err = RNG_FAILURE_E;
break;
}
err = mp_copy(key->sign_k, &pubkey->k);
if (err != MP_OKAY) break;
mp_forcezero(key->sign_k);
mp_free(key->sign_k);
XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC);
key->sign_k = NULL;
err = wc_ecc_make_pub_ex(pubkey, curve, NULL);
}
else
#endif
{
err = wc_ecc_make_key_ex(rng, key->dp->size, pubkey,
key->dp->id);
}
if (err != MP_OKAY) break;
/* find r = x1 mod n */
err = mp_mod(pubkey->pubkey.x, curve->order, r);
if (err != MP_OKAY) break;
if (mp_iszero(r) == MP_YES) {
#ifndef ALT_ECC_SIZE
mp_clear(pubkey->pubkey.x);
mp_clear(pubkey->pubkey.y);
mp_clear(pubkey->pubkey.z);
#endif
mp_forcezero(&pubkey->k);
}
else {
/* find s = (e + xr)/k
= b.(e/k.b + x.r/k.b) */
/* k = k.b */
err = mp_mulmod(&pubkey->k, b, curve->order, &pubkey->k);
if (err != MP_OKAY) break;
/* k = 1/k.b */
err = mp_invmod(&pubkey->k, curve->order, &pubkey->k);
if (err != MP_OKAY) break;
/* s = x.r */
err = mp_mulmod(&key->k, r, curve->order, s);
if (err != MP_OKAY) break;
/* s = x.r/k.b */
err = mp_mulmod(&pubkey->k, s, curve->order, s);
if (err != MP_OKAY) break;
/* e = e/k.b */
err = mp_mulmod(&pubkey->k, e, curve->order, e);
if (err != MP_OKAY) break;
/* s = e/k.b + x.r/k.b
= (e + x.r)/k.b */
err = mp_add(e, s, s);
if (err != MP_OKAY) break;
/* s = b.(e + x.r)/k.b
= (e + x.r)/k */
err = mp_mulmod(s, b, curve->order, s);
if (err != MP_OKAY) break;
/* s = (e + xr)/k */
err = mp_mod(s, curve->order, s);
if (err != MP_OKAY) break;
if (mp_iszero(s) == MP_NO)
break;
}
}
mp_clear(b);
mp_free(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
wc_ecc_free(pubkey);
#ifdef WOLFSSL_SMALL_STACK
XFREE(pubkey, key->heap, DYNAMIC_TYPE_ECC);
#endif
}
}
mp_clear(e);
wc_ecc_curve_free(curve);
#ifdef WOLFSSL_SMALL_STACK
XFREE(e, key->heap, DYNAMIC_TYPE_ECC);
#endif
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
return err;
}
#ifdef WOLFSSL_ECDSA_SET_K
int wc_ecc_sign_set_k(const byte* k, word32 klen, ecc_key* key)
{
int ret = 0;
if (k == NULL || klen == 0 || key == NULL) {
ret = BAD_FUNC_ARG;
}
if (ret == 0) {
if (key->sign_k == NULL) {
key->sign_k = (mp_int*)XMALLOC(sizeof(mp_int), key->heap,
DYNAMIC_TYPE_ECC);
if (key->sign_k == NULL) {
ret = MEMORY_E;
}
}
}
if (ret == 0) {
ret = mp_init(key->sign_k);
}
if (ret == 0) {
ret = mp_read_unsigned_bin(key->sign_k, k, klen);
}
return ret;
}
#endif /* WOLFSSL_ECDSA_SET_K */
#endif /* WOLFSSL_ATECC508A && WOLFSSL_CRYPTOCELL*/
#endif /* HAVE_ECC_SIGN */
#ifdef WOLFSSL_CUSTOM_CURVES
void wc_ecc_free_curve(const ecc_set_type* curve, void* heap)
{
#ifndef WOLFSSL_ECC_CURVE_STATIC
if (curve->prime != NULL)
XFREE((void*)curve->prime, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Af != NULL)
XFREE((void*)curve->Af, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Bf != NULL)
XFREE((void*)curve->Bf, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->order != NULL)
XFREE((void*)curve->order, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Gx != NULL)
XFREE((void*)curve->Gx, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (curve->Gy != NULL)
XFREE((void*)curve->Gy, heap, DYNAMIC_TYPE_ECC_BUFFER);
#endif
XFREE((void*)curve, heap, DYNAMIC_TYPE_ECC_BUFFER);
(void)heap;
}
#endif /* WOLFSSL_CUSTOM_CURVES */
/**
Free an ECC key from memory
key The key you wish to free
*/
WOLFSSL_ABI
int wc_ecc_free(ecc_key* key)
{
if (key == NULL) {
return 0;
}
#ifdef WOLFSSL_ECDSA_SET_K
if (key->sign_k != NULL) {
mp_forcezero(key->sign_k);
mp_free(key->sign_k);
XFREE(key->sign_k, key->heap, DYNAMIC_TYPE_ECC);
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
#ifdef WC_ASYNC_ENABLE_ECC
wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC);
#endif
wc_ecc_free_async(key);
#endif
#ifdef WOLFSSL_ATECC508A
atmel_ecc_free(key->slot);
key->slot = ATECC_INVALID_SLOT;
#endif /* WOLFSSL_ATECC508A */
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_forcezero(&key->k);
#ifdef WOLFSSL_CUSTOM_CURVES
if (key->deallocSet && key->dp != NULL)
wc_ecc_free_curve(key->dp, key->heap);
#endif
return 0;
}
#if !defined(WOLFSSL_SP_MATH) && !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifdef ECC_SHAMIR
/** Computes kA*A + kB*B = C using Shamir's Trick
A First point to multiply
kA What to multiple A by
B Second point to multiply
kB What to multiple B by
C [out] Destination point (can overlap with A or B)
a ECC curve parameter a
modulus Modulus for curve
return MP_OKAY on success
*/
#ifdef FP_ECC
static int normal_ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus,
void* heap)
#else
int ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus,
void* heap)
#endif
{
#ifdef WOLFSSL_SMALL_STACK
ecc_point** precomp = NULL;
#ifdef WOLFSSL_SMALL_STACK_CACHE
ecc_key key;
#endif
#else
ecc_point* precomp[SHAMIR_PRECOMP_SZ];
#endif
unsigned bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble;
unsigned char* tA;
unsigned char* tB;
int err = MP_OKAY, first, x, y;
mp_digit mp = 0;
/* argchks */
if (A == NULL || kA == NULL || B == NULL || kB == NULL || C == NULL ||
modulus == NULL) {
return ECC_BAD_ARG_E;
}
/* allocate memory */
tA = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (tA == NULL) {
return GEN_MEM_ERR;
}
tB = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER);
if (tB == NULL) {
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return GEN_MEM_ERR;
}
#ifdef WOLFSSL_SMALL_STACK
precomp = (ecc_point**)XMALLOC(sizeof(ecc_point*) * SHAMIR_PRECOMP_SZ, heap,
DYNAMIC_TYPE_ECC_BUFFER);
if (precomp == NULL) {
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return GEN_MEM_ERR;
}
#endif
#ifdef WOLFSSL_SMALL_STACK_CACHE
key.t1 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.t2 = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#ifdef ALT_ECC_SIZE
key.x = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.y = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
key.z = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
#endif
if (key.t1 == NULL || key.t2 == NULL
#ifdef ALT_ECC_SIZE
|| key.x == NULL || key.y == NULL || key.z == NULL
#endif
) {
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
XFREE(precomp, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
C->key = &key;
#endif /* WOLFSSL_SMALL_STACK_CACHE */
/* init variables */
XMEMSET(tA, 0, ECC_BUFSIZE);
XMEMSET(tB, 0, ECC_BUFSIZE);
#ifndef WOLFSSL_SMALL_STACK
XMEMSET(precomp, 0, sizeof(precomp));
#else
XMEMSET(precomp, 0, sizeof(ecc_point*) * SHAMIR_PRECOMP_SZ);
#endif
/* get sizes */
lenA = mp_unsigned_bin_size(kA);
lenB = mp_unsigned_bin_size(kB);
len = MAX(lenA, lenB);
/* sanity check */
if ((lenA > ECC_BUFSIZE) || (lenB > ECC_BUFSIZE)) {
err = BAD_FUNC_ARG;
}
if (err == MP_OKAY) {
/* extract and justify kA */
err = mp_to_unsigned_bin(kA, (len - lenA) + tA);
/* extract and justify kB */
if (err == MP_OKAY)
err = mp_to_unsigned_bin(kB, (len - lenB) + tB);
/* allocate the table */
if (err == MP_OKAY) {
for (x = 0; x < SHAMIR_PRECOMP_SZ; x++) {
precomp[x] = wc_ecc_new_point_h(heap);
if (precomp[x] == NULL) {
err = GEN_MEM_ERR;
break;
}
#ifdef WOLFSSL_SMALL_STACK_CACHE
precomp[x]->key = &key;
#endif
}
}
}
if (err == MP_OKAY)
/* init montgomery reduction */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
mp_int* mu;
#else
mp_int mu[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
mu = (mp_int*)XMALLOC(sizeof(mp_int), heap, DYNAMIC_TYPE_ECC);
if (mu == NULL)
err = MEMORY_E;
#endif
if (err == MP_OKAY) {
err = mp_init(mu);
}
if (err == MP_OKAY) {
err = mp_montgomery_calc_normalization(mu, modulus);
if (err == MP_OKAY)
/* copy ones ... */
err = mp_mulmod(A->x, mu, modulus, precomp[1]->x);
if (err == MP_OKAY)
err = mp_mulmod(A->y, mu, modulus, precomp[1]->y);
if (err == MP_OKAY)
err = mp_mulmod(A->z, mu, modulus, precomp[1]->z);
if (err == MP_OKAY)
err = mp_mulmod(B->x, mu, modulus, precomp[1<<2]->x);
if (err == MP_OKAY)
err = mp_mulmod(B->y, mu, modulus, precomp[1<<2]->y);
if (err == MP_OKAY)
err = mp_mulmod(B->z, mu, modulus, precomp[1<<2]->z);
/* done with mu */
mp_clear(mu);
}
#ifdef WOLFSSL_SMALL_STACK
if (mu != NULL) {
XFREE(mu, heap, DYNAMIC_TYPE_ECC);
}
#endif
}
if (err == MP_OKAY)
/* precomp [i,0](A + B) table */
err = ecc_projective_dbl_point(precomp[1], precomp[2], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_add_point(precomp[1], precomp[2], precomp[3],
a, modulus, mp);
if (err == MP_OKAY)
/* precomp [0,i](A + B) table */
err = ecc_projective_dbl_point(precomp[1<<2], precomp[2<<2], a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_add_point(precomp[1<<2], precomp[2<<2], precomp[3<<2],
a, modulus, mp);
if (err == MP_OKAY) {
/* precomp [i,j](A + B) table (i != 0, j != 0) */
for (x = 1; x < 4; x++) {
for (y = 1; y < 4; y++) {
if (err == MP_OKAY) {
err = ecc_projective_add_point(precomp[x], precomp[(y<<2)],
precomp[x+(y<<2)], a, modulus, mp);
}
}
}
}
if (err == MP_OKAY) {
nibble = 3;
first = 1;
bitbufA = tA[0];
bitbufB = tB[0];
/* for every byte of the multiplicands */
for (x = 0;; ) {
/* grab a nibble */
if (++nibble == 4) {
if (x == (int)len) break;
bitbufA = tA[x];
bitbufB = tB[x];
nibble = 0;
x++;
}
/* extract two bits from both, shift/update */
nA = (bitbufA >> 6) & 0x03;
nB = (bitbufB >> 6) & 0x03;
bitbufA = (bitbufA << 2) & 0xFF;
bitbufB = (bitbufB << 2) & 0xFF;
/* if both zero, if first, continue */
if ((nA == 0) && (nB == 0) && (first == 1)) {
continue;
}
/* double twice, only if this isn't the first */
if (first == 0) {
/* double twice */
if (err == MP_OKAY)
err = ecc_projective_dbl_point(C, C, a, modulus, mp);
if (err == MP_OKAY)
err = ecc_projective_dbl_point(C, C, a, modulus, mp);
else
break;
}
/* if not both zero */
if ((nA != 0) || (nB != 0)) {
if (first == 1) {
/* if first, copy from table */
first = 0;
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->x, C->x);
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->y, C->y);
if (err == MP_OKAY)
err = mp_copy(precomp[nA + (nB<<2)]->z, C->z);
else
break;
} else {
/* if not first, add from table */
if (err == MP_OKAY)
err = ecc_projective_add_point(C, precomp[nA + (nB<<2)], C,
a, modulus, mp);
if (err != MP_OKAY)
break;
if (mp_iszero(C->z)) {
/* When all zero then should have done an add */
if (mp_iszero(C->x) && mp_iszero(C->y)) {
err = ecc_projective_dbl_point(precomp[nA + (nB<<2)], C,
a, modulus, mp);
if (err != MP_OKAY)
break;
}
/* When only Z zero then result is infinity */
else {
err = mp_set(C->x, 0);
if (err != MP_OKAY)
break;
err = mp_set(C->y, 0);
if (err != MP_OKAY)
break;
err = mp_set(C->z, 1);
if (err != MP_OKAY)
break;
first = 1;
}
}
}
}
}
}
/* reduce to affine */
if (err == MP_OKAY)
err = ecc_map(C, modulus, mp);
/* clean up */
for (x = 0; x < SHAMIR_PRECOMP_SZ; x++) {
wc_ecc_del_point_h(precomp[x], heap);
}
ForceZero(tA, ECC_BUFSIZE);
ForceZero(tB, ECC_BUFSIZE);
#ifdef WOLFSSL_SMALL_STACK_CACHE
#ifdef ALT_ECC_SIZE
XFREE(key.z, heap, DYNAMIC_TYPE_ECC);
XFREE(key.y, heap, DYNAMIC_TYPE_ECC);
XFREE(key.x, heap, DYNAMIC_TYPE_ECC);
#endif
XFREE(key.t2, heap, DYNAMIC_TYPE_ECC);
XFREE(key.t1, heap, DYNAMIC_TYPE_ECC);
C->key = NULL;
#endif
#ifdef WOLFSSL_SMALL_STACK
XFREE(precomp, heap, DYNAMIC_TYPE_ECC_BUFFER);
#endif
XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER);
return err;
}
#endif /* ECC_SHAMIR */
#endif /* !WOLFSSL_SP_MATH && !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCEL*/
#ifdef HAVE_ECC_VERIFY
#ifndef NO_ASN
/* verify
*
* w = s^-1 mod n
* u1 = xw
* u2 = rw
* X = u1*G + u2*Q
* v = X_x1 mod n
* accept if v == r
*/
/**
Verify an ECC signature
sig The signature to verify
siglen The length of the signature (octets)
hash The hash (message digest) that was signed
hashlen The length of the hash (octets)
res Result of signature, 1==valid, 0==invalid
key The corresponding public ECC key
return MP_OKAY if successful (even if the signature is not valid)
*/
int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash,
word32 hashlen, int* res, ecc_key* key)
{
int err;
mp_int *r = NULL, *s = NULL;
#if (!defined(WOLFSSL_ASYNC_CRYPT) || !defined(WC_ASYNC_ENABLE_ECC)) && \
!defined(WOLFSSL_SMALL_STACK)
mp_int r_lcl, s_lcl;
#endif
if (sig == NULL || hash == NULL || res == NULL || key == NULL) {
return ECC_BAD_ARG_E;
}
#ifdef WOLF_CRYPTO_CB
if (key->devId != INVALID_DEVID) {
err = wc_CryptoCb_EccVerify(sig, siglen, hash, hashlen, res, key);
if (err != CRYPTOCB_UNAVAILABLE)
return err;
/* fall-through when unavailable */
}
#endif
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
err = wc_ecc_alloc_async(key);
if (err != 0)
return err;
r = key->r;
s = key->s;
#else
#ifndef WOLFSSL_SMALL_STACK
r = &r_lcl;
s = &s_lcl;
#else
r = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (r == NULL)
return MEMORY_E;
s = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (s == NULL) {
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
XMEMSET(r, 0, sizeof(mp_int));
XMEMSET(s, 0, sizeof(mp_int));
#endif /* WOLFSSL_ASYNC_CRYPT */
switch (key->state) {
case ECC_STATE_NONE:
case ECC_STATE_VERIFY_DECODE:
key->state = ECC_STATE_VERIFY_DECODE;
/* default to invalid signature */
*res = 0;
/* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s.
* If either of those don't allocate correctly, none of
* the rest of this function will execute, and everything
* gets cleaned up at the end. */
/* decode DSA header */
err = DecodeECC_DSA_Sig(sig, siglen, r, s);
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_VERIFY_DO:
key->state = ECC_STATE_VERIFY_DO;
err = wc_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
#ifndef WOLFSSL_ASYNC_CRYPT
/* done with R/S */
mp_clear(r);
mp_clear(s);
#ifdef WOLFSSL_SMALL_STACK
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
r = NULL;
s = NULL;
#endif
#endif
if (err < 0) {
break;
}
FALL_THROUGH;
case ECC_STATE_VERIFY_RES:
key->state = ECC_STATE_VERIFY_RES;
err = 0;
break;
default:
err = BAD_STATE_E;
}
/* if async pending then return and skip done cleanup below */
if (err == WC_PENDING_E) {
key->state++;
return err;
}
/* cleanup */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
wc_ecc_free_async(key);
#elif defined(WOLFSSL_SMALL_STACK)
XFREE(s, key->heap, DYNAMIC_TYPE_ECC);
XFREE(r, key->heap, DYNAMIC_TYPE_ECC);
r = NULL;
s = NULL;
#endif
key->state = ECC_STATE_NONE;
return err;
}
#endif /* !NO_ASN */
/**
Verify an ECC signature
r The signature R component to verify
s The signature S component to verify
hash The hash (message digest) that was signed
hashlen The length of the hash (octets)
res Result of signature, 1==valid, 0==invalid
key The corresponding public ECC key
return MP_OKAY if successful (even if the signature is not valid)
*/
int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash,
word32 hashlen, int* res, ecc_key* key)
#if defined(WOLFSSL_STM32_PKA)
{
return stm32_ecc_verify_hash_ex(r, s, hash, hashlen, res, key);
}
#else
{
int err;
word32 keySz;
#ifdef WOLFSSL_ATECC508A
byte sigRS[ATECC_KEY_SIZE*2];
#elif defined(WOLFSSL_CRYPTOCELL)
byte sigRS[ECC_MAX_CRYPTO_HW_SIZE*2];
CRYS_ECDSA_VerifyUserContext_t sigCtxTemp;
word32 msgLenInBytes = hashlen;
CRYS_ECPKI_HASH_OpMode_t hash_mode;
#elif !defined(WOLFSSL_SP_MATH) || defined(FREESCALE_LTC_ECC)
int did_init = 0;
ecc_point *mG = NULL, *mQ = NULL;
#ifdef WOLFSSL_SMALL_STACK
mp_int* v = NULL;
mp_int* w = NULL;
mp_int* u1 = NULL;
mp_int* u2 = NULL;
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
mp_int* e_lcl = NULL;
#endif
#else /* WOLFSSL_SMALL_STACK */
mp_int v[1];
mp_int w[1];
mp_int u1[1];
mp_int u2[1];
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
mp_int e_lcl[1];
#endif
#endif /* WOLFSSL_SMALL_STACK */
mp_int* e;
DECLARE_CURVE_SPECS(curve, ECC_CURVE_FIELD_COUNT);
#endif
if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL)
return ECC_BAD_ARG_E;
/* default to invalid signature */
*res = 0;
/* is the IDX valid ? */
if (wc_ecc_is_valid_idx(key->idx) != 1) {
return ECC_BAD_ARG_E;
}
keySz = key->dp->size;
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \
defined(WOLFSSL_ASYNC_CRYPT_TEST)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_VERIFY)) {
WC_ASYNC_TEST* testDev = &key->asyncDev.test;
testDev->eccVerify.r = r;
testDev->eccVerify.s = s;
testDev->eccVerify.hash = hash;
testDev->eccVerify.hashlen = hashlen;
testDev->eccVerify.stat = res;
testDev->eccVerify.key = key;
return WC_PENDING_E;
}
}
#endif
#ifdef WOLFSSL_ATECC508A
/* Extract R and S */
err = mp_to_unsigned_bin(r, &sigRS[0]);
if (err != MP_OKAY) {
return err;
}
err = mp_to_unsigned_bin(s, &sigRS[keySz]);
if (err != MP_OKAY) {
return err;
}
err = atmel_ecc_verify(hash, sigRS, key->pubkey_raw, res);
if (err != 0) {
return err;
}
(void)hashlen;
#elif defined(WOLFSSL_CRYPTOCELL)
/* Extract R and S */
err = mp_to_unsigned_bin(r, &sigRS[0]);
if (err != MP_OKAY) {
return err;
}
err = mp_to_unsigned_bin(s, &sigRS[keySz]);
if (err != MP_OKAY) {
return err;
}
hash_mode = cc310_hashModeECC(msgLenInBytes);
if (hash_mode == CRYS_ECPKI_HASH_OpModeLast) {
/* hash_mode = */ cc310_hashModeECC(keySz);
hash_mode = CRYS_ECPKI_HASH_SHA256_mode;
}
/* truncate if hash is longer than key size */
if (msgLenInBytes > keySz) {
msgLenInBytes = keySz;
}
/* verify the signature using the public key */
err = CRYS_ECDSA_Verify(&sigCtxTemp,
&key->ctx.pubKey,
hash_mode,
&sigRS[0],
keySz*2,
(byte*)hash,
msgLenInBytes);
if (err != SA_SILIB_RET_OK) {
WOLFSSL_MSG("CRYS_ECDSA_Verify failed");
return err;
}
/* valid signature if we get to this point */
*res = 1;
#else
/* checking if private key with no public part */
if (key->type == ECC_PRIVATEKEY_ONLY) {
WOLFSSL_MSG("Verify called with private key, generating public part");
err = wc_ecc_make_pub_ex(key, NULL, NULL);
if (err != MP_OKAY) {
WOLFSSL_MSG("Unable to extract public key");
return err;
}
}
#if defined(WOLFSSL_DSP) && !defined(FREESCALE_LTC_ECC)
if (key->handle != -1) {
return sp_dsp_ecc_verify_256(key->handle, hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
if (wolfSSL_GetHandleCbSet() == 1) {
return sp_dsp_ecc_verify_256(0, hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
#if defined(WOLFSSL_SP_MATH) && !defined(FREESCALE_LTC_ECC)
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
return sp_ecc_verify_384(hash, hashlen, key->pubkey.x, key->pubkey.y,
key->pubkey.z, r, s, res, key->heap);
}
#endif
return WC_KEY_SIZE_E;
#else
#if defined WOLFSSL_HAVE_SP_ECC && !defined(FREESCALE_LTC_ECC)
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC)
#endif
{
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
return sp_ecc_verify_256(hash, hashlen, key->pubkey.x,
key->pubkey.y, key->pubkey.z,r, s, res,
key->heap);
}
#endif /* WOLFSSL_SP_NO_256 */
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
return sp_ecc_verify_384(hash, hashlen, key->pubkey.x,
key->pubkey.y, key->pubkey.z,r, s, res,
key->heap);
}
#endif /* WOLFSSL_SP_384 */
}
#endif /* WOLFSSL_HAVE_SP_ECC */
ALLOC_CURVE_SPECS(ECC_CURVE_FIELD_COUNT);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V)
err = wc_ecc_alloc_mpint(key, &key->e);
if (err != 0) {
FREE_CURVE_SPECS();
return err;
}
e = key->e;
#else
#ifdef WOLFSSL_SMALL_STACK
e_lcl = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (e_lcl == NULL) {
FREE_CURVE_SPECS();
return MEMORY_E;
}
#endif
e = e_lcl;
#endif /* WOLFSSL_ASYNC_CRYPT && HAVE_CAVIUM_V */
err = mp_init(e);
if (err != MP_OKAY)
return MEMORY_E;
/* read in the specs for this curve */
err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL);
/* check for zero */
if (err == MP_OKAY) {
if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES ||
mp_cmp(r, curve->order) != MP_LT ||
mp_cmp(s, curve->order) != MP_LT) {
err = MP_ZERO_E;
}
}
/* read hash */
if (err == MP_OKAY) {
/* we may need to truncate if hash is longer than key size */
unsigned int orderBits = mp_count_bits(curve->order);
/* truncate down to byte size, may be all that's needed */
if ( (WOLFSSL_BIT_SIZE * hashlen) > orderBits)
hashlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
err = mp_read_unsigned_bin(e, hash, hashlen);
/* may still need bit truncation too */
if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * hashlen) > orderBits)
mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7));
}
/* check for async hardware acceleration */
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) {
#if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA)
#ifdef HAVE_CAVIUM_V
if (NitroxEccIsCurveSupported(key))
#endif
{
err = wc_mp_to_bigint_sz(e, &e->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(key->pubkey.x, &key->pubkey.x->raw, keySz);
if (err == MP_OKAY)
err = wc_mp_to_bigint_sz(key->pubkey.y, &key->pubkey.y->raw, keySz);
if (err == MP_OKAY)
#ifdef HAVE_CAVIUM_V
err = NitroxEcdsaVerify(key, &e->raw, &key->pubkey.x->raw,
&key->pubkey.y->raw, &r->raw, &s->raw,
&curve->prime->raw, &curve->order->raw, res);
#else
err = IntelQaEcdsaVerify(&key->asyncDev, &e->raw, &key->pubkey.x->raw,
&key->pubkey.y->raw, &r->raw, &s->raw, &curve->Af->raw,
&curve->Bf->raw, &curve->prime->raw, &curve->order->raw,
&curve->Gx->raw, &curve->Gy->raw, res);
#endif
#ifndef HAVE_CAVIUM_V
mp_clear(e);
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
return err;
}
#endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */
}
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_ECC */
#ifdef WOLFSSL_SMALL_STACK
if (err == MP_OKAY) {
v = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (v == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
w = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (w == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
u1 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (u1 == NULL)
err = MEMORY_E;
}
if (err == MP_OKAY) {
u2 = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (u2 == NULL)
err = MEMORY_E;
}
#endif
/* allocate ints */
if (err == MP_OKAY) {
if ((err = mp_init_multi(v, w, u1, u2, NULL, NULL)) != MP_OKAY) {
err = MEMORY_E;
}
did_init = 1;
}
/* allocate points */
if (err == MP_OKAY) {
mG = wc_ecc_new_point_h(key->heap);
mQ = wc_ecc_new_point_h(key->heap);
if (mQ == NULL || mG == NULL)
err = MEMORY_E;
}
/* w = s^-1 mod n */
if (err == MP_OKAY)
err = mp_invmod(s, curve->order, w);
/* u1 = ew */
if (err == MP_OKAY)
err = mp_mulmod(e, w, curve->order, u1);
/* u2 = rw */
if (err == MP_OKAY)
err = mp_mulmod(r, w, curve->order, u2);
/* find mG and mQ */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, mG->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, mG->y);
if (err == MP_OKAY)
err = mp_set(mG->z, 1);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.x, mQ->x);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.y, mQ->y);
if (err == MP_OKAY)
err = mp_copy(key->pubkey.z, mQ->z);
#if defined(FREESCALE_LTC_ECC)
/* use PKHA to compute u1*mG + u2*mQ */
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0, key->heap);
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap);
if (err == MP_OKAY)
err = wc_ecc_point_add(mG, mQ, mG, curve->prime);
#else
#ifndef ECC_SHAMIR
if (err == MP_OKAY)
{
mp_digit mp = 0;
if (!mp_iszero(u1)) {
/* compute u1*mG + u2*mQ = mG */
err = wc_ecc_mulmod_ex(u1, mG, mG, curve->Af, curve->prime, 0,
key->heap);
if (err == MP_OKAY) {
err = wc_ecc_mulmod_ex(u2, mQ, mQ, curve->Af, curve->prime, 0,
key->heap);
}
/* find the montgomery mp */
if (err == MP_OKAY)
err = mp_montgomery_setup(curve->prime, &mp);
/* add them */
if (err == MP_OKAY)
err = ecc_projective_add_point(mQ, mG, mG, curve->Af,
curve->prime, mp);
if (err == MP_OKAY && mp_iszero(mG->z)) {
/* When all zero then should have done an add */
if (mp_iszero(mG->x) && mp_iszero(mG->y)) {
err = ecc_projective_dbl_point(mQ, mG, curve->Af,
curve->prime, mp);
}
/* When only Z zero then result is infinity */
else {
err = mp_set(mG->x, 0);
if (err == MP_OKAY)
err = mp_set(mG->y, 0);
if (err == MP_OKAY)
err = mp_set(mG->z, 1);
}
}
}
else {
/* compute 0*mG + u2*mQ = mG */
err = wc_ecc_mulmod_ex(u2, mQ, mG, curve->Af, curve->prime, 0,
key->heap);
/* find the montgomery mp */
if (err == MP_OKAY)
err = mp_montgomery_setup(curve->prime, &mp);
}
/* reduce */
if (err == MP_OKAY)
err = ecc_map(mG, curve->prime, mp);
}
#else
/* use Shamir's trick to compute u1*mG + u2*mQ using half the doubles */
if (err == MP_OKAY) {
err = ecc_mul2add(mG, u1, mQ, u2, mG, curve->Af, curve->prime,
key->heap);
}
#endif /* ECC_SHAMIR */
#endif /* FREESCALE_LTC_ECC */
/* v = X_x1 mod n */
if (err == MP_OKAY)
err = mp_mod(mG->x, curve->order, v);
/* does v == r */
if (err == MP_OKAY) {
if (mp_cmp(v, r) == MP_EQ)
*res = 1;
}
/* cleanup */
wc_ecc_del_point_h(mG, key->heap);
wc_ecc_del_point_h(mQ, key->heap);
mp_clear(e);
if (did_init) {
mp_clear(v);
mp_clear(w);
mp_clear(u1);
mp_clear(u2);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(u2, key->heap, DYNAMIC_TYPE_ECC);
XFREE(u1, key->heap, DYNAMIC_TYPE_ECC);
XFREE(w, key->heap, DYNAMIC_TYPE_ECC);
XFREE(v, key->heap, DYNAMIC_TYPE_ECC);
#if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V)
XFREE(e_lcl, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_SP_MATH */
#endif /* WOLFSSL_ATECC508A */
(void)keySz;
(void)hashlen;
return err;
}
#endif /* WOLFSSL_STM32_PKA */
#endif /* HAVE_ECC_VERIFY */
#ifdef HAVE_ECC_KEY_IMPORT
/* import point from der */
int wc_ecc_import_point_der(byte* in, word32 inLen, const int curve_idx,
ecc_point* point)
{
int err = 0;
int compressed = 0;
int keysize;
byte pointType;
if (in == NULL || point == NULL || (curve_idx < 0) ||
(wc_ecc_is_valid_idx(curve_idx) == 0))
return ECC_BAD_ARG_E;
/* must be odd */
if ((inLen & 1) == 0) {
return ECC_BAD_ARG_E;
}
/* init point */
#ifdef ALT_ECC_SIZE
point->x = (mp_int*)&point->xyz[0];
point->y = (mp_int*)&point->xyz[1];
point->z = (mp_int*)&point->xyz[2];
alt_fp_init(point->x);
alt_fp_init(point->y);
alt_fp_init(point->z);
#else
err = mp_init_multi(point->x, point->y, point->z, NULL, NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* check for point type (4, 2, or 3) */
pointType = in[0];
if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN &&
pointType != ECC_POINT_COMP_ODD) {
err = ASN_PARSE_E;
}
if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) {
#ifdef HAVE_COMP_KEY
compressed = 1;
#else
err = NOT_COMPILED_IN;
#endif
}
/* adjust to skip first byte */
inLen -= 1;
in += 1;
/* calculate key size based on inLen / 2 */
keysize = inLen>>1;
/* read data */
if (err == MP_OKAY)
err = mp_read_unsigned_bin(point->x, (byte*)in, keysize);
#ifdef HAVE_COMP_KEY
if (err == MP_OKAY && compressed == 1) { /* build y */
#ifndef WOLFSSL_SP_MATH
int did_init = 0;
mp_int t1, t2;
DECLARE_CURVE_SPECS(curve, 3);
ALLOC_CURVE_SPECS(3);
if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
err = MEMORY_E;
else
did_init = 1;
/* load curve info */
if (err == MP_OKAY)
err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
ECC_CURVE_FIELD_BF));
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(point->x, &t1);
if (err == MP_OKAY)
err = mp_mulmod(&t1, point->x, curve->prime, &t1);
/* compute x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(curve->Af, point->x, curve->prime, &t2);
if (err == MP_OKAY)
err = mp_add(&t1, &t2, &t1);
/* compute x^3 + a*x + b */
if (err == MP_OKAY)
err = mp_add(&t1, curve->Bf, &t1);
/* compute sqrt(x^3 + a*x + b) */
if (err == MP_OKAY)
err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
/* adjust y */
if (err == MP_OKAY) {
if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
(mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) {
err = mp_mod(&t2, curve->prime, point->y);
}
else {
err = mp_submod(curve->prime, &t2, curve->prime, point->y);
}
}
if (did_init) {
mp_clear(&t2);
mp_clear(&t1);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#else
#ifndef WOLFSSL_SP_NO_256
if (curve_idx != ECC_CUSTOM_IDX &&
ecc_sets[curve_idx].id == ECC_SECP256R1) {
sp_ecc_uncompress_256(point->x, pointType, point->y);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (curve_idx != ECC_CUSTOM_IDX &&
ecc_sets[curve_idx].id == ECC_SECP384R1) {
sp_ecc_uncompress_384(point->x, pointType, point->y);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
}
#endif
if (err == MP_OKAY && compressed == 0)
err = mp_read_unsigned_bin(point->y, (byte*)in + keysize, keysize);
if (err == MP_OKAY)
err = mp_set(point->z, 1);
if (err != MP_OKAY) {
mp_clear(point->x);
mp_clear(point->y);
mp_clear(point->z);
}
return err;
}
#endif /* HAVE_ECC_KEY_IMPORT */
#ifdef HAVE_ECC_KEY_EXPORT
/* export point to der */
int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out,
word32* outLen)
{
int ret = MP_OKAY;
word32 numlen;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_BUFSIZE];
#endif
if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0))
return ECC_BAD_ARG_E;
/* return length needed only */
if (point != NULL && out == NULL && outLen != NULL) {
numlen = ecc_sets[curve_idx].size;
*outLen = 1 + 2*numlen;
return LENGTH_ONLY_E;
}
if (point == NULL || out == NULL || outLen == NULL)
return ECC_BAD_ARG_E;
numlen = ecc_sets[curve_idx].size;
if (*outLen < (1 + 2*numlen)) {
*outLen = 1 + 2*numlen;
return BUFFER_E;
}
/* store byte point type */
out[0] = ECC_POINT_UNCOMP;
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/* pad and store x */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(point->x, buf +
(numlen - mp_unsigned_bin_size(point->x)));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1, buf, numlen);
/* pad and store y */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(point->y, buf +
(numlen - mp_unsigned_bin_size(point->y)));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1+numlen, buf, numlen);
*outLen = 1 + 2*numlen;
done:
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* export public ECC key in ANSI X9.63 format */
int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen)
{
int ret = MP_OKAY;
word32 numlen;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_BUFSIZE];
#endif
word32 pubxlen, pubylen;
/* return length needed only */
if (key != NULL && out == NULL && outLen != NULL) {
/* if key hasn't been setup assume max bytes for size estimation */
numlen = key->dp ? key->dp->size : MAX_ECC_BYTES;
*outLen = 1 + 2*numlen;
return LENGTH_ONLY_E;
}
if (key == NULL || out == NULL || outLen == NULL)
return ECC_BAD_ARG_E;
if (key->type == ECC_PRIVATEKEY_ONLY)
return ECC_PRIVATEONLY_E;
if (wc_ecc_is_valid_idx(key->idx) == 0 || key->dp == NULL) {
return ECC_BAD_ARG_E;
}
numlen = key->dp->size;
/* verify room in out buffer */
if (*outLen < (1 + 2*numlen)) {
*outLen = 1 + 2*numlen;
return BUFFER_E;
}
/* verify public key length is less than key size */
pubxlen = mp_unsigned_bin_size(key->pubkey.x);
pubylen = mp_unsigned_bin_size(key->pubkey.y);
if ((pubxlen > numlen) || (pubylen > numlen)) {
WOLFSSL_MSG("Public key x/y invalid!");
return BUFFER_E;
}
/* store byte point type */
out[0] = ECC_POINT_UNCOMP;
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/* pad and store x */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - pubxlen));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1, buf, numlen);
/* pad and store y */
XMEMSET(buf, 0, ECC_BUFSIZE);
ret = mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - pubylen));
if (ret != MP_OKAY)
goto done;
XMEMCPY(out+1+numlen, buf, numlen);
*outLen = 1 + 2*numlen;
done:
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* export public ECC key in ANSI X9.63 format, extended with
* compression option */
int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen,
int compressed)
{
if (compressed == 0)
return wc_ecc_export_x963(key, out, outLen);
#ifdef HAVE_COMP_KEY
else
return wc_ecc_export_x963_compressed(key, out, outLen);
#else
return NOT_COMPILED_IN;
#endif
}
#endif /* HAVE_ECC_KEY_EXPORT */
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
/* is ecc point on curve described by dp ? */
int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime)
{
#ifndef WOLFSSL_SP_MATH
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* t1;
mp_int* t2;
#else
mp_int t1[1], t2[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
t1 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t1 == NULL)
return MEMORY_E;
t2 = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (t2 == NULL) {
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
if ((err = mp_init_multi(t1, t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/* compute y^2 */
if (err == MP_OKAY)
err = mp_sqr(ecp->y, t1);
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(ecp->x, t2);
if (err == MP_OKAY)
err = mp_mod(t2, prime, t2);
if (err == MP_OKAY)
err = mp_mul(ecp->x, t2, t2);
/* compute y^2 - x^3 */
if (err == MP_OKAY)
err = mp_sub(t1, t2, t1);
/* Determine if curve "a" should be used in calc */
#ifdef WOLFSSL_CUSTOM_CURVES
if (err == MP_OKAY) {
/* Use a and prime to determine if a == 3 */
err = mp_set(t2, 0);
if (err == MP_OKAY)
err = mp_submod(prime, a, prime, t2);
}
if (err == MP_OKAY && mp_cmp_d(t2, 3) != MP_EQ) {
/* compute y^2 - x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(t2, ecp->x, prime, t2);
if (err == MP_OKAY)
err = mp_addmod(t1, t2, prime, t1);
}
else
#endif /* WOLFSSL_CUSTOM_CURVES */
{
/* assumes "a" == 3 */
(void)a;
/* compute y^2 - x^3 + 3x */
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_add(t1, ecp->x, t1);
if (err == MP_OKAY)
err = mp_mod(t1, prime, t1);
}
/* adjust range (0, prime) */
while (err == MP_OKAY && mp_isneg(t1)) {
err = mp_add(t1, prime, t1);
}
while (err == MP_OKAY && mp_cmp(t1, prime) != MP_LT) {
err = mp_sub(t1, prime, t1);
}
/* compare to b */
if (err == MP_OKAY) {
if (mp_cmp(t1, b) != MP_EQ) {
err = MP_VAL;
} else {
err = MP_OKAY;
}
}
mp_clear(t1);
mp_clear(t2);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t2, NULL, DYNAMIC_TYPE_ECC);
XFREE(t1, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
#else
(void)a;
(void)b;
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(prime) == 256) {
return sp_ecc_is_point_256(ecp->x, ecp->y);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(prime) == 384) {
return sp_ecc_is_point_384(ecp->x, ecp->y);
}
#endif
return WC_KEY_SIZE_E;
#endif
}
#ifndef WOLFSSL_SP_MATH
/* validate privkey * generator == pubkey, 0 on success */
static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime)
{
int err = MP_OKAY;
ecc_point* base = NULL;
ecc_point* res = NULL;
DECLARE_CURVE_SPECS(curve, 2);
if (key == NULL)
return BAD_FUNC_ARG;
ALLOC_CURVE_SPECS(2);
res = wc_ecc_new_point_h(key->heap);
if (res == NULL)
err = MEMORY_E;
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
if (err == MP_OKAY) {
err = sp_ecc_mulmod_base_256(&key->k, res, 1, key->heap);
}
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
if (err == MP_OKAY) {
err = sp_ecc_mulmod_base_384(&key->k, res, 1, key->heap);
}
}
else
#endif
#endif
{
base = wc_ecc_new_point_h(key->heap);
if (base == NULL)
err = MEMORY_E;
if (err == MP_OKAY) {
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_GX | ECC_CURVE_FIELD_GY));
}
/* set up base generator */
if (err == MP_OKAY)
err = mp_copy(curve->Gx, base->x);
if (err == MP_OKAY)
err = mp_copy(curve->Gy, base->y);
if (err == MP_OKAY)
err = mp_set(base->z, 1);
if (err == MP_OKAY)
err = wc_ecc_mulmod_ex(&key->k, base, res, a, prime, 1, key->heap);
}
if (err == MP_OKAY) {
/* compare result to public key */
if (mp_cmp(res->x, key->pubkey.x) != MP_EQ ||
mp_cmp(res->y, key->pubkey.y) != MP_EQ ||
mp_cmp(res->z, key->pubkey.z) != MP_EQ) {
/* didn't match */
err = ECC_PRIV_KEY_E;
}
}
wc_ecc_curve_free(curve);
wc_ecc_del_point_h(res, key->heap);
wc_ecc_del_point_h(base, key->heap);
FREE_CURVE_SPECS();
return err;
}
#endif
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
/* check privkey generator helper, creates prime needed */
static int ecc_check_privkey_gen_helper(ecc_key* key)
{
int err;
#ifndef WOLFSSL_ATECC508A
DECLARE_CURVE_SPECS(curve, 2);
#endif
if (key == NULL)
return BAD_FUNC_ARG;
#ifdef WOLFSSL_ATECC508A
/* Hardware based private key, so this operation is not supported */
err = MP_OKAY; /* just report success */
#else
ALLOC_CURVE_SPECS(2);
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF));
if (err == MP_OKAY)
err = ecc_check_privkey_gen(key, curve->Af, curve->prime);
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#endif /* WOLFSSL_ATECC508A */
return err;
}
#endif /* WOLFSSL_VALIDATE_ECC_IMPORT */
#if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH)
/* validate order * pubkey = point at infinity, 0 on success */
static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a,
mp_int* prime, mp_int* order)
{
ecc_point* inf = NULL;
int err;
if (key == NULL)
return BAD_FUNC_ARG;
inf = wc_ecc_new_point_h(key->heap);
if (inf == NULL)
err = MEMORY_E;
else {
#ifdef WOLFSSL_HAVE_SP_ECC
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_mulmod_256(order, pubkey, inf, 1, key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX &&
ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_mulmod_384(order, pubkey, inf, 1, key->heap);
}
else
#endif
#endif
#ifndef WOLFSSL_SP_MATH
err = wc_ecc_mulmod_ex(order, pubkey, inf, a, prime, 1, key->heap);
if (err == MP_OKAY && !wc_ecc_point_is_at_infinity(inf))
err = ECC_INF_E;
#else
(void)a;
(void)prime;
err = WC_KEY_SIZE_E;
#endif
}
wc_ecc_del_point_h(inf, key->heap);
return err;
}
#endif
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL*/
/* perform sanity checks on ecc key validity, 0 on success */
int wc_ecc_check_key(ecc_key* key)
{
int err;
#ifndef WOLFSSL_SP_MATH
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
mp_int* b = NULL;
#ifdef USE_ECC_B_PARAM
DECLARE_CURVE_SPECS(curve, 4);
#else
#ifndef WOLFSSL_SMALL_STACK
mp_int b_lcl;
#endif
DECLARE_CURVE_SPECS(curve, 3);
#endif /* USE_ECC_B_PARAM */
#endif /* WOLFSSL_ATECC508A */
if (key == NULL)
return BAD_FUNC_ARG;
#if defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_CRYPTOCELL)
err = 0; /* consider key check success on ATECC508A */
#else
#ifdef USE_ECC_B_PARAM
ALLOC_CURVE_SPECS(4);
#else
ALLOC_CURVE_SPECS(3);
#ifndef WOLFSSL_SMALL_STACK
b = &b_lcl;
#else
b = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_ECC);
if (b == NULL) {
FREE_CURVE_SPECS();
return MEMORY_E;
}
#endif
XMEMSET(b, 0, sizeof(mp_int));
#endif
/* SP 800-56Ar3, section 5.6.2.3.3, process step 1 */
/* pubkey point cannot be at infinity */
if (wc_ecc_point_is_at_infinity(&key->pubkey)) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
FREE_CURVE_SPECS();
return ECC_INF_E;
}
/* load curve info */
err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME |
ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_ORDER
#ifdef USE_ECC_B_PARAM
| ECC_CURVE_FIELD_BF
#endif
));
#ifndef USE_ECC_B_PARAM
/* load curve b parameter */
if (err == MP_OKAY)
err = mp_init(b);
if (err == MP_OKAY)
err = mp_read_radix(b, key->dp->Bf, MP_RADIX_HEX);
#else
if (err == MP_OKAY)
b = curve->Bf;
#endif
/* SP 800-56Ar3, section 5.6.2.3.3, process step 2 */
/* Qx must be in the range [0, p-1] */
if (err == MP_OKAY) {
if (mp_cmp(key->pubkey.x, curve->prime) != MP_LT)
err = ECC_OUT_OF_RANGE_E;
}
/* Qy must be in the range [0, p-1] */
if (err == MP_OKAY) {
if (mp_cmp(key->pubkey.y, curve->prime) != MP_LT)
err = ECC_OUT_OF_RANGE_E;
}
/* SP 800-56Ar3, section 5.6.2.3.3, process steps 3 */
/* make sure point is actually on curve */
if (err == MP_OKAY)
err = wc_ecc_is_point(&key->pubkey, curve->Af, b, curve->prime);
/* SP 800-56Ar3, section 5.6.2.3.3, process steps 4 */
/* pubkey * order must be at infinity */
if (err == MP_OKAY)
err = ecc_check_pubkey_order(key, &key->pubkey, curve->Af, curve->prime,
curve->order);
/* SP 800-56Ar3, section 5.6.2.1.4, method (b) for ECC */
/* private * base generator must equal pubkey */
if (err == MP_OKAY && key->type == ECC_PRIVATEKEY)
err = ecc_check_privkey_gen(key, curve->Af, curve->prime);
wc_ecc_curve_free(curve);
#ifndef USE_ECC_B_PARAM
mp_clear(b);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, key->heap, DYNAMIC_TYPE_ECC);
#endif
#endif
FREE_CURVE_SPECS();
#endif /* WOLFSSL_ATECC508A */
#else
if (key == NULL)
return BAD_FUNC_ARG;
/* pubkey point cannot be at infinity */
#ifndef WOLFSSL_SP_NO_256
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) {
err = sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, &key->k,
key->heap);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP384R1) {
err = sp_ecc_check_key_384(key->pubkey.x, key->pubkey.y, &key->k,
key->heap);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
return err;
}
#ifdef HAVE_ECC_KEY_IMPORT
/* import public ECC key in ANSI X9.63 format */
int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key,
int curve_id)
{
int err = MP_OKAY;
int compressed = 0;
int keysize = 0;
byte pointType;
if (in == NULL || key == NULL)
return BAD_FUNC_ARG;
/* must be odd */
if ((inLen & 1) == 0) {
return ECC_BAD_ARG_E;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
/* init key */
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
err = mp_init(&key->k);
#else
err = mp_init_multi(&key->k,
key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* check for point type (4, 2, or 3) */
pointType = in[0];
if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN &&
pointType != ECC_POINT_COMP_ODD) {
err = ASN_PARSE_E;
}
if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) {
#ifdef HAVE_COMP_KEY
compressed = 1;
#else
err = NOT_COMPILED_IN;
#endif
}
/* adjust to skip first byte */
inLen -= 1;
in += 1;
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 only save raw public key for hardware */
if (curve_id == ECC_SECP256R1 && !compressed &&
inLen <= sizeof(key->pubkey_raw)) {
XMEMCPY(key->pubkey_raw, (byte*)in, inLen);
}
#endif
if (err == MP_OKAY) {
#ifdef HAVE_COMP_KEY
/* adjust inLen if compressed */
if (compressed)
inLen = inLen*2 + 1; /* used uncompressed len */
#endif
/* determine key size */
keysize = (inLen>>1);
err = wc_ecc_set_curve(key, keysize, curve_id);
key->type = ECC_PUBLICKEY;
}
/* read data */
if (err == MP_OKAY)
err = mp_read_unsigned_bin(key->pubkey.x, (byte*)in, keysize);
#ifdef HAVE_COMP_KEY
if (err == MP_OKAY && compressed == 1) { /* build y */
#ifndef WOLFSSL_SP_MATH
mp_int t1, t2;
int did_init = 0;
DECLARE_CURVE_SPECS(curve, 3);
ALLOC_CURVE_SPECS(3);
if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY)
err = MEMORY_E;
else
did_init = 1;
/* load curve info */
if (err == MP_OKAY)
err = wc_ecc_curve_load(key->dp, &curve,
(ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF |
ECC_CURVE_FIELD_BF));
/* compute x^3 */
if (err == MP_OKAY)
err = mp_sqr(key->pubkey.x, &t1);
if (err == MP_OKAY)
err = mp_mulmod(&t1, key->pubkey.x, curve->prime, &t1);
/* compute x^3 + a*x */
if (err == MP_OKAY)
err = mp_mulmod(curve->Af, key->pubkey.x, curve->prime, &t2);
if (err == MP_OKAY)
err = mp_add(&t1, &t2, &t1);
/* compute x^3 + a*x + b */
if (err == MP_OKAY)
err = mp_add(&t1, curve->Bf, &t1);
/* compute sqrt(x^3 + a*x + b) */
if (err == MP_OKAY)
err = mp_sqrtmod_prime(&t1, curve->prime, &t2);
/* adjust y */
if (err == MP_OKAY) {
if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) ||
(mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) {
err = mp_mod(&t2, curve->prime, &t2);
}
else {
err = mp_submod(curve->prime, &t2, curve->prime, &t2);
}
if (err == MP_OKAY)
err = mp_copy(&t2, key->pubkey.y);
}
if (did_init) {
mp_clear(&t2);
mp_clear(&t1);
}
wc_ecc_curve_free(curve);
FREE_CURVE_SPECS();
#else
#ifndef WOLFSSL_SP_NO_256
if (key->dp->id == ECC_SECP256R1) {
sp_ecc_uncompress_256(key->pubkey.x, pointType, key->pubkey.y);
}
else
#endif
#ifdef WOLFSSL_SP_384
if (key->dp->id == ECC_SECP384R1) {
sp_ecc_uncompress_384(key->pubkey.x, pointType, key->pubkey.y);
}
else
#endif
{
err = WC_KEY_SIZE_E;
}
#endif
}
#endif /* HAVE_COMP_KEY */
if (err == MP_OKAY && compressed == 0)
err = mp_read_unsigned_bin(key->pubkey.y, (byte*)in + keysize, keysize);
if (err == MP_OKAY)
err = mp_set(key->pubkey.z, 1);
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if (err == MP_OKAY)
err = wc_ecc_check_key(key);
#endif
if (err != MP_OKAY) {
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_clear(&key->k);
}
return err;
}
WOLFSSL_ABI
int wc_ecc_import_x963(const byte* in, word32 inLen, ecc_key* key)
{
return wc_ecc_import_x963_ex(in, inLen, key, ECC_CURVE_DEF);
}
#endif /* HAVE_ECC_KEY_IMPORT */
#ifdef HAVE_ECC_KEY_EXPORT
/* export ecc key to component form, d is optional if only exporting public
* encType is WC_TYPE_UNSIGNED_BIN or WC_TYPE_HEX_STR
* return MP_OKAY on success */
int wc_ecc_export_ex(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen, byte* d, word32* dLen, int encType)
{
int err = 0;
word32 keySz;
if (key == NULL) {
return BAD_FUNC_ARG;
}
if (wc_ecc_is_valid_idx(key->idx) == 0) {
return ECC_BAD_ARG_E;
}
keySz = key->dp->size;
/* private key, d */
if (d != NULL) {
if (dLen == NULL ||
(key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY))
return BAD_FUNC_ARG;
#ifdef WOLFSSL_ATECC508A
/* Hardware cannot export private portion */
return NOT_COMPILED_IN;
#else
err = wc_export_int(&key->k, d, dLen, keySz, encType);
if (err != MP_OKAY)
return err;
#endif
}
/* public x component */
if (qx != NULL) {
if (qxLen == NULL || key->type == ECC_PRIVATEKEY_ONLY)
return BAD_FUNC_ARG;
err = wc_export_int(key->pubkey.x, qx, qxLen, keySz, encType);
if (err != MP_OKAY)
return err;
}
/* public y component */
if (qy != NULL) {
if (qyLen == NULL || key->type == ECC_PRIVATEKEY_ONLY)
return BAD_FUNC_ARG;
err = wc_export_int(key->pubkey.y, qy, qyLen, keySz, encType);
if (err != MP_OKAY)
return err;
}
return err;
}
/* export ecc private key only raw, outLen is in/out size as unsigned bin
return MP_OKAY on success */
int wc_ecc_export_private_only(ecc_key* key, byte* out, word32* outLen)
{
if (out == NULL || outLen == NULL) {
return BAD_FUNC_ARG;
}
return wc_ecc_export_ex(key, NULL, NULL, NULL, NULL, out, outLen,
WC_TYPE_UNSIGNED_BIN);
}
/* export public key to raw elements including public (Qx,Qy) as unsigned bin
* return MP_OKAY on success, negative on error */
int wc_ecc_export_public_raw(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen)
{
if (qx == NULL || qxLen == NULL || qy == NULL || qyLen == NULL) {
return BAD_FUNC_ARG;
}
return wc_ecc_export_ex(key, qx, qxLen, qy, qyLen, NULL, NULL,
WC_TYPE_UNSIGNED_BIN);
}
/* export ecc key to raw elements including public (Qx,Qy) and
* private (d) as unsigned bin
* return MP_OKAY on success, negative on error */
int wc_ecc_export_private_raw(ecc_key* key, byte* qx, word32* qxLen,
byte* qy, word32* qyLen, byte* d, word32* dLen)
{
return wc_ecc_export_ex(key, qx, qxLen, qy, qyLen, d, dLen,
WC_TYPE_UNSIGNED_BIN);
}
#endif /* HAVE_ECC_KEY_EXPORT */
#ifndef NO_ASN
#ifdef HAVE_ECC_KEY_IMPORT
/* import private key, public part optional if (pub) passed as NULL */
int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz,
const byte* pub, word32 pubSz, ecc_key* key,
int curve_id)
{
int ret;
word32 idx = 0;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_BUILD_TempData_t tempBuff;
#endif
if (key == NULL || priv == NULL)
return BAD_FUNC_ARG;
/* public optional, NULL if only importing private */
if (pub != NULL) {
ret = wc_ecc_import_x963_ex(pub, pubSz, key, curve_id);
if (ret < 0)
ret = wc_EccPublicKeyDecode(pub, &idx, key, pubSz);
key->type = ECC_PRIVATEKEY;
}
else {
/* make sure required variables are reset */
wc_ecc_reset(key);
/* set key size */
ret = wc_ecc_set_curve(key, privSz, curve_id);
key->type = ECC_PRIVATEKEY_ONLY;
}
if (ret != 0)
return ret;
#ifdef WOLFSSL_ATECC508A
/* Hardware does not support loading private keys */
return NOT_COMPILED_IN;
#elif defined(WOLFSSL_CRYPTOCELL)
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
if (pub != NULL && pub[0] != '\0') {
/* create public key from external key buffer */
ret = CRYS_ECPKI_BuildPublKeyFullCheck(pDomain,
(byte*)pub,
pubSz,
&key->ctx.pubKey,
&tempBuff);
if (ret != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPublKeyFullCheck failed");
return ret;
}
}
/* import private key */
if (priv != NULL && priv[0] != '\0') {
/* Create private key from external key buffer*/
ret = CRYS_ECPKI_BuildPrivKey(pDomain,
priv,
privSz,
&key->ctx.privKey);
if (ret != SA_SILIB_RET_OK) {
WOLFSSL_MSG("CRYS_ECPKI_BuildPrivKey failed");
return ret;
}
ret = mp_read_unsigned_bin(&key->k, priv, privSz);
}
#else
ret = mp_read_unsigned_bin(&key->k, priv, privSz);
#ifdef HAVE_WOLF_BIGINT
if (ret == 0 &&
wc_bigint_from_unsigned_bin(&key->k.raw, priv, privSz) != 0) {
mp_clear(&key->k);
ret = ASN_GETINT_E;
}
#endif /* HAVE_WOLF_BIGINT */
#endif /* WOLFSSL_ATECC508A */
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if ((pub != NULL) && (ret == MP_OKAY))
/* public key needed to perform key validation */
ret = ecc_check_privkey_gen_helper(key);
#endif
return ret;
}
/* ecc private key import, public key in ANSI X9.63 format, private raw */
int wc_ecc_import_private_key(const byte* priv, word32 privSz, const byte* pub,
word32 pubSz, ecc_key* key)
{
return wc_ecc_import_private_key_ex(priv, privSz, pub, pubSz, key,
ECC_CURVE_DEF);
}
#endif /* HAVE_ECC_KEY_IMPORT */
/**
Convert ECC R,S to signature
r R component of signature
s S component of signature
out DER-encoded ECDSA signature
outlen [in/out] output buffer size, output signature size
return MP_OKAY on success
*/
int wc_ecc_rs_to_sig(const char* r, const char* s, byte* out, word32* outlen)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (r == NULL || s == NULL || out == NULL || outlen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = mp_init_multi(rtmp, stmp, NULL, NULL, NULL, NULL);
if (err != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
err = mp_read_radix(rtmp, r, MP_RADIX_HEX);
if (err == MP_OKAY)
err = mp_read_radix(stmp, s, MP_RADIX_HEX);
/* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
if (err == MP_OKAY)
err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
if (err == MP_OKAY) {
if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
err = MP_ZERO_E;
}
mp_clear(rtmp);
mp_clear(stmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/**
Convert ECC R,S raw unsigned bin to signature
r R component of signature
rSz R size
s S component of signature
sSz S size
out DER-encoded ECDSA signature
outlen [in/out] output buffer size, output signature size
return MP_OKAY on success
*/
int wc_ecc_rs_raw_to_sig(const byte* r, word32 rSz, const byte* s, word32 sSz,
byte* out, word32* outlen)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (r == NULL || s == NULL || out == NULL || outlen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = mp_init_multi(rtmp, stmp, NULL, NULL, NULL, NULL);
if (err != MP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
err = mp_read_unsigned_bin(rtmp, r, rSz);
if (err == MP_OKAY)
err = mp_read_unsigned_bin(stmp, s, sSz);
/* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */
if (err == MP_OKAY)
err = StoreECC_DSA_Sig(out, outlen, rtmp, stmp);
if (err == MP_OKAY) {
if (mp_iszero(rtmp) == MP_YES || mp_iszero(stmp) == MP_YES)
err = MP_ZERO_E;
}
mp_clear(rtmp);
mp_clear(stmp);
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
/**
Convert ECC signature to R,S
sig DER-encoded ECDSA signature
sigLen length of signature in octets
r R component of signature
rLen [in/out] output "r" buffer size, output "r" size
s S component of signature
sLen [in/out] output "s" buffer size, output "s" size
return MP_OKAY on success, negative on error
*/
int wc_ecc_sig_to_rs(const byte* sig, word32 sigLen, byte* r, word32* rLen,
byte* s, word32* sLen)
{
int err;
int tmp_valid = 0;
word32 x = 0;
#ifdef WOLFSSL_SMALL_STACK
mp_int* rtmp = NULL;
mp_int* stmp = NULL;
#else
mp_int rtmp[1];
mp_int stmp[1];
#endif
if (sig == NULL || r == NULL || rLen == NULL || s == NULL || sLen == NULL)
return ECC_BAD_ARG_E;
#ifdef WOLFSSL_SMALL_STACK
rtmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (rtmp == NULL)
return MEMORY_E;
stmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_ECC);
if (stmp == NULL) {
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
return MEMORY_E;
}
#endif
err = DecodeECC_DSA_Sig(sig, sigLen, rtmp, stmp);
/* rtmp and stmp are initialized */
if (err == MP_OKAY) {
tmp_valid = 1;
}
/* extract r */
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(rtmp);
if (*rLen < x)
err = BUFFER_E;
if (err == MP_OKAY) {
*rLen = x;
err = mp_to_unsigned_bin(rtmp, r);
}
}
/* extract s */
if (err == MP_OKAY) {
x = mp_unsigned_bin_size(stmp);
if (*sLen < x)
err = BUFFER_E;
if (err == MP_OKAY) {
*sLen = x;
err = mp_to_unsigned_bin(stmp, s);
}
}
if (tmp_valid) {
mp_clear(rtmp);
mp_clear(stmp);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(stmp, NULL, DYNAMIC_TYPE_ECC);
XFREE(rtmp, NULL, DYNAMIC_TYPE_ECC);
#endif
return err;
}
#endif /* !NO_ASN */
#ifdef HAVE_ECC_KEY_IMPORT
static int wc_ecc_import_raw_private(ecc_key* key, const char* qx,
const char* qy, const char* d, int curve_id, int encType)
{
int err = MP_OKAY;
#if defined(WOLFSSL_CRYPTOCELL) && !defined(WOLFSSL_ATECC508A)
const CRYS_ECPKI_Domain_t* pDomain;
CRYS_ECPKI_BUILD_TempData_t tempBuff;
byte key_raw[ECC_MAX_CRYPTO_HW_SIZE*2 + 1];
word32 keySz = 0;
#endif
/* if d is NULL, only import as public key using Qx,Qy */
if (key == NULL || qx == NULL || qy == NULL) {
return BAD_FUNC_ARG;
}
/* make sure required variables are reset */
wc_ecc_reset(key);
/* set curve type and index */
err = wc_ecc_set_curve(key, 0, curve_id);
if (err != 0) {
return err;
}
/* init key */
#ifdef ALT_ECC_SIZE
key->pubkey.x = (mp_int*)&key->pubkey.xyz[0];
key->pubkey.y = (mp_int*)&key->pubkey.xyz[1];
key->pubkey.z = (mp_int*)&key->pubkey.xyz[2];
alt_fp_init(key->pubkey.x);
alt_fp_init(key->pubkey.y);
alt_fp_init(key->pubkey.z);
err = mp_init(&key->k);
#else
err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z,
NULL, NULL);
#endif
if (err != MP_OKAY)
return MEMORY_E;
/* read Qx */
if (err == MP_OKAY) {
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx,
key->dp->size);
}
/* read Qy */
if (err == MP_OKAY) {
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy,
key->dp->size);
}
if (err == MP_OKAY)
err = mp_set(key->pubkey.z, 1);
#ifdef WOLFSSL_ATECC508A
/* For SECP256R1 only save raw public key for hardware */
if (err == MP_OKAY && curve_id == ECC_SECP256R1) {
word32 keySz = key->dp->size;
err = wc_export_int(key->pubkey.x, key->pubkey_raw,
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
if (err == MP_OKAY)
err = wc_export_int(key->pubkey.y, &key->pubkey_raw[keySz],
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
}
#elif defined(WOLFSSL_CRYPTOCELL)
if (err == MP_OKAY) {
key_raw[0] = ECC_POINT_UNCOMP;
keySz = (word32)key->dp->size;
err = wc_export_int(key->pubkey.x, &key_raw[1], &keySz, keySz,
WC_TYPE_UNSIGNED_BIN);
if (err == MP_OKAY)
err = wc_export_int(key->pubkey.y, &key_raw[1+keySz],
&keySz, keySz, WC_TYPE_UNSIGNED_BIN);
pDomain = CRYS_ECPKI_GetEcDomain(cc310_mapCurve(curve_id));
/* create public key from external key buffer */
err = CRYS_ECPKI_BuildPublKeyFullCheck(pDomain,
key_raw,
keySz*2 + 1,
&key->ctx.pubKey,
&tempBuff);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPublKeyFullCheck failed");
return err;
}
}
#endif
/* import private key */
if (err == MP_OKAY) {
if (d != NULL && d[0] != '\0') {
#ifdef WOLFSSL_ATECC508A
/* Hardware doesn't support loading private key */
err = NOT_COMPILED_IN;
#elif defined(WOLFSSL_CRYPTOCELL)
key->type = ECC_PRIVATEKEY;
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(&key->k, d, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(&key->k, (const byte*)d,
key->dp->size);
if (err == MP_OKAY) {
err = wc_export_int(&key->k, &key_raw[0], &keySz, keySz,
WC_TYPE_UNSIGNED_BIN);
}
if (err == MP_OKAY) {
/* Create private key from external key buffer*/
err = CRYS_ECPKI_BuildPrivKey(pDomain,
key_raw,
keySz,
&key->ctx.privKey);
if (err != SA_SILIB_RET_OK){
WOLFSSL_MSG("CRYS_ECPKI_BuildPrivKey failed");
return err;
}
}
#else
key->type = ECC_PRIVATEKEY;
if (encType == WC_TYPE_HEX_STR)
err = mp_read_radix(&key->k, d, MP_RADIX_HEX);
else
err = mp_read_unsigned_bin(&key->k, (const byte*)d,
key->dp->size);
#endif /* WOLFSSL_ATECC508A */
} else {
key->type = ECC_PUBLICKEY;
}
}
#ifdef WOLFSSL_VALIDATE_ECC_IMPORT
if (err == MP_OKAY)
err = wc_ecc_check_key(key);
#endif
if (err != MP_OKAY) {
mp_clear(key->pubkey.x);
mp_clear(key->pubkey.y);
mp_clear(key->pubkey.z);
mp_clear(&key->k);
}
return err;
}
/**
Import raw ECC key
key The destination ecc_key structure
qx x component of the public key, as ASCII hex string
qy y component of the public key, as ASCII hex string
d private key, as ASCII hex string, optional if importing public
key only
dp Custom ecc_set_type
return MP_OKAY on success
*/
int wc_ecc_import_raw_ex(ecc_key* key, const char* qx, const char* qy,
const char* d, int curve_id)
{
return wc_ecc_import_raw_private(key, qx, qy, d, curve_id,
WC_TYPE_HEX_STR);
}
/* Import x, y and optional private (d) as unsigned binary */
int wc_ecc_import_unsigned(ecc_key* key, byte* qx, byte* qy,
byte* d, int curve_id)
{
return wc_ecc_import_raw_private(key, (const char*)qx, (const char*)qy,
(const char*)d, curve_id, WC_TYPE_UNSIGNED_BIN);
}
/**
Import raw ECC key
key The destination ecc_key structure
qx x component of the public key, as ASCII hex string
qy y component of the public key, as ASCII hex string
d private key, as ASCII hex string, optional if importing public
key only
curveName ECC curve name, from ecc_sets[]
return MP_OKAY on success
*/
int wc_ecc_import_raw(ecc_key* key, const char* qx, const char* qy,
const char* d, const char* curveName)
{
int err, x;
/* if d is NULL, only import as public key using Qx,Qy */
if (key == NULL || qx == NULL || qy == NULL || curveName == NULL) {
return BAD_FUNC_ARG;
}
/* set curve type and index */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (XSTRNCMP(ecc_sets[x].name, curveName,
XSTRLEN(curveName)) == 0) {
break;
}
}
if (ecc_sets[x].size == 0) {
WOLFSSL_MSG("ecc_set curve name not found");
err = ASN_PARSE_E;
} else {
return wc_ecc_import_raw_private(key, qx, qy, d, ecc_sets[x].id,
WC_TYPE_HEX_STR);
}
return err;
}
#endif /* HAVE_ECC_KEY_IMPORT */
/* key size in octets */
int wc_ecc_size(ecc_key* key)
{
if (key == NULL)
return 0;
return key->dp->size;
}
/* maximum signature size based on key size */
int wc_ecc_sig_size_calc(int sz)
{
int maxSigSz = 0;
/* calculate based on key bits */
/* maximum possible signature header size is 7 bytes plus 2 bytes padding */
maxSigSz = (sz * 2) + SIG_HEADER_SZ + ECC_MAX_PAD_SZ;
/* if total length is less than 128 + SEQ(1)+LEN(1) then subtract 1 */
if (maxSigSz < (128 + 2)) {
maxSigSz -= 1;
}
return maxSigSz;
}
/* maximum signature size based on actual key curve */
int wc_ecc_sig_size(ecc_key* key)
{
int maxSigSz;
int orderBits, keySz;
if (key == NULL || key->dp == NULL)
return 0;
/* the signature r and s will always be less than order */
/* if the order MSB (top bit of byte) is set then ASN encoding needs
extra byte for r and s, so add 2 */
keySz = key->dp->size;
orderBits = wc_ecc_get_curve_order_bit_count(key->dp);
if (orderBits > keySz * 8) {
keySz = (orderBits + 7) / 8;
}
/* maximum possible signature header size is 7 bytes */
maxSigSz = (keySz * 2) + SIG_HEADER_SZ;
if ((orderBits % 8) == 0) {
/* MSB can be set, so add 2 */
maxSigSz += ECC_MAX_PAD_SZ;
}
/* if total length is less than 128 + SEQ(1)+LEN(1) then subtract 1 */
if (maxSigSz < (128 + 2)) {
maxSigSz -= 1;
}
return maxSigSz;
}
#ifdef FP_ECC
/* fixed point ECC cache */
/* number of entries in the cache */
#ifndef FP_ENTRIES
#define FP_ENTRIES 15
#endif
/* number of bits in LUT */
#ifndef FP_LUT
#define FP_LUT 8U
#endif
#ifdef ECC_SHAMIR
/* Sharmir requires a bigger LUT, TAO */
#if (FP_LUT > 12) || (FP_LUT < 4)
#error FP_LUT must be between 4 and 12 inclusively
#endif
#else
#if (FP_LUT > 12) || (FP_LUT < 2)
#error FP_LUT must be between 2 and 12 inclusively
#endif
#endif
#ifndef WOLFSSL_SP_MATH
/** Our FP cache */
typedef struct {
ecc_point* g; /* cached COPY of base point */
ecc_point* LUT[1U<<FP_LUT]; /* fixed point lookup */
mp_int mu; /* copy of the montgomery constant */
int lru_count; /* amount of times this entry has been used */
int lock; /* flag to indicate cache eviction */
/* permitted (0) or not (1) */
} fp_cache_t;
/* if HAVE_THREAD_LS this cache is per thread, no locking needed */
static THREAD_LS_T fp_cache_t fp_cache[FP_ENTRIES];
#ifndef HAVE_THREAD_LS
static volatile int initMutex = 0; /* prevent multiple mutex inits */
static wolfSSL_Mutex ecc_fp_lock;
#endif /* HAVE_THREAD_LS */
/* simple table to help direct the generation of the LUT */
static const struct {
int ham, terma, termb;
} lut_orders[] = {
{ 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 2, 1, 2 }, { 1, 0, 0 }, { 2, 1, 4 }, { 2, 2, 4 }, { 3, 3, 4 },
{ 1, 0, 0 }, { 2, 1, 8 }, { 2, 2, 8 }, { 3, 3, 8 }, { 2, 4, 8 }, { 3, 5, 8 }, { 3, 6, 8 }, { 4, 7, 8 },
{ 1, 0, 0 }, { 2, 1, 16 }, { 2, 2, 16 }, { 3, 3, 16 }, { 2, 4, 16 }, { 3, 5, 16 }, { 3, 6, 16 }, { 4, 7, 16 },
{ 2, 8, 16 }, { 3, 9, 16 }, { 3, 10, 16 }, { 4, 11, 16 }, { 3, 12, 16 }, { 4, 13, 16 }, { 4, 14, 16 }, { 5, 15, 16 },
{ 1, 0, 0 }, { 2, 1, 32 }, { 2, 2, 32 }, { 3, 3, 32 }, { 2, 4, 32 }, { 3, 5, 32 }, { 3, 6, 32 }, { 4, 7, 32 },
{ 2, 8, 32 }, { 3, 9, 32 }, { 3, 10, 32 }, { 4, 11, 32 }, { 3, 12, 32 }, { 4, 13, 32 }, { 4, 14, 32 }, { 5, 15, 32 },
{ 2, 16, 32 }, { 3, 17, 32 }, { 3, 18, 32 }, { 4, 19, 32 }, { 3, 20, 32 }, { 4, 21, 32 }, { 4, 22, 32 }, { 5, 23, 32 },
{ 3, 24, 32 }, { 4, 25, 32 }, { 4, 26, 32 }, { 5, 27, 32 }, { 4, 28, 32 }, { 5, 29, 32 }, { 5, 30, 32 }, { 6, 31, 32 },
#if FP_LUT > 6
{ 1, 0, 0 }, { 2, 1, 64 }, { 2, 2, 64 }, { 3, 3, 64 }, { 2, 4, 64 }, { 3, 5, 64 }, { 3, 6, 64 }, { 4, 7, 64 },
{ 2, 8, 64 }, { 3, 9, 64 }, { 3, 10, 64 }, { 4, 11, 64 }, { 3, 12, 64 }, { 4, 13, 64 }, { 4, 14, 64 }, { 5, 15, 64 },
{ 2, 16, 64 }, { 3, 17, 64 }, { 3, 18, 64 }, { 4, 19, 64 }, { 3, 20, 64 }, { 4, 21, 64 }, { 4, 22, 64 }, { 5, 23, 64 },
{ 3, 24, 64 }, { 4, 25, 64 }, { 4, 26, 64 }, { 5, 27, 64 }, { 4, 28, 64 }, { 5, 29, 64 }, { 5, 30, 64 }, { 6, 31, 64 },
{ 2, 32, 64 }, { 3, 33, 64 }, { 3, 34, 64 }, { 4, 35, 64 }, { 3, 36, 64 }, { 4, 37, 64 }, { 4, 38, 64 }, { 5, 39, 64 },
{ 3, 40, 64 }, { 4, 41, 64 }, { 4, 42, 64 }, { 5, 43, 64 }, { 4, 44, 64 }, { 5, 45, 64 }, { 5, 46, 64 }, { 6, 47, 64 },
{ 3, 48, 64 }, { 4, 49, 64 }, { 4, 50, 64 }, { 5, 51, 64 }, { 4, 52, 64 }, { 5, 53, 64 }, { 5, 54, 64 }, { 6, 55, 64 },
{ 4, 56, 64 }, { 5, 57, 64 }, { 5, 58, 64 }, { 6, 59, 64 }, { 5, 60, 64 }, { 6, 61, 64 }, { 6, 62, 64 }, { 7, 63, 64 },
#if FP_LUT > 7
{ 1, 0, 0 }, { 2, 1, 128 }, { 2, 2, 128 }, { 3, 3, 128 }, { 2, 4, 128 }, { 3, 5, 128 }, { 3, 6, 128 }, { 4, 7, 128 },
{ 2, 8, 128 }, { 3, 9, 128 }, { 3, 10, 128 }, { 4, 11, 128 }, { 3, 12, 128 }, { 4, 13, 128 }, { 4, 14, 128 }, { 5, 15, 128 },
{ 2, 16, 128 }, { 3, 17, 128 }, { 3, 18, 128 }, { 4, 19, 128 }, { 3, 20, 128 }, { 4, 21, 128 }, { 4, 22, 128 }, { 5, 23, 128 },
{ 3, 24, 128 }, { 4, 25, 128 }, { 4, 26, 128 }, { 5, 27, 128 }, { 4, 28, 128 }, { 5, 29, 128 }, { 5, 30, 128 }, { 6, 31, 128 },
{ 2, 32, 128 }, { 3, 33, 128 }, { 3, 34, 128 }, { 4, 35, 128 }, { 3, 36, 128 }, { 4, 37, 128 }, { 4, 38, 128 }, { 5, 39, 128 },
{ 3, 40, 128 }, { 4, 41, 128 }, { 4, 42, 128 }, { 5, 43, 128 }, { 4, 44, 128 }, { 5, 45, 128 }, { 5, 46, 128 }, { 6, 47, 128 },
{ 3, 48, 128 }, { 4, 49, 128 }, { 4, 50, 128 }, { 5, 51, 128 }, { 4, 52, 128 }, { 5, 53, 128 }, { 5, 54, 128 }, { 6, 55, 128 },
{ 4, 56, 128 }, { 5, 57, 128 }, { 5, 58, 128 }, { 6, 59, 128 }, { 5, 60, 128 }, { 6, 61, 128 }, { 6, 62, 128 }, { 7, 63, 128 },
{ 2, 64, 128 }, { 3, 65, 128 }, { 3, 66, 128 }, { 4, 67, 128 }, { 3, 68, 128 }, { 4, 69, 128 }, { 4, 70, 128 }, { 5, 71, 128 },
{ 3, 72, 128 }, { 4, 73, 128 }, { 4, 74, 128 }, { 5, 75, 128 }, { 4, 76, 128 }, { 5, 77, 128 }, { 5, 78, 128 }, { 6, 79, 128 },
{ 3, 80, 128 }, { 4, 81, 128 }, { 4, 82, 128 }, { 5, 83, 128 }, { 4, 84, 128 }, { 5, 85, 128 }, { 5, 86, 128 }, { 6, 87, 128 },
{ 4, 88, 128 }, { 5, 89, 128 }, { 5, 90, 128 }, { 6, 91, 128 }, { 5, 92, 128 }, { 6, 93, 128 }, { 6, 94, 128 }, { 7, 95, 128 },
{ 3, 96, 128 }, { 4, 97, 128 }, { 4, 98, 128 }, { 5, 99, 128 }, { 4, 100, 128 }, { 5, 101, 128 }, { 5, 102, 128 }, { 6, 103, 128 },
{ 4, 104, 128 }, { 5, 105, 128 }, { 5, 106, 128 }, { 6, 107, 128 }, { 5, 108, 128 }, { 6, 109, 128 }, { 6, 110, 128 }, { 7, 111, 128 },
{ 4, 112, 128 }, { 5, 113, 128 }, { 5, 114, 128 }, { 6, 115, 128 }, { 5, 116, 128 }, { 6, 117, 128 }, { 6, 118, 128 }, { 7, 119, 128 },
{ 5, 120, 128 }, { 6, 121, 128 }, { 6, 122, 128 }, { 7, 123, 128 }, { 6, 124, 128 }, { 7, 125, 128 }, { 7, 126, 128 }, { 8, 127, 128 },
#if FP_LUT > 8
{ 1, 0, 0 }, { 2, 1, 256 }, { 2, 2, 256 }, { 3, 3, 256 }, { 2, 4, 256 }, { 3, 5, 256 }, { 3, 6, 256 }, { 4, 7, 256 },
{ 2, 8, 256 }, { 3, 9, 256 }, { 3, 10, 256 }, { 4, 11, 256 }, { 3, 12, 256 }, { 4, 13, 256 }, { 4, 14, 256 }, { 5, 15, 256 },
{ 2, 16, 256 }, { 3, 17, 256 }, { 3, 18, 256 }, { 4, 19, 256 }, { 3, 20, 256 }, { 4, 21, 256 }, { 4, 22, 256 }, { 5, 23, 256 },
{ 3, 24, 256 }, { 4, 25, 256 }, { 4, 26, 256 }, { 5, 27, 256 }, { 4, 28, 256 }, { 5, 29, 256 }, { 5, 30, 256 }, { 6, 31, 256 },
{ 2, 32, 256 }, { 3, 33, 256 }, { 3, 34, 256 }, { 4, 35, 256 }, { 3, 36, 256 }, { 4, 37, 256 }, { 4, 38, 256 }, { 5, 39, 256 },
{ 3, 40, 256 }, { 4, 41, 256 }, { 4, 42, 256 }, { 5, 43, 256 }, { 4, 44, 256 }, { 5, 45, 256 }, { 5, 46, 256 }, { 6, 47, 256 },
{ 3, 48, 256 }, { 4, 49, 256 }, { 4, 50, 256 }, { 5, 51, 256 }, { 4, 52, 256 }, { 5, 53, 256 }, { 5, 54, 256 }, { 6, 55, 256 },
{ 4, 56, 256 }, { 5, 57, 256 }, { 5, 58, 256 }, { 6, 59, 256 }, { 5, 60, 256 }, { 6, 61, 256 }, { 6, 62, 256 }, { 7, 63, 256 },
{ 2, 64, 256 }, { 3, 65, 256 }, { 3, 66, 256 }, { 4, 67, 256 }, { 3, 68, 256 }, { 4, 69, 256 }, { 4, 70, 256 }, { 5, 71, 256 },
{ 3, 72, 256 }, { 4, 73, 256 }, { 4, 74, 256 }, { 5, 75, 256 }, { 4, 76, 256 }, { 5, 77, 256 }, { 5, 78, 256 }, { 6, 79, 256 },
{ 3, 80, 256 }, { 4, 81, 256 }, { 4, 82, 256 }, { 5, 83, 256 }, { 4, 84, 256 }, { 5, 85, 256 }, { 5, 86, 256 }, { 6, 87, 256 },
{ 4, 88, 256 }, { 5, 89, 256 }, { 5, 90, 256 }, { 6, 91, 256 }, { 5, 92, 256 }, { 6, 93, 256 }, { 6, 94, 256 }, { 7, 95, 256 },
{ 3, 96, 256 }, { 4, 97, 256 }, { 4, 98, 256 }, { 5, 99, 256 }, { 4, 100, 256 }, { 5, 101, 256 }, { 5, 102, 256 }, { 6, 103, 256 },
{ 4, 104, 256 }, { 5, 105, 256 }, { 5, 106, 256 }, { 6, 107, 256 }, { 5, 108, 256 }, { 6, 109, 256 }, { 6, 110, 256 }, { 7, 111, 256 },
{ 4, 112, 256 }, { 5, 113, 256 }, { 5, 114, 256 }, { 6, 115, 256 }, { 5, 116, 256 }, { 6, 117, 256 }, { 6, 118, 256 }, { 7, 119, 256 },
{ 5, 120, 256 }, { 6, 121, 256 }, { 6, 122, 256 }, { 7, 123, 256 }, { 6, 124, 256 }, { 7, 125, 256 }, { 7, 126, 256 }, { 8, 127, 256 },
{ 2, 128, 256 }, { 3, 129, 256 }, { 3, 130, 256 }, { 4, 131, 256 }, { 3, 132, 256 }, { 4, 133, 256 }, { 4, 134, 256 }, { 5, 135, 256 },
{ 3, 136, 256 }, { 4, 137, 256 }, { 4, 138, 256 }, { 5, 139, 256 }, { 4, 140, 256 }, { 5, 141, 256 }, { 5, 142, 256 }, { 6, 143, 256 },
{ 3, 144, 256 }, { 4, 145, 256 }, { 4, 146, 256 }, { 5, 147, 256 }, { 4, 148, 256 }, { 5, 149, 256 }, { 5, 150, 256 }, { 6, 151, 256 },
{ 4, 152, 256 }, { 5, 153, 256 }, { 5, 154, 256 }, { 6, 155, 256 }, { 5, 156, 256 }, { 6, 157, 256 }, { 6, 158, 256 }, { 7, 159, 256 },
{ 3, 160, 256 }, { 4, 161, 256 }, { 4, 162, 256 }, { 5, 163, 256 }, { 4, 164, 256 }, { 5, 165, 256 }, { 5, 166, 256 }, { 6, 167, 256 },
{ 4, 168, 256 }, { 5, 169, 256 }, { 5, 170, 256 }, { 6, 171, 256 }, { 5, 172, 256 }, { 6, 173, 256 }, { 6, 174, 256 }, { 7, 175, 256 },
{ 4, 176, 256 }, { 5, 177, 256 }, { 5, 178, 256 }, { 6, 179, 256 }, { 5, 180, 256 }, { 6, 181, 256 }, { 6, 182, 256 }, { 7, 183, 256 },
{ 5, 184, 256 }, { 6, 185, 256 }, { 6, 186, 256 }, { 7, 187, 256 }, { 6, 188, 256 }, { 7, 189, 256 }, { 7, 190, 256 }, { 8, 191, 256 },
{ 3, 192, 256 }, { 4, 193, 256 }, { 4, 194, 256 }, { 5, 195, 256 }, { 4, 196, 256 }, { 5, 197, 256 }, { 5, 198, 256 }, { 6, 199, 256 },
{ 4, 200, 256 }, { 5, 201, 256 }, { 5, 202, 256 }, { 6, 203, 256 }, { 5, 204, 256 }, { 6, 205, 256 }, { 6, 206, 256 }, { 7, 207, 256 },
{ 4, 208, 256 }, { 5, 209, 256 }, { 5, 210, 256 }, { 6, 211, 256 }, { 5, 212, 256 }, { 6, 213, 256 }, { 6, 214, 256 }, { 7, 215, 256 },
{ 5, 216, 256 }, { 6, 217, 256 }, { 6, 218, 256 }, { 7, 219, 256 }, { 6, 220, 256 }, { 7, 221, 256 }, { 7, 222, 256 }, { 8, 223, 256 },
{ 4, 224, 256 }, { 5, 225, 256 }, { 5, 226, 256 }, { 6, 227, 256 }, { 5, 228, 256 }, { 6, 229, 256 }, { 6, 230, 256 }, { 7, 231, 256 },
{ 5, 232, 256 }, { 6, 233, 256 }, { 6, 234, 256 }, { 7, 235, 256 }, { 6, 236, 256 }, { 7, 237, 256 }, { 7, 238, 256 }, { 8, 239, 256 },
{ 5, 240, 256 }, { 6, 241, 256 }, { 6, 242, 256 }, { 7, 243, 256 }, { 6, 244, 256 }, { 7, 245, 256 }, { 7, 246, 256 }, { 8, 247, 256 },
{ 6, 248, 256 }, { 7, 249, 256 }, { 7, 250, 256 }, { 8, 251, 256 }, { 7, 252, 256 }, { 8, 253, 256 }, { 8, 254, 256 }, { 9, 255, 256 },
#if FP_LUT > 9
{ 1, 0, 0 }, { 2, 1, 512 }, { 2, 2, 512 }, { 3, 3, 512 }, { 2, 4, 512 }, { 3, 5, 512 }, { 3, 6, 512 }, { 4, 7, 512 },
{ 2, 8, 512 }, { 3, 9, 512 }, { 3, 10, 512 }, { 4, 11, 512 }, { 3, 12, 512 }, { 4, 13, 512 }, { 4, 14, 512 }, { 5, 15, 512 },
{ 2, 16, 512 }, { 3, 17, 512 }, { 3, 18, 512 }, { 4, 19, 512 }, { 3, 20, 512 }, { 4, 21, 512 }, { 4, 22, 512 }, { 5, 23, 512 },
{ 3, 24, 512 }, { 4, 25, 512 }, { 4, 26, 512 }, { 5, 27, 512 }, { 4, 28, 512 }, { 5, 29, 512 }, { 5, 30, 512 }, { 6, 31, 512 },
{ 2, 32, 512 }, { 3, 33, 512 }, { 3, 34, 512 }, { 4, 35, 512 }, { 3, 36, 512 }, { 4, 37, 512 }, { 4, 38, 512 }, { 5, 39, 512 },
{ 3, 40, 512 }, { 4, 41, 512 }, { 4, 42, 512 }, { 5, 43, 512 }, { 4, 44, 512 }, { 5, 45, 512 }, { 5, 46, 512 }, { 6, 47, 512 },
{ 3, 48, 512 }, { 4, 49, 512 }, { 4, 50, 512 }, { 5, 51, 512 }, { 4, 52, 512 }, { 5, 53, 512 }, { 5, 54, 512 }, { 6, 55, 512 },
{ 4, 56, 512 }, { 5, 57, 512 }, { 5, 58, 512 }, { 6, 59, 512 }, { 5, 60, 512 }, { 6, 61, 512 }, { 6, 62, 512 }, { 7, 63, 512 },
{ 2, 64, 512 }, { 3, 65, 512 }, { 3, 66, 512 }, { 4, 67, 512 }, { 3, 68, 512 }, { 4, 69, 512 }, { 4, 70, 512 }, { 5, 71, 512 },
{ 3, 72, 512 }, { 4, 73, 512 }, { 4, 74, 512 }, { 5, 75, 512 }, { 4, 76, 512 }, { 5, 77, 512 }, { 5, 78, 512 }, { 6, 79, 512 },
{ 3, 80, 512 }, { 4, 81, 512 }, { 4, 82, 512 }, { 5, 83, 512 }, { 4, 84, 512 }, { 5, 85, 512 }, { 5, 86, 512 }, { 6, 87, 512 },
{ 4, 88, 512 }, { 5, 89, 512 }, { 5, 90, 512 }, { 6, 91, 512 }, { 5, 92, 512 }, { 6, 93, 512 }, { 6, 94, 512 }, { 7, 95, 512 },
{ 3, 96, 512 }, { 4, 97, 512 }, { 4, 98, 512 }, { 5, 99, 512 }, { 4, 100, 512 }, { 5, 101, 512 }, { 5, 102, 512 }, { 6, 103, 512 },
{ 4, 104, 512 }, { 5, 105, 512 }, { 5, 106, 512 }, { 6, 107, 512 }, { 5, 108, 512 }, { 6, 109, 512 }, { 6, 110, 512 }, { 7, 111, 512 },
{ 4, 112, 512 }, { 5, 113, 512 }, { 5, 114, 512 }, { 6, 115, 512 }, { 5, 116, 512 }, { 6, 117, 512 }, { 6, 118, 512 }, { 7, 119, 512 },
{ 5, 120, 512 }, { 6, 121, 512 }, { 6, 122, 512 }, { 7, 123, 512 }, { 6, 124, 512 }, { 7, 125, 512 }, { 7, 126, 512 }, { 8, 127, 512 },
{ 2, 128, 512 }, { 3, 129, 512 }, { 3, 130, 512 }, { 4, 131, 512 }, { 3, 132, 512 }, { 4, 133, 512 }, { 4, 134, 512 }, { 5, 135, 512 },
{ 3, 136, 512 }, { 4, 137, 512 }, { 4, 138, 512 }, { 5, 139, 512 }, { 4, 140, 512 }, { 5, 141, 512 }, { 5, 142, 512 }, { 6, 143, 512 },
{ 3, 144, 512 }, { 4, 145, 512 }, { 4, 146, 512 }, { 5, 147, 512 }, { 4, 148, 512 }, { 5, 149, 512 }, { 5, 150, 512 }, { 6, 151, 512 },
{ 4, 152, 512 }, { 5, 153, 512 }, { 5, 154, 512 }, { 6, 155, 512 }, { 5, 156, 512 }, { 6, 157, 512 }, { 6, 158, 512 }, { 7, 159, 512 },
{ 3, 160, 512 }, { 4, 161, 512 }, { 4, 162, 512 }, { 5, 163, 512 }, { 4, 164, 512 }, { 5, 165, 512 }, { 5, 166, 512 }, { 6, 167, 512 },
{ 4, 168, 512 }, { 5, 169, 512 }, { 5, 170, 512 }, { 6, 171, 512 }, { 5, 172, 512 }, { 6, 173, 512 }, { 6, 174, 512 }, { 7, 175, 512 },
{ 4, 176, 512 }, { 5, 177, 512 }, { 5, 178, 512 }, { 6, 179, 512 }, { 5, 180, 512 }, { 6, 181, 512 }, { 6, 182, 512 }, { 7, 183, 512 },
{ 5, 184, 512 }, { 6, 185, 512 }, { 6, 186, 512 }, { 7, 187, 512 }, { 6, 188, 512 }, { 7, 189, 512 }, { 7, 190, 512 }, { 8, 191, 512 },
{ 3, 192, 512 }, { 4, 193, 512 }, { 4, 194, 512 }, { 5, 195, 512 }, { 4, 196, 512 }, { 5, 197, 512 }, { 5, 198, 512 }, { 6, 199, 512 },
{ 4, 200, 512 }, { 5, 201, 512 }, { 5, 202, 512 }, { 6, 203, 512 }, { 5, 204, 512 }, { 6, 205, 512 }, { 6, 206, 512 }, { 7, 207, 512 },
{ 4, 208, 512 }, { 5, 209, 512 }, { 5, 210, 512 }, { 6, 211, 512 }, { 5, 212, 512 }, { 6, 213, 512 }, { 6, 214, 512 }, { 7, 215, 512 },
{ 5, 216, 512 }, { 6, 217, 512 }, { 6, 218, 512 }, { 7, 219, 512 }, { 6, 220, 512 }, { 7, 221, 512 }, { 7, 222, 512 }, { 8, 223, 512 },
{ 4, 224, 512 }, { 5, 225, 512 }, { 5, 226, 512 }, { 6, 227, 512 }, { 5, 228, 512 }, { 6, 229, 512 }, { 6, 230, 512 }, { 7, 231, 512 },
{ 5, 232, 512 }, { 6, 233, 512 }, { 6, 234, 512 }, { 7, 235, 512 }, { 6, 236, 512 }, { 7, 237, 512 }, { 7, 238, 512 }, { 8, 239, 512 },
{ 5, 240, 512 }, { 6, 241, 512 }, { 6, 242, 512 }, { 7, 243, 512 }, { 6, 244, 512 }, { 7, 245, 512 }, { 7, 246, 512 }, { 8, 247, 512 },
{ 6, 248, 512 }, { 7, 249, 512 }, { 7, 250, 512 }, { 8, 251, 512 }, { 7, 252, 512 }, { 8, 253, 512 }, { 8, 254, 512 }, { 9, 255, 512 },
{ 2, 256, 512 }, { 3, 257, 512 }, { 3, 258, 512 }, { 4, 259, 512 }, { 3, 260, 512 }, { 4, 261, 512 }, { 4, 262, 512 }, { 5, 263, 512 },
{ 3, 264, 512 }, { 4, 265, 512 }, { 4, 266, 512 }, { 5, 267, 512 }, { 4, 268, 512 }, { 5, 269, 512 }, { 5, 270, 512 }, { 6, 271, 512 },
{ 3, 272, 512 }, { 4, 273, 512 }, { 4, 274, 512 }, { 5, 275, 512 }, { 4, 276, 512 }, { 5, 277, 512 }, { 5, 278, 512 }, { 6, 279, 512 },
{ 4, 280, 512 }, { 5, 281, 512 }, { 5, 282, 512 }, { 6, 283, 512 }, { 5, 284, 512 }, { 6, 285, 512 }, { 6, 286, 512 }, { 7, 287, 512 },
{ 3, 288, 512 }, { 4, 289, 512 }, { 4, 290, 512 }, { 5, 291, 512 }, { 4, 292, 512 }, { 5, 293, 512 }, { 5, 294, 512 }, { 6, 295, 512 },
{ 4, 296, 512 }, { 5, 297, 512 }, { 5, 298, 512 }, { 6, 299, 512 }, { 5, 300, 512 }, { 6, 301, 512 }, { 6, 302, 512 }, { 7, 303, 512 },
{ 4, 304, 512 }, { 5, 305, 512 }, { 5, 306, 512 }, { 6, 307, 512 }, { 5, 308, 512 }, { 6, 309, 512 }, { 6, 310, 512 }, { 7, 311, 512 },
{ 5, 312, 512 }, { 6, 313, 512 }, { 6, 314, 512 }, { 7, 315, 512 }, { 6, 316, 512 }, { 7, 317, 512 }, { 7, 318, 512 }, { 8, 319, 512 },
{ 3, 320, 512 }, { 4, 321, 512 }, { 4, 322, 512 }, { 5, 323, 512 }, { 4, 324, 512 }, { 5, 325, 512 }, { 5, 326, 512 }, { 6, 327, 512 },
{ 4, 328, 512 }, { 5, 329, 512 }, { 5, 330, 512 }, { 6, 331, 512 }, { 5, 332, 512 }, { 6, 333, 512 }, { 6, 334, 512 }, { 7, 335, 512 },
{ 4, 336, 512 }, { 5, 337, 512 }, { 5, 338, 512 }, { 6, 339, 512 }, { 5, 340, 512 }, { 6, 341, 512 }, { 6, 342, 512 }, { 7, 343, 512 },
{ 5, 344, 512 }, { 6, 345, 512 }, { 6, 346, 512 }, { 7, 347, 512 }, { 6, 348, 512 }, { 7, 349, 512 }, { 7, 350, 512 }, { 8, 351, 512 },
{ 4, 352, 512 }, { 5, 353, 512 }, { 5, 354, 512 }, { 6, 355, 512 }, { 5, 356, 512 }, { 6, 357, 512 }, { 6, 358, 512 }, { 7, 359, 512 },
{ 5, 360, 512 }, { 6, 361, 512 }, { 6, 362, 512 }, { 7, 363, 512 }, { 6, 364, 512 }, { 7, 365, 512 }, { 7, 366, 512 }, { 8, 367, 512 },
{ 5, 368, 512 }, { 6, 369, 512 }, { 6, 370, 512 }, { 7, 371, 512 }, { 6, 372, 512 }, { 7, 373, 512 }, { 7, 374, 512 }, { 8, 375, 512 },
{ 6, 376, 512 }, { 7, 377, 512 }, { 7, 378, 512 }, { 8, 379, 512 }, { 7, 380, 512 }, { 8, 381, 512 }, { 8, 382, 512 }, { 9, 383, 512 },
{ 3, 384, 512 }, { 4, 385, 512 }, { 4, 386, 512 }, { 5, 387, 512 }, { 4, 388, 512 }, { 5, 389, 512 }, { 5, 390, 512 }, { 6, 391, 512 },
{ 4, 392, 512 }, { 5, 393, 512 }, { 5, 394, 512 }, { 6, 395, 512 }, { 5, 396, 512 }, { 6, 397, 512 }, { 6, 398, 512 }, { 7, 399, 512 },
{ 4, 400, 512 }, { 5, 401, 512 }, { 5, 402, 512 }, { 6, 403, 512 }, { 5, 404, 512 }, { 6, 405, 512 }, { 6, 406, 512 }, { 7, 407, 512 },
{ 5, 408, 512 }, { 6, 409, 512 }, { 6, 410, 512 }, { 7, 411, 512 }, { 6, 412, 512 }, { 7, 413, 512 }, { 7, 414, 512 }, { 8, 415, 512 },
{ 4, 416, 512 }, { 5, 417, 512 }, { 5, 418, 512 }, { 6, 419, 512 }, { 5, 420, 512 }, { 6, 421, 512 }, { 6, 422, 512 }, { 7, 423, 512 },
{ 5, 424, 512 }, { 6, 425, 512 }, { 6, 426, 512 }, { 7, 427, 512 }, { 6, 428, 512 }, { 7, 429, 512 }, { 7, 430, 512 }, { 8, 431, 512 },
{ 5, 432, 512 }, { 6, 433, 512 }, { 6, 434, 512 }, { 7, 435, 512 }, { 6, 436, 512 }, { 7, 437, 512 }, { 7, 438, 512 }, { 8, 439, 512 },
{ 6, 440, 512 }, { 7, 441, 512 }, { 7, 442, 512 }, { 8, 443, 512 }, { 7, 444, 512 }, { 8, 445, 512 }, { 8, 446, 512 }, { 9, 447, 512 },
{ 4, 448, 512 }, { 5, 449, 512 }, { 5, 450, 512 }, { 6, 451, 512 }, { 5, 452, 512 }, { 6, 453, 512 }, { 6, 454, 512 }, { 7, 455, 512 },
{ 5, 456, 512 }, { 6, 457, 512 }, { 6, 458, 512 }, { 7, 459, 512 }, { 6, 460, 512 }, { 7, 461, 512 }, { 7, 462, 512 }, { 8, 463, 512 },
{ 5, 464, 512 }, { 6, 465, 512 }, { 6, 466, 512 }, { 7, 467, 512 }, { 6, 468, 512 }, { 7, 469, 512 }, { 7, 470, 512 }, { 8, 471, 512 },
{ 6, 472, 512 }, { 7, 473, 512 }, { 7, 474, 512 }, { 8, 475, 512 }, { 7, 476, 512 }, { 8, 477, 512 }, { 8, 478, 512 }, { 9, 479, 512 },
{ 5, 480, 512 }, { 6, 481, 512 }, { 6, 482, 512 }, { 7, 483, 512 }, { 6, 484, 512 }, { 7, 485, 512 }, { 7, 486, 512 }, { 8, 487, 512 },
{ 6, 488, 512 }, { 7, 489, 512 }, { 7, 490, 512 }, { 8, 491, 512 }, { 7, 492, 512 }, { 8, 493, 512 }, { 8, 494, 512 }, { 9, 495, 512 },
{ 6, 496, 512 }, { 7, 497, 512 }, { 7, 498, 512 }, { 8, 499, 512 }, { 7, 500, 512 }, { 8, 501, 512 }, { 8, 502, 512 }, { 9, 503, 512 },
{ 7, 504, 512 }, { 8, 505, 512 }, { 8, 506, 512 }, { 9, 507, 512 }, { 8, 508, 512 }, { 9, 509, 512 }, { 9, 510, 512 }, { 10, 511, 512 },
#if FP_LUT > 10
{ 1, 0, 0 }, { 2, 1, 1024 }, { 2, 2, 1024 }, { 3, 3, 1024 }, { 2, 4, 1024 }, { 3, 5, 1024 }, { 3, 6, 1024 }, { 4, 7, 1024 },
{ 2, 8, 1024 }, { 3, 9, 1024 }, { 3, 10, 1024 }, { 4, 11, 1024 }, { 3, 12, 1024 }, { 4, 13, 1024 }, { 4, 14, 1024 }, { 5, 15, 1024 },
{ 2, 16, 1024 }, { 3, 17, 1024 }, { 3, 18, 1024 }, { 4, 19, 1024 }, { 3, 20, 1024 }, { 4, 21, 1024 }, { 4, 22, 1024 }, { 5, 23, 1024 },
{ 3, 24, 1024 }, { 4, 25, 1024 }, { 4, 26, 1024 }, { 5, 27, 1024 }, { 4, 28, 1024 }, { 5, 29, 1024 }, { 5, 30, 1024 }, { 6, 31, 1024 },
{ 2, 32, 1024 }, { 3, 33, 1024 }, { 3, 34, 1024 }, { 4, 35, 1024 }, { 3, 36, 1024 }, { 4, 37, 1024 }, { 4, 38, 1024 }, { 5, 39, 1024 },
{ 3, 40, 1024 }, { 4, 41, 1024 }, { 4, 42, 1024 }, { 5, 43, 1024 }, { 4, 44, 1024 }, { 5, 45, 1024 }, { 5, 46, 1024 }, { 6, 47, 1024 },
{ 3, 48, 1024 }, { 4, 49, 1024 }, { 4, 50, 1024 }, { 5, 51, 1024 }, { 4, 52, 1024 }, { 5, 53, 1024 }, { 5, 54, 1024 }, { 6, 55, 1024 },
{ 4, 56, 1024 }, { 5, 57, 1024 }, { 5, 58, 1024 }, { 6, 59, 1024 }, { 5, 60, 1024 }, { 6, 61, 1024 }, { 6, 62, 1024 }, { 7, 63, 1024 },
{ 2, 64, 1024 }, { 3, 65, 1024 }, { 3, 66, 1024 }, { 4, 67, 1024 }, { 3, 68, 1024 }, { 4, 69, 1024 }, { 4, 70, 1024 }, { 5, 71, 1024 },
{ 3, 72, 1024 }, { 4, 73, 1024 }, { 4, 74, 1024 }, { 5, 75, 1024 }, { 4, 76, 1024 }, { 5, 77, 1024 }, { 5, 78, 1024 }, { 6, 79, 1024 },
{ 3, 80, 1024 }, { 4, 81, 1024 }, { 4, 82, 1024 }, { 5, 83, 1024 }, { 4, 84, 1024 }, { 5, 85, 1024 }, { 5, 86, 1024 }, { 6, 87, 1024 },
{ 4, 88, 1024 }, { 5, 89, 1024 }, { 5, 90, 1024 }, { 6, 91, 1024 }, { 5, 92, 1024 }, { 6, 93, 1024 }, { 6, 94, 1024 }, { 7, 95, 1024 },
{ 3, 96, 1024 }, { 4, 97, 1024 }, { 4, 98, 1024 }, { 5, 99, 1024 }, { 4, 100, 1024 }, { 5, 101, 1024 }, { 5, 102, 1024 }, { 6, 103, 1024 },
{ 4, 104, 1024 }, { 5, 105, 1024 }, { 5, 106, 1024 }, { 6, 107, 1024 }, { 5, 108, 1024 }, { 6, 109, 1024 }, { 6, 110, 1024 }, { 7, 111, 1024 },
{ 4, 112, 1024 }, { 5, 113, 1024 }, { 5, 114, 1024 }, { 6, 115, 1024 }, { 5, 116, 1024 }, { 6, 117, 1024 }, { 6, 118, 1024 }, { 7, 119, 1024 },
{ 5, 120, 1024 }, { 6, 121, 1024 }, { 6, 122, 1024 }, { 7, 123, 1024 }, { 6, 124, 1024 }, { 7, 125, 1024 }, { 7, 126, 1024 }, { 8, 127, 1024 },
{ 2, 128, 1024 }, { 3, 129, 1024 }, { 3, 130, 1024 }, { 4, 131, 1024 }, { 3, 132, 1024 }, { 4, 133, 1024 }, { 4, 134, 1024 }, { 5, 135, 1024 },
{ 3, 136, 1024 }, { 4, 137, 1024 }, { 4, 138, 1024 }, { 5, 139, 1024 }, { 4, 140, 1024 }, { 5, 141, 1024 }, { 5, 142, 1024 }, { 6, 143, 1024 },
{ 3, 144, 1024 }, { 4, 145, 1024 }, { 4, 146, 1024 }, { 5, 147, 1024 }, { 4, 148, 1024 }, { 5, 149, 1024 }, { 5, 150, 1024 }, { 6, 151, 1024 },
{ 4, 152, 1024 }, { 5, 153, 1024 }, { 5, 154, 1024 }, { 6, 155, 1024 }, { 5, 156, 1024 }, { 6, 157, 1024 }, { 6, 158, 1024 }, { 7, 159, 1024 },
{ 3, 160, 1024 }, { 4, 161, 1024 }, { 4, 162, 1024 }, { 5, 163, 1024 }, { 4, 164, 1024 }, { 5, 165, 1024 }, { 5, 166, 1024 }, { 6, 167, 1024 },
{ 4, 168, 1024 }, { 5, 169, 1024 }, { 5, 170, 1024 }, { 6, 171, 1024 }, { 5, 172, 1024 }, { 6, 173, 1024 }, { 6, 174, 1024 }, { 7, 175, 1024 },
{ 4, 176, 1024 }, { 5, 177, 1024 }, { 5, 178, 1024 }, { 6, 179, 1024 }, { 5, 180, 1024 }, { 6, 181, 1024 }, { 6, 182, 1024 }, { 7, 183, 1024 },
{ 5, 184, 1024 }, { 6, 185, 1024 }, { 6, 186, 1024 }, { 7, 187, 1024 }, { 6, 188, 1024 }, { 7, 189, 1024 }, { 7, 190, 1024 }, { 8, 191, 1024 },
{ 3, 192, 1024 }, { 4, 193, 1024 }, { 4, 194, 1024 }, { 5, 195, 1024 }, { 4, 196, 1024 }, { 5, 197, 1024 }, { 5, 198, 1024 }, { 6, 199, 1024 },
{ 4, 200, 1024 }, { 5, 201, 1024 }, { 5, 202, 1024 }, { 6, 203, 1024 }, { 5, 204, 1024 }, { 6, 205, 1024 }, { 6, 206, 1024 }, { 7, 207, 1024 },
{ 4, 208, 1024 }, { 5, 209, 1024 }, { 5, 210, 1024 }, { 6, 211, 1024 }, { 5, 212, 1024 }, { 6, 213, 1024 }, { 6, 214, 1024 }, { 7, 215, 1024 },
{ 5, 216, 1024 }, { 6, 217, 1024 }, { 6, 218, 1024 }, { 7, 219, 1024 }, { 6, 220, 1024 }, { 7, 221, 1024 }, { 7, 222, 1024 }, { 8, 223, 1024 },
{ 4, 224, 1024 }, { 5, 225, 1024 }, { 5, 226, 1024 }, { 6, 227, 1024 }, { 5, 228, 1024 }, { 6, 229, 1024 }, { 6, 230, 1024 }, { 7, 231, 1024 },
{ 5, 232, 1024 }, { 6, 233, 1024 }, { 6, 234, 1024 }, { 7, 235, 1024 }, { 6, 236, 1024 }, { 7, 237, 1024 }, { 7, 238, 1024 }, { 8, 239, 1024 },
{ 5, 240, 1024 }, { 6, 241, 1024 }, { 6, 242, 1024 }, { 7, 243, 1024 }, { 6, 244, 1024 }, { 7, 245, 1024 }, { 7, 246, 1024 }, { 8, 247, 1024 },
{ 6, 248, 1024 }, { 7, 249, 1024 }, { 7, 250, 1024 }, { 8, 251, 1024 }, { 7, 252, 1024 }, { 8, 253, 1024 }, { 8, 254, 1024 }, { 9, 255, 1024 },
{ 2, 256, 1024 }, { 3, 257, 1024 }, { 3, 258, 1024 }, { 4, 259, 1024 }, { 3, 260, 1024 }, { 4, 261, 1024 }, { 4, 262, 1024 }, { 5, 263, 1024 },
{ 3, 264, 1024 }, { 4, 265, 1024 }, { 4, 266, 1024 }, { 5, 267, 1024 }, { 4, 268, 1024 }, { 5, 269, 1024 }, { 5, 270, 1024 }, { 6, 271, 1024 },
{ 3, 272, 1024 }, { 4, 273, 1024 }, { 4, 274, 1024 }, { 5, 275, 1024 }, { 4, 276, 1024 }, { 5, 277, 1024 }, { 5, 278, 1024 }, { 6, 279, 1024 },
{ 4, 280, 1024 }, { 5, 281, 1024 }, { 5, 282, 1024 }, { 6, 283, 1024 }, { 5, 284, 1024 }, { 6, 285, 1024 }, { 6, 286, 1024 }, { 7, 287, 1024 },
{ 3, 288, 1024 }, { 4, 289, 1024 }, { 4, 290, 1024 }, { 5, 291, 1024 }, { 4, 292, 1024 }, { 5, 293, 1024 }, { 5, 294, 1024 }, { 6, 295, 1024 },
{ 4, 296, 1024 }, { 5, 297, 1024 }, { 5, 298, 1024 }, { 6, 299, 1024 }, { 5, 300, 1024 }, { 6, 301, 1024 }, { 6, 302, 1024 }, { 7, 303, 1024 },
{ 4, 304, 1024 }, { 5, 305, 1024 }, { 5, 306, 1024 }, { 6, 307, 1024 }, { 5, 308, 1024 }, { 6, 309, 1024 }, { 6, 310, 1024 }, { 7, 311, 1024 },
{ 5, 312, 1024 }, { 6, 313, 1024 }, { 6, 314, 1024 }, { 7, 315, 1024 }, { 6, 316, 1024 }, { 7, 317, 1024 }, { 7, 318, 1024 }, { 8, 319, 1024 },
{ 3, 320, 1024 }, { 4, 321, 1024 }, { 4, 322, 1024 }, { 5, 323, 1024 }, { 4, 324, 1024 }, { 5, 325, 1024 }, { 5, 326, 1024 }, { 6, 327, 1024 },
{ 4, 328, 1024 }, { 5, 329, 1024 }, { 5, 330, 1024 }, { 6, 331, 1024 }, { 5, 332, 1024 }, { 6, 333, 1024 }, { 6, 334, 1024 }, { 7, 335, 1024 },
{ 4, 336, 1024 }, { 5, 337, 1024 }, { 5, 338, 1024 }, { 6, 339, 1024 }, { 5, 340, 1024 }, { 6, 341, 1024 }, { 6, 342, 1024 }, { 7, 343, 1024 },
{ 5, 344, 1024 }, { 6, 345, 1024 }, { 6, 346, 1024 }, { 7, 347, 1024 }, { 6, 348, 1024 }, { 7, 349, 1024 }, { 7, 350, 1024 }, { 8, 351, 1024 },
{ 4, 352, 1024 }, { 5, 353, 1024 }, { 5, 354, 1024 }, { 6, 355, 1024 }, { 5, 356, 1024 }, { 6, 357, 1024 }, { 6, 358, 1024 }, { 7, 359, 1024 },
{ 5, 360, 1024 }, { 6, 361, 1024 }, { 6, 362, 1024 }, { 7, 363, 1024 }, { 6, 364, 1024 }, { 7, 365, 1024 }, { 7, 366, 1024 }, { 8, 367, 1024 },
{ 5, 368, 1024 }, { 6, 369, 1024 }, { 6, 370, 1024 }, { 7, 371, 1024 }, { 6, 372, 1024 }, { 7, 373, 1024 }, { 7, 374, 1024 }, { 8, 375, 1024 },
{ 6, 376, 1024 }, { 7, 377, 1024 }, { 7, 378, 1024 }, { 8, 379, 1024 }, { 7, 380, 1024 }, { 8, 381, 1024 }, { 8, 382, 1024 }, { 9, 383, 1024 },
{ 3, 384, 1024 }, { 4, 385, 1024 }, { 4, 386, 1024 }, { 5, 387, 1024 }, { 4, 388, 1024 }, { 5, 389, 1024 }, { 5, 390, 1024 }, { 6, 391, 1024 },
{ 4, 392, 1024 }, { 5, 393, 1024 }, { 5, 394, 1024 }, { 6, 395, 1024 }, { 5, 396, 1024 }, { 6, 397, 1024 }, { 6, 398, 1024 }, { 7, 399, 1024 },
{ 4, 400, 1024 }, { 5, 401, 1024 }, { 5, 402, 1024 }, { 6, 403, 1024 }, { 5, 404, 1024 }, { 6, 405, 1024 }, { 6, 406, 1024 }, { 7, 407, 1024 },
{ 5, 408, 1024 }, { 6, 409, 1024 }, { 6, 410, 1024 }, { 7, 411, 1024 }, { 6, 412, 1024 }, { 7, 413, 1024 }, { 7, 414, 1024 }, { 8, 415, 1024 },
{ 4, 416, 1024 }, { 5, 417, 1024 }, { 5, 418, 1024 }, { 6, 419, 1024 }, { 5, 420, 1024 }, { 6, 421, 1024 }, { 6, 422, 1024 }, { 7, 423, 1024 },
{ 5, 424, 1024 }, { 6, 425, 1024 }, { 6, 426, 1024 }, { 7, 427, 1024 }, { 6, 428, 1024 }, { 7, 429, 1024 }, { 7, 430, 1024 }, { 8, 431, 1024 },
{ 5, 432, 1024 }, { 6, 433, 1024 }, { 6, 434, 1024 }, { 7, 435, 1024 }, { 6, 436, 1024 }, { 7, 437, 1024 }, { 7, 438, 1024 }, { 8, 439, 1024 },
{ 6, 440, 1024 }, { 7, 441, 1024 }, { 7, 442, 1024 }, { 8, 443, 1024 }, { 7, 444, 1024 }, { 8, 445, 1024 }, { 8, 446, 1024 }, { 9, 447, 1024 },
{ 4, 448, 1024 }, { 5, 449, 1024 }, { 5, 450, 1024 }, { 6, 451, 1024 }, { 5, 452, 1024 }, { 6, 453, 1024 }, { 6, 454, 1024 }, { 7, 455, 1024 },
{ 5, 456, 1024 }, { 6, 457, 1024 }, { 6, 458, 1024 }, { 7, 459, 1024 }, { 6, 460, 1024 }, { 7, 461, 1024 }, { 7, 462, 1024 }, { 8, 463, 1024 },
{ 5, 464, 1024 }, { 6, 465, 1024 }, { 6, 466, 1024 }, { 7, 467, 1024 }, { 6, 468, 1024 }, { 7, 469, 1024 }, { 7, 470, 1024 }, { 8, 471, 1024 },
{ 6, 472, 1024 }, { 7, 473, 1024 }, { 7, 474, 1024 }, { 8, 475, 1024 }, { 7, 476, 1024 }, { 8, 477, 1024 }, { 8, 478, 1024 }, { 9, 479, 1024 },
{ 5, 480, 1024 }, { 6, 481, 1024 }, { 6, 482, 1024 }, { 7, 483, 1024 }, { 6, 484, 1024 }, { 7, 485, 1024 }, { 7, 486, 1024 }, { 8, 487, 1024 },
{ 6, 488, 1024 }, { 7, 489, 1024 }, { 7, 490, 1024 }, { 8, 491, 1024 }, { 7, 492, 1024 }, { 8, 493, 1024 }, { 8, 494, 1024 }, { 9, 495, 1024 },
{ 6, 496, 1024 }, { 7, 497, 1024 }, { 7, 498, 1024 }, { 8, 499, 1024 }, { 7, 500, 1024 }, { 8, 501, 1024 }, { 8, 502, 1024 }, { 9, 503, 1024 },
{ 7, 504, 1024 }, { 8, 505, 1024 }, { 8, 506, 1024 }, { 9, 507, 1024 }, { 8, 508, 1024 }, { 9, 509, 1024 }, { 9, 510, 1024 }, { 10, 511, 1024 },
{ 2, 512, 1024 }, { 3, 513, 1024 }, { 3, 514, 1024 }, { 4, 515, 1024 }, { 3, 516, 1024 }, { 4, 517, 1024 }, { 4, 518, 1024 }, { 5, 519, 1024 },
{ 3, 520, 1024 }, { 4, 521, 1024 }, { 4, 522, 1024 }, { 5, 523, 1024 }, { 4, 524, 1024 }, { 5, 525, 1024 }, { 5, 526, 1024 }, { 6, 527, 1024 },
{ 3, 528, 1024 }, { 4, 529, 1024 }, { 4, 530, 1024 }, { 5, 531, 1024 }, { 4, 532, 1024 }, { 5, 533, 1024 }, { 5, 534, 1024 }, { 6, 535, 1024 },
{ 4, 536, 1024 }, { 5, 537, 1024 }, { 5, 538, 1024 }, { 6, 539, 1024 }, { 5, 540, 1024 }, { 6, 541, 1024 }, { 6, 542, 1024 }, { 7, 543, 1024 },
{ 3, 544, 1024 }, { 4, 545, 1024 }, { 4, 546, 1024 }, { 5, 547, 1024 }, { 4, 548, 1024 }, { 5, 549, 1024 }, { 5, 550, 1024 }, { 6, 551, 1024 },
{ 4, 552, 1024 }, { 5, 553, 1024 }, { 5, 554, 1024 }, { 6, 555, 1024 }, { 5, 556, 1024 }, { 6, 557, 1024 }, { 6, 558, 1024 }, { 7, 559, 1024 },
{ 4, 560, 1024 }, { 5, 561, 1024 }, { 5, 562, 1024 }, { 6, 563, 1024 }, { 5, 564, 1024 }, { 6, 565, 1024 }, { 6, 566, 1024 }, { 7, 567, 1024 },
{ 5, 568, 1024 }, { 6, 569, 1024 }, { 6, 570, 1024 }, { 7, 571, 1024 }, { 6, 572, 1024 }, { 7, 573, 1024 }, { 7, 574, 1024 }, { 8, 575, 1024 },
{ 3, 576, 1024 }, { 4, 577, 1024 }, { 4, 578, 1024 }, { 5, 579, 1024 }, { 4, 580, 1024 }, { 5, 581, 1024 }, { 5, 582, 1024 }, { 6, 583, 1024 },
{ 4, 584, 1024 }, { 5, 585, 1024 }, { 5, 586, 1024 }, { 6, 587, 1024 }, { 5, 588, 1024 }, { 6, 589, 1024 }, { 6, 590, 1024 }, { 7, 591, 1024 },
{ 4, 592, 1024 }, { 5, 593, 1024 }, { 5, 594, 1024 }, { 6, 595, 1024 }, { 5, 596, 1024 }, { 6, 597, 1024 }, { 6, 598, 1024 }, { 7, 599, 1024 },
{ 5, 600, 1024 }, { 6, 601, 1024 }, { 6, 602, 1024 }, { 7, 603, 1024 }, { 6, 604, 1024 }, { 7, 605, 1024 }, { 7, 606, 1024 }, { 8, 607, 1024 },
{ 4, 608, 1024 }, { 5, 609, 1024 }, { 5, 610, 1024 }, { 6, 611, 1024 }, { 5, 612, 1024 }, { 6, 613, 1024 }, { 6, 614, 1024 }, { 7, 615, 1024 },
{ 5, 616, 1024 }, { 6, 617, 1024 }, { 6, 618, 1024 }, { 7, 619, 1024 }, { 6, 620, 1024 }, { 7, 621, 1024 }, { 7, 622, 1024 }, { 8, 623, 1024 },
{ 5, 624, 1024 }, { 6, 625, 1024 }, { 6, 626, 1024 }, { 7, 627, 1024 }, { 6, 628, 1024 }, { 7, 629, 1024 }, { 7, 630, 1024 }, { 8, 631, 1024 },
{ 6, 632, 1024 }, { 7, 633, 1024 }, { 7, 634, 1024 }, { 8, 635, 1024 }, { 7, 636, 1024 }, { 8, 637, 1024 }, { 8, 638, 1024 }, { 9, 639, 1024 },
{ 3, 640, 1024 }, { 4, 641, 1024 }, { 4, 642, 1024 }, { 5, 643, 1024 }, { 4, 644, 1024 }, { 5, 645, 1024 }, { 5, 646, 1024 }, { 6, 647, 1024 },
{ 4, 648, 1024 }, { 5, 649, 1024 }, { 5, 650, 1024 }, { 6, 651, 1024 }, { 5, 652, 1024 }, { 6, 653, 1024 }, { 6, 654, 1024 }, { 7, 655, 1024 },
{ 4, 656, 1024 }, { 5, 657, 1024 }, { 5, 658, 1024 }, { 6, 659, 1024 }, { 5, 660, 1024 }, { 6, 661, 1024 }, { 6, 662, 1024 }, { 7, 663, 1024 },
{ 5, 664, 1024 }, { 6, 665, 1024 }, { 6, 666, 1024 }, { 7, 667, 1024 }, { 6, 668, 1024 }, { 7, 669, 1024 }, { 7, 670, 1024 }, { 8, 671, 1024 },
{ 4, 672, 1024 }, { 5, 673, 1024 }, { 5, 674, 1024 }, { 6, 675, 1024 }, { 5, 676, 1024 }, { 6, 677, 1024 }, { 6, 678, 1024 }, { 7, 679, 1024 },
{ 5, 680, 1024 }, { 6, 681, 1024 }, { 6, 682, 1024 }, { 7, 683, 1024 }, { 6, 684, 1024 }, { 7, 685, 1024 }, { 7, 686, 1024 }, { 8, 687, 1024 },
{ 5, 688, 1024 }, { 6, 689, 1024 }, { 6, 690, 1024 }, { 7, 691, 1024 }, { 6, 692, 1024 }, { 7, 693, 1024 }, { 7, 694, 1024 }, { 8, 695, 1024 },
{ 6, 696, 1024 }, { 7, 697, 1024 }, { 7, 698, 1024 }, { 8, 699, 1024 }, { 7, 700, 1024 }, { 8, 701, 1024 }, { 8, 702, 1024 }, { 9, 703, 1024 },
{ 4, 704, 1024 }, { 5, 705, 1024 }, { 5, 706, 1024 }, { 6, 707, 1024 }, { 5, 708, 1024 }, { 6, 709, 1024 }, { 6, 710, 1024 }, { 7, 711, 1024 },
{ 5, 712, 1024 }, { 6, 713, 1024 }, { 6, 714, 1024 }, { 7, 715, 1024 }, { 6, 716, 1024 }, { 7, 717, 1024 }, { 7, 718, 1024 }, { 8, 719, 1024 },
{ 5, 720, 1024 }, { 6, 721, 1024 }, { 6, 722, 1024 }, { 7, 723, 1024 }, { 6, 724, 1024 }, { 7, 725, 1024 }, { 7, 726, 1024 }, { 8, 727, 1024 },
{ 6, 728, 1024 }, { 7, 729, 1024 }, { 7, 730, 1024 }, { 8, 731, 1024 }, { 7, 732, 1024 }, { 8, 733, 1024 }, { 8, 734, 1024 }, { 9, 735, 1024 },
{ 5, 736, 1024 }, { 6, 737, 1024 }, { 6, 738, 1024 }, { 7, 739, 1024 }, { 6, 740, 1024 }, { 7, 741, 1024 }, { 7, 742, 1024 }, { 8, 743, 1024 },
{ 6, 744, 1024 }, { 7, 745, 1024 }, { 7, 746, 1024 }, { 8, 747, 1024 }, { 7, 748, 1024 }, { 8, 749, 1024 }, { 8, 750, 1024 }, { 9, 751, 1024 },
{ 6, 752, 1024 }, { 7, 753, 1024 }, { 7, 754, 1024 }, { 8, 755, 1024 }, { 7, 756, 1024 }, { 8, 757, 1024 }, { 8, 758, 1024 }, { 9, 759, 1024 },
{ 7, 760, 1024 }, { 8, 761, 1024 }, { 8, 762, 1024 }, { 9, 763, 1024 }, { 8, 764, 1024 }, { 9, 765, 1024 }, { 9, 766, 1024 }, { 10, 767, 1024 },
{ 3, 768, 1024 }, { 4, 769, 1024 }, { 4, 770, 1024 }, { 5, 771, 1024 }, { 4, 772, 1024 }, { 5, 773, 1024 }, { 5, 774, 1024 }, { 6, 775, 1024 },
{ 4, 776, 1024 }, { 5, 777, 1024 }, { 5, 778, 1024 }, { 6, 779, 1024 }, { 5, 780, 1024 }, { 6, 781, 1024 }, { 6, 782, 1024 }, { 7, 783, 1024 },
{ 4, 784, 1024 }, { 5, 785, 1024 }, { 5, 786, 1024 }, { 6, 787, 1024 }, { 5, 788, 1024 }, { 6, 789, 1024 }, { 6, 790, 1024 }, { 7, 791, 1024 },
{ 5, 792, 1024 }, { 6, 793, 1024 }, { 6, 794, 1024 }, { 7, 795, 1024 }, { 6, 796, 1024 }, { 7, 797, 1024 }, { 7, 798, 1024 }, { 8, 799, 1024 },
{ 4, 800, 1024 }, { 5, 801, 1024 }, { 5, 802, 1024 }, { 6, 803, 1024 }, { 5, 804, 1024 }, { 6, 805, 1024 }, { 6, 806, 1024 }, { 7, 807, 1024 },
{ 5, 808, 1024 }, { 6, 809, 1024 }, { 6, 810, 1024 }, { 7, 811, 1024 }, { 6, 812, 1024 }, { 7, 813, 1024 }, { 7, 814, 1024 }, { 8, 815, 1024 },
{ 5, 816, 1024 }, { 6, 817, 1024 }, { 6, 818, 1024 }, { 7, 819, 1024 }, { 6, 820, 1024 }, { 7, 821, 1024 }, { 7, 822, 1024 }, { 8, 823, 1024 },
{ 6, 824, 1024 }, { 7, 825, 1024 }, { 7, 826, 1024 }, { 8, 827, 1024 }, { 7, 828, 1024 }, { 8, 829, 1024 }, { 8, 830, 1024 }, { 9, 831, 1024 },
{ 4, 832, 1024 }, { 5, 833, 1024 }, { 5, 834, 1024 }, { 6, 835, 1024 }, { 5, 836, 1024 }, { 6, 837, 1024 }, { 6, 838, 1024 }, { 7, 839, 1024 },
{ 5, 840, 1024 }, { 6, 841, 1024 }, { 6, 842, 1024 }, { 7, 843, 1024 }, { 6, 844, 1024 }, { 7, 845, 1024 }, { 7, 846, 1024 }, { 8, 847, 1024 },
{ 5, 848, 1024 }, { 6, 849, 1024 }, { 6, 850, 1024 }, { 7, 851, 1024 }, { 6, 852, 1024 }, { 7, 853, 1024 }, { 7, 854, 1024 }, { 8, 855, 1024 },
{ 6, 856, 1024 }, { 7, 857, 1024 }, { 7, 858, 1024 }, { 8, 859, 1024 }, { 7, 860, 1024 }, { 8, 861, 1024 }, { 8, 862, 1024 }, { 9, 863, 1024 },
{ 5, 864, 1024 }, { 6, 865, 1024 }, { 6, 866, 1024 }, { 7, 867, 1024 }, { 6, 868, 1024 }, { 7, 869, 1024 }, { 7, 870, 1024 }, { 8, 871, 1024 },
{ 6, 872, 1024 }, { 7, 873, 1024 }, { 7, 874, 1024 }, { 8, 875, 1024 }, { 7, 876, 1024 }, { 8, 877, 1024 }, { 8, 878, 1024 }, { 9, 879, 1024 },
{ 6, 880, 1024 }, { 7, 881, 1024 }, { 7, 882, 1024 }, { 8, 883, 1024 }, { 7, 884, 1024 }, { 8, 885, 1024 }, { 8, 886, 1024 }, { 9, 887, 1024 },
{ 7, 888, 1024 }, { 8, 889, 1024 }, { 8, 890, 1024 }, { 9, 891, 1024 }, { 8, 892, 1024 }, { 9, 893, 1024 }, { 9, 894, 1024 }, { 10, 895, 1024 },
{ 4, 896, 1024 }, { 5, 897, 1024 }, { 5, 898, 1024 }, { 6, 899, 1024 }, { 5, 900, 1024 }, { 6, 901, 1024 }, { 6, 902, 1024 }, { 7, 903, 1024 },
{ 5, 904, 1024 }, { 6, 905, 1024 }, { 6, 906, 1024 }, { 7, 907, 1024 }, { 6, 908, 1024 }, { 7, 909, 1024 }, { 7, 910, 1024 }, { 8, 911, 1024 },
{ 5, 912, 1024 }, { 6, 913, 1024 }, { 6, 914, 1024 }, { 7, 915, 1024 }, { 6, 916, 1024 }, { 7, 917, 1024 }, { 7, 918, 1024 }, { 8, 919, 1024 },
{ 6, 920, 1024 }, { 7, 921, 1024 }, { 7, 922, 1024 }, { 8, 923, 1024 }, { 7, 924, 1024 }, { 8, 925, 1024 }, { 8, 926, 1024 }, { 9, 927, 1024 },
{ 5, 928, 1024 }, { 6, 929, 1024 }, { 6, 930, 1024 }, { 7, 931, 1024 }, { 6, 932, 1024 }, { 7, 933, 1024 }, { 7, 934, 1024 }, { 8, 935, 1024 },
{ 6, 936, 1024 }, { 7, 937, 1024 }, { 7, 938, 1024 }, { 8, 939, 1024 }, { 7, 940, 1024 }, { 8, 941, 1024 }, { 8, 942, 1024 }, { 9, 943, 1024 },
{ 6, 944, 1024 }, { 7, 945, 1024 }, { 7, 946, 1024 }, { 8, 947, 1024 }, { 7, 948, 1024 }, { 8, 949, 1024 }, { 8, 950, 1024 }, { 9, 951, 1024 },
{ 7, 952, 1024 }, { 8, 953, 1024 }, { 8, 954, 1024 }, { 9, 955, 1024 }, { 8, 956, 1024 }, { 9, 957, 1024 }, { 9, 958, 1024 }, { 10, 959, 1024 },
{ 5, 960, 1024 }, { 6, 961, 1024 }, { 6, 962, 1024 }, { 7, 963, 1024 }, { 6, 964, 1024 }, { 7, 965, 1024 }, { 7, 966, 1024 }, { 8, 967, 1024 },
{ 6, 968, 1024 }, { 7, 969, 1024 }, { 7, 970, 1024 }, { 8, 971, 1024 }, { 7, 972, 1024 }, { 8, 973, 1024 }, { 8, 974, 1024 }, { 9, 975, 1024 },
{ 6, 976, 1024 }, { 7, 977, 1024 }, { 7, 978, 1024 }, { 8, 979, 1024 }, { 7, 980, 1024 }, { 8, 981, 1024 }, { 8, 982, 1024 }, { 9, 983, 1024 },
{ 7, 984, 1024 }, { 8, 985, 1024 }, { 8, 986, 1024 }, { 9, 987, 1024 }, { 8, 988, 1024 }, { 9, 989, 1024 }, { 9, 990, 1024 }, { 10, 991, 1024 },
{ 6, 992, 1024 }, { 7, 993, 1024 }, { 7, 994, 1024 }, { 8, 995, 1024 }, { 7, 996, 1024 }, { 8, 997, 1024 }, { 8, 998, 1024 }, { 9, 999, 1024 },
{ 7, 1000, 1024 }, { 8, 1001, 1024 }, { 8, 1002, 1024 }, { 9, 1003, 1024 }, { 8, 1004, 1024 }, { 9, 1005, 1024 }, { 9, 1006, 1024 }, { 10, 1007, 1024 },
{ 7, 1008, 1024 }, { 8, 1009, 1024 }, { 8, 1010, 1024 }, { 9, 1011, 1024 }, { 8, 1012, 1024 }, { 9, 1013, 1024 }, { 9, 1014, 1024 }, { 10, 1015, 1024 },
{ 8, 1016, 1024 }, { 9, 1017, 1024 }, { 9, 1018, 1024 }, { 10, 1019, 1024 }, { 9, 1020, 1024 }, { 10, 1021, 1024 }, { 10, 1022, 1024 }, { 11, 1023, 1024 },
#if FP_LUT > 11
{ 1, 0, 0 }, { 2, 1, 2048 }, { 2, 2, 2048 }, { 3, 3, 2048 }, { 2, 4, 2048 }, { 3, 5, 2048 }, { 3, 6, 2048 }, { 4, 7, 2048 },
{ 2, 8, 2048 }, { 3, 9, 2048 }, { 3, 10, 2048 }, { 4, 11, 2048 }, { 3, 12, 2048 }, { 4, 13, 2048 }, { 4, 14, 2048 }, { 5, 15, 2048 },
{ 2, 16, 2048 }, { 3, 17, 2048 }, { 3, 18, 2048 }, { 4, 19, 2048 }, { 3, 20, 2048 }, { 4, 21, 2048 }, { 4, 22, 2048 }, { 5, 23, 2048 },
{ 3, 24, 2048 }, { 4, 25, 2048 }, { 4, 26, 2048 }, { 5, 27, 2048 }, { 4, 28, 2048 }, { 5, 29, 2048 }, { 5, 30, 2048 }, { 6, 31, 2048 },
{ 2, 32, 2048 }, { 3, 33, 2048 }, { 3, 34, 2048 }, { 4, 35, 2048 }, { 3, 36, 2048 }, { 4, 37, 2048 }, { 4, 38, 2048 }, { 5, 39, 2048 },
{ 3, 40, 2048 }, { 4, 41, 2048 }, { 4, 42, 2048 }, { 5, 43, 2048 }, { 4, 44, 2048 }, { 5, 45, 2048 }, { 5, 46, 2048 }, { 6, 47, 2048 },
{ 3, 48, 2048 }, { 4, 49, 2048 }, { 4, 50, 2048 }, { 5, 51, 2048 }, { 4, 52, 2048 }, { 5, 53, 2048 }, { 5, 54, 2048 }, { 6, 55, 2048 },
{ 4, 56, 2048 }, { 5, 57, 2048 }, { 5, 58, 2048 }, { 6, 59, 2048 }, { 5, 60, 2048 }, { 6, 61, 2048 }, { 6, 62, 2048 }, { 7, 63, 2048 },
{ 2, 64, 2048 }, { 3, 65, 2048 }, { 3, 66, 2048 }, { 4, 67, 2048 }, { 3, 68, 2048 }, { 4, 69, 2048 }, { 4, 70, 2048 }, { 5, 71, 2048 },
{ 3, 72, 2048 }, { 4, 73, 2048 }, { 4, 74, 2048 }, { 5, 75, 2048 }, { 4, 76, 2048 }, { 5, 77, 2048 }, { 5, 78, 2048 }, { 6, 79, 2048 },
{ 3, 80, 2048 }, { 4, 81, 2048 }, { 4, 82, 2048 }, { 5, 83, 2048 }, { 4, 84, 2048 }, { 5, 85, 2048 }, { 5, 86, 2048 }, { 6, 87, 2048 },
{ 4, 88, 2048 }, { 5, 89, 2048 }, { 5, 90, 2048 }, { 6, 91, 2048 }, { 5, 92, 2048 }, { 6, 93, 2048 }, { 6, 94, 2048 }, { 7, 95, 2048 },
{ 3, 96, 2048 }, { 4, 97, 2048 }, { 4, 98, 2048 }, { 5, 99, 2048 }, { 4, 100, 2048 }, { 5, 101, 2048 }, { 5, 102, 2048 }, { 6, 103, 2048 },
{ 4, 104, 2048 }, { 5, 105, 2048 }, { 5, 106, 2048 }, { 6, 107, 2048 }, { 5, 108, 2048 }, { 6, 109, 2048 }, { 6, 110, 2048 }, { 7, 111, 2048 },
{ 4, 112, 2048 }, { 5, 113, 2048 }, { 5, 114, 2048 }, { 6, 115, 2048 }, { 5, 116, 2048 }, { 6, 117, 2048 }, { 6, 118, 2048 }, { 7, 119, 2048 },
{ 5, 120, 2048 }, { 6, 121, 2048 }, { 6, 122, 2048 }, { 7, 123, 2048 }, { 6, 124, 2048 }, { 7, 125, 2048 }, { 7, 126, 2048 }, { 8, 127, 2048 },
{ 2, 128, 2048 }, { 3, 129, 2048 }, { 3, 130, 2048 }, { 4, 131, 2048 }, { 3, 132, 2048 }, { 4, 133, 2048 }, { 4, 134, 2048 }, { 5, 135, 2048 },
{ 3, 136, 2048 }, { 4, 137, 2048 }, { 4, 138, 2048 }, { 5, 139, 2048 }, { 4, 140, 2048 }, { 5, 141, 2048 }, { 5, 142, 2048 }, { 6, 143, 2048 },
{ 3, 144, 2048 }, { 4, 145, 2048 }, { 4, 146, 2048 }, { 5, 147, 2048 }, { 4, 148, 2048 }, { 5, 149, 2048 }, { 5, 150, 2048 }, { 6, 151, 2048 },
{ 4, 152, 2048 }, { 5, 153, 2048 }, { 5, 154, 2048 }, { 6, 155, 2048 }, { 5, 156, 2048 }, { 6, 157, 2048 }, { 6, 158, 2048 }, { 7, 159, 2048 },
{ 3, 160, 2048 }, { 4, 161, 2048 }, { 4, 162, 2048 }, { 5, 163, 2048 }, { 4, 164, 2048 }, { 5, 165, 2048 }, { 5, 166, 2048 }, { 6, 167, 2048 },
{ 4, 168, 2048 }, { 5, 169, 2048 }, { 5, 170, 2048 }, { 6, 171, 2048 }, { 5, 172, 2048 }, { 6, 173, 2048 }, { 6, 174, 2048 }, { 7, 175, 2048 },
{ 4, 176, 2048 }, { 5, 177, 2048 }, { 5, 178, 2048 }, { 6, 179, 2048 }, { 5, 180, 2048 }, { 6, 181, 2048 }, { 6, 182, 2048 }, { 7, 183, 2048 },
{ 5, 184, 2048 }, { 6, 185, 2048 }, { 6, 186, 2048 }, { 7, 187, 2048 }, { 6, 188, 2048 }, { 7, 189, 2048 }, { 7, 190, 2048 }, { 8, 191, 2048 },
{ 3, 192, 2048 }, { 4, 193, 2048 }, { 4, 194, 2048 }, { 5, 195, 2048 }, { 4, 196, 2048 }, { 5, 197, 2048 }, { 5, 198, 2048 }, { 6, 199, 2048 },
{ 4, 200, 2048 }, { 5, 201, 2048 }, { 5, 202, 2048 }, { 6, 203, 2048 }, { 5, 204, 2048 }, { 6, 205, 2048 }, { 6, 206, 2048 }, { 7, 207, 2048 },
{ 4, 208, 2048 }, { 5, 209, 2048 }, { 5, 210, 2048 }, { 6, 211, 2048 }, { 5, 212, 2048 }, { 6, 213, 2048 }, { 6, 214, 2048 }, { 7, 215, 2048 },
{ 5, 216, 2048 }, { 6, 217, 2048 }, { 6, 218, 2048 }, { 7, 219, 2048 }, { 6, 220, 2048 }, { 7, 221, 2048 }, { 7, 222, 2048 }, { 8, 223, 2048 },
{ 4, 224, 2048 }, { 5, 225, 2048 }, { 5, 226, 2048 }, { 6, 227, 2048 }, { 5, 228, 2048 }, { 6, 229, 2048 }, { 6, 230, 2048 }, { 7, 231, 2048 },
{ 5, 232, 2048 }, { 6, 233, 2048 }, { 6, 234, 2048 }, { 7, 235, 2048 }, { 6, 236, 2048 }, { 7, 237, 2048 }, { 7, 238, 2048 }, { 8, 239, 2048 },
{ 5, 240, 2048 }, { 6, 241, 2048 }, { 6, 242, 2048 }, { 7, 243, 2048 }, { 6, 244, 2048 }, { 7, 245, 2048 }, { 7, 246, 2048 }, { 8, 247, 2048 },
{ 6, 248, 2048 }, { 7, 249, 2048 }, { 7, 250, 2048 }, { 8, 251, 2048 }, { 7, 252, 2048 }, { 8, 253, 2048 }, { 8, 254, 2048 }, { 9, 255, 2048 },
{ 2, 256, 2048 }, { 3, 257, 2048 }, { 3, 258, 2048 }, { 4, 259, 2048 }, { 3, 260, 2048 }, { 4, 261, 2048 }, { 4, 262, 2048 }, { 5, 263, 2048 },
{ 3, 264, 2048 }, { 4, 265, 2048 }, { 4, 266, 2048 }, { 5, 267, 2048 }, { 4, 268, 2048 }, { 5, 269, 2048 }, { 5, 270, 2048 }, { 6, 271, 2048 },
{ 3, 272, 2048 }, { 4, 273, 2048 }, { 4, 274, 2048 }, { 5, 275, 2048 }, { 4, 276, 2048 }, { 5, 277, 2048 }, { 5, 278, 2048 }, { 6, 279, 2048 },
{ 4, 280, 2048 }, { 5, 281, 2048 }, { 5, 282, 2048 }, { 6, 283, 2048 }, { 5, 284, 2048 }, { 6, 285, 2048 }, { 6, 286, 2048 }, { 7, 287, 2048 },
{ 3, 288, 2048 }, { 4, 289, 2048 }, { 4, 290, 2048 }, { 5, 291, 2048 }, { 4, 292, 2048 }, { 5, 293, 2048 }, { 5, 294, 2048 }, { 6, 295, 2048 },
{ 4, 296, 2048 }, { 5, 297, 2048 }, { 5, 298, 2048 }, { 6, 299, 2048 }, { 5, 300, 2048 }, { 6, 301, 2048 }, { 6, 302, 2048 }, { 7, 303, 2048 },
{ 4, 304, 2048 }, { 5, 305, 2048 }, { 5, 306, 2048 }, { 6, 307, 2048 }, { 5, 308, 2048 }, { 6, 309, 2048 }, { 6, 310, 2048 }, { 7, 311, 2048 },
{ 5, 312, 2048 }, { 6, 313, 2048 }, { 6, 314, 2048 }, { 7, 315, 2048 }, { 6, 316, 2048 }, { 7, 317, 2048 }, { 7, 318, 2048 }, { 8, 319, 2048 },
{ 3, 320, 2048 }, { 4, 321, 2048 }, { 4, 322, 2048 }, { 5, 323, 2048 }, { 4, 324, 2048 }, { 5, 325, 2048 }, { 5, 326, 2048 }, { 6, 327, 2048 },
{ 4, 328, 2048 }, { 5, 329, 2048 }, { 5, 330, 2048 }, { 6, 331, 2048 }, { 5, 332, 2048 }, { 6, 333, 2048 }, { 6, 334, 2048 }, { 7, 335, 2048 },
{ 4, 336, 2048 }, { 5, 337, 2048 }, { 5, 338, 2048 }, { 6, 339, 2048 }, { 5, 340, 2048 }, { 6, 341, 2048 }, { 6, 342, 2048 }, { 7, 343, 2048 },
{ 5, 344, 2048 }, { 6, 345, 2048 }, { 6, 346, 2048 }, { 7, 347, 2048 }, { 6, 348, 2048 }, { 7, 349, 2048 }, { 7, 350, 2048 }, { 8, 351, 2048 },
{ 4, 352, 2048 }, { 5, 353, 2048 }, { 5, 354, 2048 }, { 6, 355, 2048 }, { 5, 356, 2048 }, { 6, 357, 2048 }, { 6, 358, 2048 }, { 7, 359, 2048 },
{ 5, 360, 2048 }, { 6, 361, 2048 }, { 6, 362, 2048 }, { 7, 363, 2048 }, { 6, 364, 2048 }, { 7, 365, 2048 }, { 7, 366, 2048 }, { 8, 367, 2048 },
{ 5, 368, 2048 }, { 6, 369, 2048 }, { 6, 370, 2048 }, { 7, 371, 2048 }, { 6, 372, 2048 }, { 7, 373, 2048 }, { 7, 374, 2048 }, { 8, 375, 2048 },
{ 6, 376, 2048 }, { 7, 377, 2048 }, { 7, 378, 2048 }, { 8, 379, 2048 }, { 7, 380, 2048 }, { 8, 381, 2048 }, { 8, 382, 2048 }, { 9, 383, 2048 },
{ 3, 384, 2048 }, { 4, 385, 2048 }, { 4, 386, 2048 }, { 5, 387, 2048 }, { 4, 388, 2048 }, { 5, 389, 2048 }, { 5, 390, 2048 }, { 6, 391, 2048 },
{ 4, 392, 2048 }, { 5, 393, 2048 }, { 5, 394, 2048 }, { 6, 395, 2048 }, { 5, 396, 2048 }, { 6, 397, 2048 }, { 6, 398, 2048 }, { 7, 399, 2048 },
{ 4, 400, 2048 }, { 5, 401, 2048 }, { 5, 402, 2048 }, { 6, 403, 2048 }, { 5, 404, 2048 }, { 6, 405, 2048 }, { 6, 406, 2048 }, { 7, 407, 2048 },
{ 5, 408, 2048 }, { 6, 409, 2048 }, { 6, 410, 2048 }, { 7, 411, 2048 }, { 6, 412, 2048 }, { 7, 413, 2048 }, { 7, 414, 2048 }, { 8, 415, 2048 },
{ 4, 416, 2048 }, { 5, 417, 2048 }, { 5, 418, 2048 }, { 6, 419, 2048 }, { 5, 420, 2048 }, { 6, 421, 2048 }, { 6, 422, 2048 }, { 7, 423, 2048 },
{ 5, 424, 2048 }, { 6, 425, 2048 }, { 6, 426, 2048 }, { 7, 427, 2048 }, { 6, 428, 2048 }, { 7, 429, 2048 }, { 7, 430, 2048 }, { 8, 431, 2048 },
{ 5, 432, 2048 }, { 6, 433, 2048 }, { 6, 434, 2048 }, { 7, 435, 2048 }, { 6, 436, 2048 }, { 7, 437, 2048 }, { 7, 438, 2048 }, { 8, 439, 2048 },
{ 6, 440, 2048 }, { 7, 441, 2048 }, { 7, 442, 2048 }, { 8, 443, 2048 }, { 7, 444, 2048 }, { 8, 445, 2048 }, { 8, 446, 2048 }, { 9, 447, 2048 },
{ 4, 448, 2048 }, { 5, 449, 2048 }, { 5, 450, 2048 }, { 6, 451, 2048 }, { 5, 452, 2048 }, { 6, 453, 2048 }, { 6, 454, 2048 }, { 7, 455, 2048 },
{ 5, 456, 2048 }, { 6, 457, 2048 }, { 6, 458, 2048 }, { 7, 459, 2048 }, { 6, 460, 2048 }, { 7, 461, 2048 }, { 7, 462, 2048 }, { 8, 463, 2048 },
{ 5, 464, 2048 }, { 6, 465, 2048 }, { 6, 466, 2048 }, { 7, 467, 2048 }, { 6, 468, 2048 }, { 7, 469, 2048 }, { 7, 470, 2048 }, { 8, 471, 2048 },
{ 6, 472, 2048 }, { 7, 473, 2048 }, { 7, 474, 2048 }, { 8, 475, 2048 }, { 7, 476, 2048 }, { 8, 477, 2048 }, { 8, 478, 2048 }, { 9, 479, 2048 },
{ 5, 480, 2048 }, { 6, 481, 2048 }, { 6, 482, 2048 }, { 7, 483, 2048 }, { 6, 484, 2048 }, { 7, 485, 2048 }, { 7, 486, 2048 }, { 8, 487, 2048 },
{ 6, 488, 2048 }, { 7, 489, 2048 }, { 7, 490, 2048 }, { 8, 491, 2048 }, { 7, 492, 2048 }, { 8, 493, 2048 }, { 8, 494, 2048 }, { 9, 495, 2048 },
{ 6, 496, 2048 }, { 7, 497, 2048 }, { 7, 498, 2048 }, { 8, 499, 2048 }, { 7, 500, 2048 }, { 8, 501, 2048 }, { 8, 502, 2048 }, { 9, 503, 2048 },
{ 7, 504, 2048 }, { 8, 505, 2048 }, { 8, 506, 2048 }, { 9, 507, 2048 }, { 8, 508, 2048 }, { 9, 509, 2048 }, { 9, 510, 2048 }, { 10, 511, 2048 },
{ 2, 512, 2048 }, { 3, 513, 2048 }, { 3, 514, 2048 }, { 4, 515, 2048 }, { 3, 516, 2048 }, { 4, 517, 2048 }, { 4, 518, 2048 }, { 5, 519, 2048 },
{ 3, 520, 2048 }, { 4, 521, 2048 }, { 4, 522, 2048 }, { 5, 523, 2048 }, { 4, 524, 2048 }, { 5, 525, 2048 }, { 5, 526, 2048 }, { 6, 527, 2048 },
{ 3, 528, 2048 }, { 4, 529, 2048 }, { 4, 530, 2048 }, { 5, 531, 2048 }, { 4, 532, 2048 }, { 5, 533, 2048 }, { 5, 534, 2048 }, { 6, 535, 2048 },
{ 4, 536, 2048 }, { 5, 537, 2048 }, { 5, 538, 2048 }, { 6, 539, 2048 }, { 5, 540, 2048 }, { 6, 541, 2048 }, { 6, 542, 2048 }, { 7, 543, 2048 },
{ 3, 544, 2048 }, { 4, 545, 2048 }, { 4, 546, 2048 }, { 5, 547, 2048 }, { 4, 548, 2048 }, { 5, 549, 2048 }, { 5, 550, 2048 }, { 6, 551, 2048 },
{ 4, 552, 2048 }, { 5, 553, 2048 }, { 5, 554, 2048 }, { 6, 555, 2048 }, { 5, 556, 2048 }, { 6, 557, 2048 }, { 6, 558, 2048 }, { 7, 559, 2048 },
{ 4, 560, 2048 }, { 5, 561, 2048 }, { 5, 562, 2048 }, { 6, 563, 2048 }, { 5, 564, 2048 }, { 6, 565, 2048 }, { 6, 566, 2048 }, { 7, 567, 2048 },
{ 5, 568, 2048 }, { 6, 569, 2048 }, { 6, 570, 2048 }, { 7, 571, 2048 }, { 6, 572, 2048 }, { 7, 573, 2048 }, { 7, 574, 2048 }, { 8, 575, 2048 },
{ 3, 576, 2048 }, { 4, 577, 2048 }, { 4, 578, 2048 }, { 5, 579, 2048 }, { 4, 580, 2048 }, { 5, 581, 2048 }, { 5, 582, 2048 }, { 6, 583, 2048 },
{ 4, 584, 2048 }, { 5, 585, 2048 }, { 5, 586, 2048 }, { 6, 587, 2048 }, { 5, 588, 2048 }, { 6, 589, 2048 }, { 6, 590, 2048 }, { 7, 591, 2048 },
{ 4, 592, 2048 }, { 5, 593, 2048 }, { 5, 594, 2048 }, { 6, 595, 2048 }, { 5, 596, 2048 }, { 6, 597, 2048 }, { 6, 598, 2048 }, { 7, 599, 2048 },
{ 5, 600, 2048 }, { 6, 601, 2048 }, { 6, 602, 2048 }, { 7, 603, 2048 }, { 6, 604, 2048 }, { 7, 605, 2048 }, { 7, 606, 2048 }, { 8, 607, 2048 },
{ 4, 608, 2048 }, { 5, 609, 2048 }, { 5, 610, 2048 }, { 6, 611, 2048 }, { 5, 612, 2048 }, { 6, 613, 2048 }, { 6, 614, 2048 }, { 7, 615, 2048 },
{ 5, 616, 2048 }, { 6, 617, 2048 }, { 6, 618, 2048 }, { 7, 619, 2048 }, { 6, 620, 2048 }, { 7, 621, 2048 }, { 7, 622, 2048 }, { 8, 623, 2048 },
{ 5, 624, 2048 }, { 6, 625, 2048 }, { 6, 626, 2048 }, { 7, 627, 2048 }, { 6, 628, 2048 }, { 7, 629, 2048 }, { 7, 630, 2048 }, { 8, 631, 2048 },
{ 6, 632, 2048 }, { 7, 633, 2048 }, { 7, 634, 2048 }, { 8, 635, 2048 }, { 7, 636, 2048 }, { 8, 637, 2048 }, { 8, 638, 2048 }, { 9, 639, 2048 },
{ 3, 640, 2048 }, { 4, 641, 2048 }, { 4, 642, 2048 }, { 5, 643, 2048 }, { 4, 644, 2048 }, { 5, 645, 2048 }, { 5, 646, 2048 }, { 6, 647, 2048 },
{ 4, 648, 2048 }, { 5, 649, 2048 }, { 5, 650, 2048 }, { 6, 651, 2048 }, { 5, 652, 2048 }, { 6, 653, 2048 }, { 6, 654, 2048 }, { 7, 655, 2048 },
{ 4, 656, 2048 }, { 5, 657, 2048 }, { 5, 658, 2048 }, { 6, 659, 2048 }, { 5, 660, 2048 }, { 6, 661, 2048 }, { 6, 662, 2048 }, { 7, 663, 2048 },
{ 5, 664, 2048 }, { 6, 665, 2048 }, { 6, 666, 2048 }, { 7, 667, 2048 }, { 6, 668, 2048 }, { 7, 669, 2048 }, { 7, 670, 2048 }, { 8, 671, 2048 },
{ 4, 672, 2048 }, { 5, 673, 2048 }, { 5, 674, 2048 }, { 6, 675, 2048 }, { 5, 676, 2048 }, { 6, 677, 2048 }, { 6, 678, 2048 }, { 7, 679, 2048 },
{ 5, 680, 2048 }, { 6, 681, 2048 }, { 6, 682, 2048 }, { 7, 683, 2048 }, { 6, 684, 2048 }, { 7, 685, 2048 }, { 7, 686, 2048 }, { 8, 687, 2048 },
{ 5, 688, 2048 }, { 6, 689, 2048 }, { 6, 690, 2048 }, { 7, 691, 2048 }, { 6, 692, 2048 }, { 7, 693, 2048 }, { 7, 694, 2048 }, { 8, 695, 2048 },
{ 6, 696, 2048 }, { 7, 697, 2048 }, { 7, 698, 2048 }, { 8, 699, 2048 }, { 7, 700, 2048 }, { 8, 701, 2048 }, { 8, 702, 2048 }, { 9, 703, 2048 },
{ 4, 704, 2048 }, { 5, 705, 2048 }, { 5, 706, 2048 }, { 6, 707, 2048 }, { 5, 708, 2048 }, { 6, 709, 2048 }, { 6, 710, 2048 }, { 7, 711, 2048 },
{ 5, 712, 2048 }, { 6, 713, 2048 }, { 6, 714, 2048 }, { 7, 715, 2048 }, { 6, 716, 2048 }, { 7, 717, 2048 }, { 7, 718, 2048 }, { 8, 719, 2048 },
{ 5, 720, 2048 }, { 6, 721, 2048 }, { 6, 722, 2048 }, { 7, 723, 2048 }, { 6, 724, 2048 }, { 7, 725, 2048 }, { 7, 726, 2048 }, { 8, 727, 2048 },
{ 6, 728, 2048 }, { 7, 729, 2048 }, { 7, 730, 2048 }, { 8, 731, 2048 }, { 7, 732, 2048 }, { 8, 733, 2048 }, { 8, 734, 2048 }, { 9, 735, 2048 },
{ 5, 736, 2048 }, { 6, 737, 2048 }, { 6, 738, 2048 }, { 7, 739, 2048 }, { 6, 740, 2048 }, { 7, 741, 2048 }, { 7, 742, 2048 }, { 8, 743, 2048 },
{ 6, 744, 2048 }, { 7, 745, 2048 }, { 7, 746, 2048 }, { 8, 747, 2048 }, { 7, 748, 2048 }, { 8, 749, 2048 }, { 8, 750, 2048 }, { 9, 751, 2048 },
{ 6, 752, 2048 }, { 7, 753, 2048 }, { 7, 754, 2048 }, { 8, 755, 2048 }, { 7, 756, 2048 }, { 8, 757, 2048 }, { 8, 758, 2048 }, { 9, 759, 2048 },
{ 7, 760, 2048 }, { 8, 761, 2048 }, { 8, 762, 2048 }, { 9, 763, 2048 }, { 8, 764, 2048 }, { 9, 765, 2048 }, { 9, 766, 2048 }, { 10, 767, 2048 },
{ 3, 768, 2048 }, { 4, 769, 2048 }, { 4, 770, 2048 }, { 5, 771, 2048 }, { 4, 772, 2048 }, { 5, 773, 2048 }, { 5, 774, 2048 }, { 6, 775, 2048 },
{ 4, 776, 2048 }, { 5, 777, 2048 }, { 5, 778, 2048 }, { 6, 779, 2048 }, { 5, 780, 2048 }, { 6, 781, 2048 }, { 6, 782, 2048 }, { 7, 783, 2048 },
{ 4, 784, 2048 }, { 5, 785, 2048 }, { 5, 786, 2048 }, { 6, 787, 2048 }, { 5, 788, 2048 }, { 6, 789, 2048 }, { 6, 790, 2048 }, { 7, 791, 2048 },
{ 5, 792, 2048 }, { 6, 793, 2048 }, { 6, 794, 2048 }, { 7, 795, 2048 }, { 6, 796, 2048 }, { 7, 797, 2048 }, { 7, 798, 2048 }, { 8, 799, 2048 },
{ 4, 800, 2048 }, { 5, 801, 2048 }, { 5, 802, 2048 }, { 6, 803, 2048 }, { 5, 804, 2048 }, { 6, 805, 2048 }, { 6, 806, 2048 }, { 7, 807, 2048 },
{ 5, 808, 2048 }, { 6, 809, 2048 }, { 6, 810, 2048 }, { 7, 811, 2048 }, { 6, 812, 2048 }, { 7, 813, 2048 }, { 7, 814, 2048 }, { 8, 815, 2048 },
{ 5, 816, 2048 }, { 6, 817, 2048 }, { 6, 818, 2048 }, { 7, 819, 2048 }, { 6, 820, 2048 }, { 7, 821, 2048 }, { 7, 822, 2048 }, { 8, 823, 2048 },
{ 6, 824, 2048 }, { 7, 825, 2048 }, { 7, 826, 2048 }, { 8, 827, 2048 }, { 7, 828, 2048 }, { 8, 829, 2048 }, { 8, 830, 2048 }, { 9, 831, 2048 },
{ 4, 832, 2048 }, { 5, 833, 2048 }, { 5, 834, 2048 }, { 6, 835, 2048 }, { 5, 836, 2048 }, { 6, 837, 2048 }, { 6, 838, 2048 }, { 7, 839, 2048 },
{ 5, 840, 2048 }, { 6, 841, 2048 }, { 6, 842, 2048 }, { 7, 843, 2048 }, { 6, 844, 2048 }, { 7, 845, 2048 }, { 7, 846, 2048 }, { 8, 847, 2048 },
{ 5, 848, 2048 }, { 6, 849, 2048 }, { 6, 850, 2048 }, { 7, 851, 2048 }, { 6, 852, 2048 }, { 7, 853, 2048 }, { 7, 854, 2048 }, { 8, 855, 2048 },
{ 6, 856, 2048 }, { 7, 857, 2048 }, { 7, 858, 2048 }, { 8, 859, 2048 }, { 7, 860, 2048 }, { 8, 861, 2048 }, { 8, 862, 2048 }, { 9, 863, 2048 },
{ 5, 864, 2048 }, { 6, 865, 2048 }, { 6, 866, 2048 }, { 7, 867, 2048 }, { 6, 868, 2048 }, { 7, 869, 2048 }, { 7, 870, 2048 }, { 8, 871, 2048 },
{ 6, 872, 2048 }, { 7, 873, 2048 }, { 7, 874, 2048 }, { 8, 875, 2048 }, { 7, 876, 2048 }, { 8, 877, 2048 }, { 8, 878, 2048 }, { 9, 879, 2048 },
{ 6, 880, 2048 }, { 7, 881, 2048 }, { 7, 882, 2048 }, { 8, 883, 2048 }, { 7, 884, 2048 }, { 8, 885, 2048 }, { 8, 886, 2048 }, { 9, 887, 2048 },
{ 7, 888, 2048 }, { 8, 889, 2048 }, { 8, 890, 2048 }, { 9, 891, 2048 }, { 8, 892, 2048 }, { 9, 893, 2048 }, { 9, 894, 2048 }, { 10, 895, 2048 },
{ 4, 896, 2048 }, { 5, 897, 2048 }, { 5, 898, 2048 }, { 6, 899, 2048 }, { 5, 900, 2048 }, { 6, 901, 2048 }, { 6, 902, 2048 }, { 7, 903, 2048 },
{ 5, 904, 2048 }, { 6, 905, 2048 }, { 6, 906, 2048 }, { 7, 907, 2048 }, { 6, 908, 2048 }, { 7, 909, 2048 }, { 7, 910, 2048 }, { 8, 911, 2048 },
{ 5, 912, 2048 }, { 6, 913, 2048 }, { 6, 914, 2048 }, { 7, 915, 2048 }, { 6, 916, 2048 }, { 7, 917, 2048 }, { 7, 918, 2048 }, { 8, 919, 2048 },
{ 6, 920, 2048 }, { 7, 921, 2048 }, { 7, 922, 2048 }, { 8, 923, 2048 }, { 7, 924, 2048 }, { 8, 925, 2048 }, { 8, 926, 2048 }, { 9, 927, 2048 },
{ 5, 928, 2048 }, { 6, 929, 2048 }, { 6, 930, 2048 }, { 7, 931, 2048 }, { 6, 932, 2048 }, { 7, 933, 2048 }, { 7, 934, 2048 }, { 8, 935, 2048 },
{ 6, 936, 2048 }, { 7, 937, 2048 }, { 7, 938, 2048 }, { 8, 939, 2048 }, { 7, 940, 2048 }, { 8, 941, 2048 }, { 8, 942, 2048 }, { 9, 943, 2048 },
{ 6, 944, 2048 }, { 7, 945, 2048 }, { 7, 946, 2048 }, { 8, 947, 2048 }, { 7, 948, 2048 }, { 8, 949, 2048 }, { 8, 950, 2048 }, { 9, 951, 2048 },
{ 7, 952, 2048 }, { 8, 953, 2048 }, { 8, 954, 2048 }, { 9, 955, 2048 }, { 8, 956, 2048 }, { 9, 957, 2048 }, { 9, 958, 2048 }, { 10, 959, 2048 },
{ 5, 960, 2048 }, { 6, 961, 2048 }, { 6, 962, 2048 }, { 7, 963, 2048 }, { 6, 964, 2048 }, { 7, 965, 2048 }, { 7, 966, 2048 }, { 8, 967, 2048 },
{ 6, 968, 2048 }, { 7, 969, 2048 }, { 7, 970, 2048 }, { 8, 971, 2048 }, { 7, 972, 2048 }, { 8, 973, 2048 }, { 8, 974, 2048 }, { 9, 975, 2048 },
{ 6, 976, 2048 }, { 7, 977, 2048 }, { 7, 978, 2048 }, { 8, 979, 2048 }, { 7, 980, 2048 }, { 8, 981, 2048 }, { 8, 982, 2048 }, { 9, 983, 2048 },
{ 7, 984, 2048 }, { 8, 985, 2048 }, { 8, 986, 2048 }, { 9, 987, 2048 }, { 8, 988, 2048 }, { 9, 989, 2048 }, { 9, 990, 2048 }, { 10, 991, 2048 },
{ 6, 992, 2048 }, { 7, 993, 2048 }, { 7, 994, 2048 }, { 8, 995, 2048 }, { 7, 996, 2048 }, { 8, 997, 2048 }, { 8, 998, 2048 }, { 9, 999, 2048 },
{ 7, 1000, 2048 }, { 8, 1001, 2048 }, { 8, 1002, 2048 }, { 9, 1003, 2048 }, { 8, 1004, 2048 }, { 9, 1005, 2048 }, { 9, 1006, 2048 }, { 10, 1007, 2048 },
{ 7, 1008, 2048 }, { 8, 1009, 2048 }, { 8, 1010, 2048 }, { 9, 1011, 2048 }, { 8, 1012, 2048 }, { 9, 1013, 2048 }, { 9, 1014, 2048 }, { 10, 1015, 2048 },
{ 8, 1016, 2048 }, { 9, 1017, 2048 }, { 9, 1018, 2048 }, { 10, 1019, 2048 }, { 9, 1020, 2048 }, { 10, 1021, 2048 }, { 10, 1022, 2048 }, { 11, 1023, 2048 },
{ 2, 1024, 2048 }, { 3, 1025, 2048 }, { 3, 1026, 2048 }, { 4, 1027, 2048 }, { 3, 1028, 2048 }, { 4, 1029, 2048 }, { 4, 1030, 2048 }, { 5, 1031, 2048 },
{ 3, 1032, 2048 }, { 4, 1033, 2048 }, { 4, 1034, 2048 }, { 5, 1035, 2048 }, { 4, 1036, 2048 }, { 5, 1037, 2048 }, { 5, 1038, 2048 }, { 6, 1039, 2048 },
{ 3, 1040, 2048 }, { 4, 1041, 2048 }, { 4, 1042, 2048 }, { 5, 1043, 2048 }, { 4, 1044, 2048 }, { 5, 1045, 2048 }, { 5, 1046, 2048 }, { 6, 1047, 2048 },
{ 4, 1048, 2048 }, { 5, 1049, 2048 }, { 5, 1050, 2048 }, { 6, 1051, 2048 }, { 5, 1052, 2048 }, { 6, 1053, 2048 }, { 6, 1054, 2048 }, { 7, 1055, 2048 },
{ 3, 1056, 2048 }, { 4, 1057, 2048 }, { 4, 1058, 2048 }, { 5, 1059, 2048 }, { 4, 1060, 2048 }, { 5, 1061, 2048 }, { 5, 1062, 2048 }, { 6, 1063, 2048 },
{ 4, 1064, 2048 }, { 5, 1065, 2048 }, { 5, 1066, 2048 }, { 6, 1067, 2048 }, { 5, 1068, 2048 }, { 6, 1069, 2048 }, { 6, 1070, 2048 }, { 7, 1071, 2048 },
{ 4, 1072, 2048 }, { 5, 1073, 2048 }, { 5, 1074, 2048 }, { 6, 1075, 2048 }, { 5, 1076, 2048 }, { 6, 1077, 2048 }, { 6, 1078, 2048 }, { 7, 1079, 2048 },
{ 5, 1080, 2048 }, { 6, 1081, 2048 }, { 6, 1082, 2048 }, { 7, 1083, 2048 }, { 6, 1084, 2048 }, { 7, 1085, 2048 }, { 7, 1086, 2048 }, { 8, 1087, 2048 },
{ 3, 1088, 2048 }, { 4, 1089, 2048 }, { 4, 1090, 2048 }, { 5, 1091, 2048 }, { 4, 1092, 2048 }, { 5, 1093, 2048 }, { 5, 1094, 2048 }, { 6, 1095, 2048 },
{ 4, 1096, 2048 }, { 5, 1097, 2048 }, { 5, 1098, 2048 }, { 6, 1099, 2048 }, { 5, 1100, 2048 }, { 6, 1101, 2048 }, { 6, 1102, 2048 }, { 7, 1103, 2048 },
{ 4, 1104, 2048 }, { 5, 1105, 2048 }, { 5, 1106, 2048 }, { 6, 1107, 2048 }, { 5, 1108, 2048 }, { 6, 1109, 2048 }, { 6, 1110, 2048 }, { 7, 1111, 2048 },
{ 5, 1112, 2048 }, { 6, 1113, 2048 }, { 6, 1114, 2048 }, { 7, 1115, 2048 }, { 6, 1116, 2048 }, { 7, 1117, 2048 }, { 7, 1118, 2048 }, { 8, 1119, 2048 },
{ 4, 1120, 2048 }, { 5, 1121, 2048 }, { 5, 1122, 2048 }, { 6, 1123, 2048 }, { 5, 1124, 2048 }, { 6, 1125, 2048 }, { 6, 1126, 2048 }, { 7, 1127, 2048 },
{ 5, 1128, 2048 }, { 6, 1129, 2048 }, { 6, 1130, 2048 }, { 7, 1131, 2048 }, { 6, 1132, 2048 }, { 7, 1133, 2048 }, { 7, 1134, 2048 }, { 8, 1135, 2048 },
{ 5, 1136, 2048 }, { 6, 1137, 2048 }, { 6, 1138, 2048 }, { 7, 1139, 2048 }, { 6, 1140, 2048 }, { 7, 1141, 2048 }, { 7, 1142, 2048 }, { 8, 1143, 2048 },
{ 6, 1144, 2048 }, { 7, 1145, 2048 }, { 7, 1146, 2048 }, { 8, 1147, 2048 }, { 7, 1148, 2048 }, { 8, 1149, 2048 }, { 8, 1150, 2048 }, { 9, 1151, 2048 },
{ 3, 1152, 2048 }, { 4, 1153, 2048 }, { 4, 1154, 2048 }, { 5, 1155, 2048 }, { 4, 1156, 2048 }, { 5, 1157, 2048 }, { 5, 1158, 2048 }, { 6, 1159, 2048 },
{ 4, 1160, 2048 }, { 5, 1161, 2048 }, { 5, 1162, 2048 }, { 6, 1163, 2048 }, { 5, 1164, 2048 }, { 6, 1165, 2048 }, { 6, 1166, 2048 }, { 7, 1167, 2048 },
{ 4, 1168, 2048 }, { 5, 1169, 2048 }, { 5, 1170, 2048 }, { 6, 1171, 2048 }, { 5, 1172, 2048 }, { 6, 1173, 2048 }, { 6, 1174, 2048 }, { 7, 1175, 2048 },
{ 5, 1176, 2048 }, { 6, 1177, 2048 }, { 6, 1178, 2048 }, { 7, 1179, 2048 }, { 6, 1180, 2048 }, { 7, 1181, 2048 }, { 7, 1182, 2048 }, { 8, 1183, 2048 },
{ 4, 1184, 2048 }, { 5, 1185, 2048 }, { 5, 1186, 2048 }, { 6, 1187, 2048 }, { 5, 1188, 2048 }, { 6, 1189, 2048 }, { 6, 1190, 2048 }, { 7, 1191, 2048 },
{ 5, 1192, 2048 }, { 6, 1193, 2048 }, { 6, 1194, 2048 }, { 7, 1195, 2048 }, { 6, 1196, 2048 }, { 7, 1197, 2048 }, { 7, 1198, 2048 }, { 8, 1199, 2048 },
{ 5, 1200, 2048 }, { 6, 1201, 2048 }, { 6, 1202, 2048 }, { 7, 1203, 2048 }, { 6, 1204, 2048 }, { 7, 1205, 2048 }, { 7, 1206, 2048 }, { 8, 1207, 2048 },
{ 6, 1208, 2048 }, { 7, 1209, 2048 }, { 7, 1210, 2048 }, { 8, 1211, 2048 }, { 7, 1212, 2048 }, { 8, 1213, 2048 }, { 8, 1214, 2048 }, { 9, 1215, 2048 },
{ 4, 1216, 2048 }, { 5, 1217, 2048 }, { 5, 1218, 2048 }, { 6, 1219, 2048 }, { 5, 1220, 2048 }, { 6, 1221, 2048 }, { 6, 1222, 2048 }, { 7, 1223, 2048 },
{ 5, 1224, 2048 }, { 6, 1225, 2048 }, { 6, 1226, 2048 }, { 7, 1227, 2048 }, { 6, 1228, 2048 }, { 7, 1229, 2048 }, { 7, 1230, 2048 }, { 8, 1231, 2048 },
{ 5, 1232, 2048 }, { 6, 1233, 2048 }, { 6, 1234, 2048 }, { 7, 1235, 2048 }, { 6, 1236, 2048 }, { 7, 1237, 2048 }, { 7, 1238, 2048 }, { 8, 1239, 2048 },
{ 6, 1240, 2048 }, { 7, 1241, 2048 }, { 7, 1242, 2048 }, { 8, 1243, 2048 }, { 7, 1244, 2048 }, { 8, 1245, 2048 }, { 8, 1246, 2048 }, { 9, 1247, 2048 },
{ 5, 1248, 2048 }, { 6, 1249, 2048 }, { 6, 1250, 2048 }, { 7, 1251, 2048 }, { 6, 1252, 2048 }, { 7, 1253, 2048 }, { 7, 1254, 2048 }, { 8, 1255, 2048 },
{ 6, 1256, 2048 }, { 7, 1257, 2048 }, { 7, 1258, 2048 }, { 8, 1259, 2048 }, { 7, 1260, 2048 }, { 8, 1261, 2048 }, { 8, 1262, 2048 }, { 9, 1263, 2048 },
{ 6, 1264, 2048 }, { 7, 1265, 2048 }, { 7, 1266, 2048 }, { 8, 1267, 2048 }, { 7, 1268, 2048 }, { 8, 1269, 2048 }, { 8, 1270, 2048 }, { 9, 1271, 2048 },
{ 7, 1272, 2048 }, { 8, 1273, 2048 }, { 8, 1274, 2048 }, { 9, 1275, 2048 }, { 8, 1276, 2048 }, { 9, 1277, 2048 }, { 9, 1278, 2048 }, { 10, 1279, 2048 },
{ 3, 1280, 2048 }, { 4, 1281, 2048 }, { 4, 1282, 2048 }, { 5, 1283, 2048 }, { 4, 1284, 2048 }, { 5, 1285, 2048 }, { 5, 1286, 2048 }, { 6, 1287, 2048 },
{ 4, 1288, 2048 }, { 5, 1289, 2048 }, { 5, 1290, 2048 }, { 6, 1291, 2048 }, { 5, 1292, 2048 }, { 6, 1293, 2048 }, { 6, 1294, 2048 }, { 7, 1295, 2048 },
{ 4, 1296, 2048 }, { 5, 1297, 2048 }, { 5, 1298, 2048 }, { 6, 1299, 2048 }, { 5, 1300, 2048 }, { 6, 1301, 2048 }, { 6, 1302, 2048 }, { 7, 1303, 2048 },
{ 5, 1304, 2048 }, { 6, 1305, 2048 }, { 6, 1306, 2048 }, { 7, 1307, 2048 }, { 6, 1308, 2048 }, { 7, 1309, 2048 }, { 7, 1310, 2048 }, { 8, 1311, 2048 },
{ 4, 1312, 2048 }, { 5, 1313, 2048 }, { 5, 1314, 2048 }, { 6, 1315, 2048 }, { 5, 1316, 2048 }, { 6, 1317, 2048 }, { 6, 1318, 2048 }, { 7, 1319, 2048 },
{ 5, 1320, 2048 }, { 6, 1321, 2048 }, { 6, 1322, 2048 }, { 7, 1323, 2048 }, { 6, 1324, 2048 }, { 7, 1325, 2048 }, { 7, 1326, 2048 }, { 8, 1327, 2048 },
{ 5, 1328, 2048 }, { 6, 1329, 2048 }, { 6, 1330, 2048 }, { 7, 1331, 2048 }, { 6, 1332, 2048 }, { 7, 1333, 2048 }, { 7, 1334, 2048 }, { 8, 1335, 2048 },
{ 6, 1336, 2048 }, { 7, 1337, 2048 }, { 7, 1338, 2048 }, { 8, 1339, 2048 }, { 7, 1340, 2048 }, { 8, 1341, 2048 }, { 8, 1342, 2048 }, { 9, 1343, 2048 },
{ 4, 1344, 2048 }, { 5, 1345, 2048 }, { 5, 1346, 2048 }, { 6, 1347, 2048 }, { 5, 1348, 2048 }, { 6, 1349, 2048 }, { 6, 1350, 2048 }, { 7, 1351, 2048 },
{ 5, 1352, 2048 }, { 6, 1353, 2048 }, { 6, 1354, 2048 }, { 7, 1355, 2048 }, { 6, 1356, 2048 }, { 7, 1357, 2048 }, { 7, 1358, 2048 }, { 8, 1359, 2048 },
{ 5, 1360, 2048 }, { 6, 1361, 2048 }, { 6, 1362, 2048 }, { 7, 1363, 2048 }, { 6, 1364, 2048 }, { 7, 1365, 2048 }, { 7, 1366, 2048 }, { 8, 1367, 2048 },
{ 6, 1368, 2048 }, { 7, 1369, 2048 }, { 7, 1370, 2048 }, { 8, 1371, 2048 }, { 7, 1372, 2048 }, { 8, 1373, 2048 }, { 8, 1374, 2048 }, { 9, 1375, 2048 },
{ 5, 1376, 2048 }, { 6, 1377, 2048 }, { 6, 1378, 2048 }, { 7, 1379, 2048 }, { 6, 1380, 2048 }, { 7, 1381, 2048 }, { 7, 1382, 2048 }, { 8, 1383, 2048 },
{ 6, 1384, 2048 }, { 7, 1385, 2048 }, { 7, 1386, 2048 }, { 8, 1387, 2048 }, { 7, 1388, 2048 }, { 8, 1389, 2048 }, { 8, 1390, 2048 }, { 9, 1391, 2048 },
{ 6, 1392, 2048 }, { 7, 1393, 2048 }, { 7, 1394, 2048 }, { 8, 1395, 2048 }, { 7, 1396, 2048 }, { 8, 1397, 2048 }, { 8, 1398, 2048 }, { 9, 1399, 2048 },
{ 7, 1400, 2048 }, { 8, 1401, 2048 }, { 8, 1402, 2048 }, { 9, 1403, 2048 }, { 8, 1404, 2048 }, { 9, 1405, 2048 }, { 9, 1406, 2048 }, { 10, 1407, 2048 },
{ 4, 1408, 2048 }, { 5, 1409, 2048 }, { 5, 1410, 2048 }, { 6, 1411, 2048 }, { 5, 1412, 2048 }, { 6, 1413, 2048 }, { 6, 1414, 2048 }, { 7, 1415, 2048 },
{ 5, 1416, 2048 }, { 6, 1417, 2048 }, { 6, 1418, 2048 }, { 7, 1419, 2048 }, { 6, 1420, 2048 }, { 7, 1421, 2048 }, { 7, 1422, 2048 }, { 8, 1423, 2048 },
{ 5, 1424, 2048 }, { 6, 1425, 2048 }, { 6, 1426, 2048 }, { 7, 1427, 2048 }, { 6, 1428, 2048 }, { 7, 1429, 2048 }, { 7, 1430, 2048 }, { 8, 1431, 2048 },
{ 6, 1432, 2048 }, { 7, 1433, 2048 }, { 7, 1434, 2048 }, { 8, 1435, 2048 }, { 7, 1436, 2048 }, { 8, 1437, 2048 }, { 8, 1438, 2048 }, { 9, 1439, 2048 },
{ 5, 1440, 2048 }, { 6, 1441, 2048 }, { 6, 1442, 2048 }, { 7, 1443, 2048 }, { 6, 1444, 2048 }, { 7, 1445, 2048 }, { 7, 1446, 2048 }, { 8, 1447, 2048 },
{ 6, 1448, 2048 }, { 7, 1449, 2048 }, { 7, 1450, 2048 }, { 8, 1451, 2048 }, { 7, 1452, 2048 }, { 8, 1453, 2048 }, { 8, 1454, 2048 }, { 9, 1455, 2048 },
{ 6, 1456, 2048 }, { 7, 1457, 2048 }, { 7, 1458, 2048 }, { 8, 1459, 2048 }, { 7, 1460, 2048 }, { 8, 1461, 2048 }, { 8, 1462, 2048 }, { 9, 1463, 2048 },
{ 7, 1464, 2048 }, { 8, 1465, 2048 }, { 8, 1466, 2048 }, { 9, 1467, 2048 }, { 8, 1468, 2048 }, { 9, 1469, 2048 }, { 9, 1470, 2048 }, { 10, 1471, 2048 },
{ 5, 1472, 2048 }, { 6, 1473, 2048 }, { 6, 1474, 2048 }, { 7, 1475, 2048 }, { 6, 1476, 2048 }, { 7, 1477, 2048 }, { 7, 1478, 2048 }, { 8, 1479, 2048 },
{ 6, 1480, 2048 }, { 7, 1481, 2048 }, { 7, 1482, 2048 }, { 8, 1483, 2048 }, { 7, 1484, 2048 }, { 8, 1485, 2048 }, { 8, 1486, 2048 }, { 9, 1487, 2048 },
{ 6, 1488, 2048 }, { 7, 1489, 2048 }, { 7, 1490, 2048 }, { 8, 1491, 2048 }, { 7, 1492, 2048 }, { 8, 1493, 2048 }, { 8, 1494, 2048 }, { 9, 1495, 2048 },
{ 7, 1496, 2048 }, { 8, 1497, 2048 }, { 8, 1498, 2048 }, { 9, 1499, 2048 }, { 8, 1500, 2048 }, { 9, 1501, 2048 }, { 9, 1502, 2048 }, { 10, 1503, 2048 },
{ 6, 1504, 2048 }, { 7, 1505, 2048 }, { 7, 1506, 2048 }, { 8, 1507, 2048 }, { 7, 1508, 2048 }, { 8, 1509, 2048 }, { 8, 1510, 2048 }, { 9, 1511, 2048 },
{ 7, 1512, 2048 }, { 8, 1513, 2048 }, { 8, 1514, 2048 }, { 9, 1515, 2048 }, { 8, 1516, 2048 }, { 9, 1517, 2048 }, { 9, 1518, 2048 }, { 10, 1519, 2048 },
{ 7, 1520, 2048 }, { 8, 1521, 2048 }, { 8, 1522, 2048 }, { 9, 1523, 2048 }, { 8, 1524, 2048 }, { 9, 1525, 2048 }, { 9, 1526, 2048 }, { 10, 1527, 2048 },
{ 8, 1528, 2048 }, { 9, 1529, 2048 }, { 9, 1530, 2048 }, { 10, 1531, 2048 }, { 9, 1532, 2048 }, { 10, 1533, 2048 }, { 10, 1534, 2048 }, { 11, 1535, 2048 },
{ 3, 1536, 2048 }, { 4, 1537, 2048 }, { 4, 1538, 2048 }, { 5, 1539, 2048 }, { 4, 1540, 2048 }, { 5, 1541, 2048 }, { 5, 1542, 2048 }, { 6, 1543, 2048 },
{ 4, 1544, 2048 }, { 5, 1545, 2048 }, { 5, 1546, 2048 }, { 6, 1547, 2048 }, { 5, 1548, 2048 }, { 6, 1549, 2048 }, { 6, 1550, 2048 }, { 7, 1551, 2048 },
{ 4, 1552, 2048 }, { 5, 1553, 2048 }, { 5, 1554, 2048 }, { 6, 1555, 2048 }, { 5, 1556, 2048 }, { 6, 1557, 2048 }, { 6, 1558, 2048 }, { 7, 1559, 2048 },
{ 5, 1560, 2048 }, { 6, 1561, 2048 }, { 6, 1562, 2048 }, { 7, 1563, 2048 }, { 6, 1564, 2048 }, { 7, 1565, 2048 }, { 7, 1566, 2048 }, { 8, 1567, 2048 },
{ 4, 1568, 2048 }, { 5, 1569, 2048 }, { 5, 1570, 2048 }, { 6, 1571, 2048 }, { 5, 1572, 2048 }, { 6, 1573, 2048 }, { 6, 1574, 2048 }, { 7, 1575, 2048 },
{ 5, 1576, 2048 }, { 6, 1577, 2048 }, { 6, 1578, 2048 }, { 7, 1579, 2048 }, { 6, 1580, 2048 }, { 7, 1581, 2048 }, { 7, 1582, 2048 }, { 8, 1583, 2048 },
{ 5, 1584, 2048 }, { 6, 1585, 2048 }, { 6, 1586, 2048 }, { 7, 1587, 2048 }, { 6, 1588, 2048 }, { 7, 1589, 2048 }, { 7, 1590, 2048 }, { 8, 1591, 2048 },
{ 6, 1592, 2048 }, { 7, 1593, 2048 }, { 7, 1594, 2048 }, { 8, 1595, 2048 }, { 7, 1596, 2048 }, { 8, 1597, 2048 }, { 8, 1598, 2048 }, { 9, 1599, 2048 },
{ 4, 1600, 2048 }, { 5, 1601, 2048 }, { 5, 1602, 2048 }, { 6, 1603, 2048 }, { 5, 1604, 2048 }, { 6, 1605, 2048 }, { 6, 1606, 2048 }, { 7, 1607, 2048 },
{ 5, 1608, 2048 }, { 6, 1609, 2048 }, { 6, 1610, 2048 }, { 7, 1611, 2048 }, { 6, 1612, 2048 }, { 7, 1613, 2048 }, { 7, 1614, 2048 }, { 8, 1615, 2048 },
{ 5, 1616, 2048 }, { 6, 1617, 2048 }, { 6, 1618, 2048 }, { 7, 1619, 2048 }, { 6, 1620, 2048 }, { 7, 1621, 2048 }, { 7, 1622, 2048 }, { 8, 1623, 2048 },
{ 6, 1624, 2048 }, { 7, 1625, 2048 }, { 7, 1626, 2048 }, { 8, 1627, 2048 }, { 7, 1628, 2048 }, { 8, 1629, 2048 }, { 8, 1630, 2048 }, { 9, 1631, 2048 },
{ 5, 1632, 2048 }, { 6, 1633, 2048 }, { 6, 1634, 2048 }, { 7, 1635, 2048 }, { 6, 1636, 2048 }, { 7, 1637, 2048 }, { 7, 1638, 2048 }, { 8, 1639, 2048 },
{ 6, 1640, 2048 }, { 7, 1641, 2048 }, { 7, 1642, 2048 }, { 8, 1643, 2048 }, { 7, 1644, 2048 }, { 8, 1645, 2048 }, { 8, 1646, 2048 }, { 9, 1647, 2048 },
{ 6, 1648, 2048 }, { 7, 1649, 2048 }, { 7, 1650, 2048 }, { 8, 1651, 2048 }, { 7, 1652, 2048 }, { 8, 1653, 2048 }, { 8, 1654, 2048 }, { 9, 1655, 2048 },
{ 7, 1656, 2048 }, { 8, 1657, 2048 }, { 8, 1658, 2048 }, { 9, 1659, 2048 }, { 8, 1660, 2048 }, { 9, 1661, 2048 }, { 9, 1662, 2048 }, { 10, 1663, 2048 },
{ 4, 1664, 2048 }, { 5, 1665, 2048 }, { 5, 1666, 2048 }, { 6, 1667, 2048 }, { 5, 1668, 2048 }, { 6, 1669, 2048 }, { 6, 1670, 2048 }, { 7, 1671, 2048 },
{ 5, 1672, 2048 }, { 6, 1673, 2048 }, { 6, 1674, 2048 }, { 7, 1675, 2048 }, { 6, 1676, 2048 }, { 7, 1677, 2048 }, { 7, 1678, 2048 }, { 8, 1679, 2048 },
{ 5, 1680, 2048 }, { 6, 1681, 2048 }, { 6, 1682, 2048 }, { 7, 1683, 2048 }, { 6, 1684, 2048 }, { 7, 1685, 2048 }, { 7, 1686, 2048 }, { 8, 1687, 2048 },
{ 6, 1688, 2048 }, { 7, 1689, 2048 }, { 7, 1690, 2048 }, { 8, 1691, 2048 }, { 7, 1692, 2048 }, { 8, 1693, 2048 }, { 8, 1694, 2048 }, { 9, 1695, 2048 },
{ 5, 1696, 2048 }, { 6, 1697, 2048 }, { 6, 1698, 2048 }, { 7, 1699, 2048 }, { 6, 1700, 2048 }, { 7, 1701, 2048 }, { 7, 1702, 2048 }, { 8, 1703, 2048 },
{ 6, 1704, 2048 }, { 7, 1705, 2048 }, { 7, 1706, 2048 }, { 8, 1707, 2048 }, { 7, 1708, 2048 }, { 8, 1709, 2048 }, { 8, 1710, 2048 }, { 9, 1711, 2048 },
{ 6, 1712, 2048 }, { 7, 1713, 2048 }, { 7, 1714, 2048 }, { 8, 1715, 2048 }, { 7, 1716, 2048 }, { 8, 1717, 2048 }, { 8, 1718, 2048 }, { 9, 1719, 2048 },
{ 7, 1720, 2048 }, { 8, 1721, 2048 }, { 8, 1722, 2048 }, { 9, 1723, 2048 }, { 8, 1724, 2048 }, { 9, 1725, 2048 }, { 9, 1726, 2048 }, { 10, 1727, 2048 },
{ 5, 1728, 2048 }, { 6, 1729, 2048 }, { 6, 1730, 2048 }, { 7, 1731, 2048 }, { 6, 1732, 2048 }, { 7, 1733, 2048 }, { 7, 1734, 2048 }, { 8, 1735, 2048 },
{ 6, 1736, 2048 }, { 7, 1737, 2048 }, { 7, 1738, 2048 }, { 8, 1739, 2048 }, { 7, 1740, 2048 }, { 8, 1741, 2048 }, { 8, 1742, 2048 }, { 9, 1743, 2048 },
{ 6, 1744, 2048 }, { 7, 1745, 2048 }, { 7, 1746, 2048 }, { 8, 1747, 2048 }, { 7, 1748, 2048 }, { 8, 1749, 2048 }, { 8, 1750, 2048 }, { 9, 1751, 2048 },
{ 7, 1752, 2048 }, { 8, 1753, 2048 }, { 8, 1754, 2048 }, { 9, 1755, 2048 }, { 8, 1756, 2048 }, { 9, 1757, 2048 }, { 9, 1758, 2048 }, { 10, 1759, 2048 },
{ 6, 1760, 2048 }, { 7, 1761, 2048 }, { 7, 1762, 2048 }, { 8, 1763, 2048 }, { 7, 1764, 2048 }, { 8, 1765, 2048 }, { 8, 1766, 2048 }, { 9, 1767, 2048 },
{ 7, 1768, 2048 }, { 8, 1769, 2048 }, { 8, 1770, 2048 }, { 9, 1771, 2048 }, { 8, 1772, 2048 }, { 9, 1773, 2048 }, { 9, 1774, 2048 }, { 10, 1775, 2048 },
{ 7, 1776, 2048 }, { 8, 1777, 2048 }, { 8, 1778, 2048 }, { 9, 1779, 2048 }, { 8, 1780, 2048 }, { 9, 1781, 2048 }, { 9, 1782, 2048 }, { 10, 1783, 2048 },
{ 8, 1784, 2048 }, { 9, 1785, 2048 }, { 9, 1786, 2048 }, { 10, 1787, 2048 }, { 9, 1788, 2048 }, { 10, 1789, 2048 }, { 10, 1790, 2048 }, { 11, 1791, 2048 },
{ 4, 1792, 2048 }, { 5, 1793, 2048 }, { 5, 1794, 2048 }, { 6, 1795, 2048 }, { 5, 1796, 2048 }, { 6, 1797, 2048 }, { 6, 1798, 2048 }, { 7, 1799, 2048 },
{ 5, 1800, 2048 }, { 6, 1801, 2048 }, { 6, 1802, 2048 }, { 7, 1803, 2048 }, { 6, 1804, 2048 }, { 7, 1805, 2048 }, { 7, 1806, 2048 }, { 8, 1807, 2048 },
{ 5, 1808, 2048 }, { 6, 1809, 2048 }, { 6, 1810, 2048 }, { 7, 1811, 2048 }, { 6, 1812, 2048 }, { 7, 1813, 2048 }, { 7, 1814, 2048 }, { 8, 1815, 2048 },
{ 6, 1816, 2048 }, { 7, 1817, 2048 }, { 7, 1818, 2048 }, { 8, 1819, 2048 }, { 7, 1820, 2048 }, { 8, 1821, 2048 }, { 8, 1822, 2048 }, { 9, 1823, 2048 },
{ 5, 1824, 2048 }, { 6, 1825, 2048 }, { 6, 1826, 2048 }, { 7, 1827, 2048 }, { 6, 1828, 2048 }, { 7, 1829, 2048 }, { 7, 1830, 2048 }, { 8, 1831, 2048 },
{ 6, 1832, 2048 }, { 7, 1833, 2048 }, { 7, 1834, 2048 }, { 8, 1835, 2048 }, { 7, 1836, 2048 }, { 8, 1837, 2048 }, { 8, 1838, 2048 }, { 9, 1839, 2048 },
{ 6, 1840, 2048 }, { 7, 1841, 2048 }, { 7, 1842, 2048 }, { 8, 1843, 2048 }, { 7, 1844, 2048 }, { 8, 1845, 2048 }, { 8, 1846, 2048 }, { 9, 1847, 2048 },
{ 7, 1848, 2048 }, { 8, 1849, 2048 }, { 8, 1850, 2048 }, { 9, 1851, 2048 }, { 8, 1852, 2048 }, { 9, 1853, 2048 }, { 9, 1854, 2048 }, { 10, 1855, 2048 },
{ 5, 1856, 2048 }, { 6, 1857, 2048 }, { 6, 1858, 2048 }, { 7, 1859, 2048 }, { 6, 1860, 2048 }, { 7, 1861, 2048 }, { 7, 1862, 2048 }, { 8, 1863, 2048 },
{ 6, 1864, 2048 }, { 7, 1865, 2048 }, { 7, 1866, 2048 }, { 8, 1867, 2048 }, { 7, 1868, 2048 }, { 8, 1869, 2048 }, { 8, 1870, 2048 }, { 9, 1871, 2048 },
{ 6, 1872, 2048 }, { 7, 1873, 2048 }, { 7, 1874, 2048 }, { 8, 1875, 2048 }, { 7, 1876, 2048 }, { 8, 1877, 2048 }, { 8, 1878, 2048 }, { 9, 1879, 2048 },
{ 7, 1880, 2048 }, { 8, 1881, 2048 }, { 8, 1882, 2048 }, { 9, 1883, 2048 }, { 8, 1884, 2048 }, { 9, 1885, 2048 }, { 9, 1886, 2048 }, { 10, 1887, 2048 },
{ 6, 1888, 2048 }, { 7, 1889, 2048 }, { 7, 1890, 2048 }, { 8, 1891, 2048 }, { 7, 1892, 2048 }, { 8, 1893, 2048 }, { 8, 1894, 2048 }, { 9, 1895, 2048 },
{ 7, 1896, 2048 }, { 8, 1897, 2048 }, { 8, 1898, 2048 }, { 9, 1899, 2048 }, { 8, 1900, 2048 }, { 9, 1901, 2048 }, { 9, 1902, 2048 }, { 10, 1903, 2048 },
{ 7, 1904, 2048 }, { 8, 1905, 2048 }, { 8, 1906, 2048 }, { 9, 1907, 2048 }, { 8, 1908, 2048 }, { 9, 1909, 2048 }, { 9, 1910, 2048 }, { 10, 1911, 2048 },
{ 8, 1912, 2048 }, { 9, 1913, 2048 }, { 9, 1914, 2048 }, { 10, 1915, 2048 }, { 9, 1916, 2048 }, { 10, 1917, 2048 }, { 10, 1918, 2048 }, { 11, 1919, 2048 },
{ 5, 1920, 2048 }, { 6, 1921, 2048 }, { 6, 1922, 2048 }, { 7, 1923, 2048 }, { 6, 1924, 2048 }, { 7, 1925, 2048 }, { 7, 1926, 2048 }, { 8, 1927, 2048 },
{ 6, 1928, 2048 }, { 7, 1929, 2048 }, { 7, 1930, 2048 }, { 8, 1931, 2048 }, { 7, 1932, 2048 }, { 8, 1933, 2048 }, { 8, 1934, 2048 }, { 9, 1935, 2048 },
{ 6, 1936, 2048 }, { 7, 1937, 2048 }, { 7, 1938, 2048 }, { 8, 1939, 2048 }, { 7, 1940, 2048 }, { 8, 1941, 2048 }, { 8, 1942, 2048 }, { 9, 1943, 2048 },
{ 7, 1944, 2048 }, { 8, 1945, 2048 }, { 8, 1946, 2048 }, { 9, 1947, 2048 }, { 8, 1948, 2048 }, { 9, 1949, 2048 }, { 9, 1950, 2048 }, { 10, 1951, 2048 },
{ 6, 1952, 2048 }, { 7, 1953, 2048 }, { 7, 1954, 2048 }, { 8, 1955, 2048 }, { 7, 1956, 2048 }, { 8, 1957, 2048 }, { 8, 1958, 2048 }, { 9, 1959, 2048 },
{ 7, 1960, 2048 }, { 8, 1961, 2048 }, { 8, 1962, 2048 }, { 9, 1963, 2048 }, { 8, 1964, 2048 }, { 9, 1965, 2048 }, { 9, 1966, 2048 }, { 10, 1967, 2048 },
{ 7, 1968, 2048 }, { 8, 1969, 2048 }, { 8, 1970, 2048 }, { 9, 1971, 2048 }, { 8, 1972, 2048 }, { 9, 1973, 2048 }, { 9, 1974, 2048 }, { 10, 1975, 2048 },
{ 8, 1976, 2048 }, { 9, 1977, 2048 }, { 9, 1978, 2048 }, { 10, 1979, 2048 }, { 9, 1980, 2048 }, { 10, 1981, 2048 }, { 10, 1982, 2048 }, { 11, 1983, 2048 },
{ 6, 1984, 2048 }, { 7, 1985, 2048 }, { 7, 1986, 2048 }, { 8, 1987, 2048 }, { 7, 1988, 2048 }, { 8, 1989, 2048 }, { 8, 1990, 2048 }, { 9, 1991, 2048 },
{ 7, 1992, 2048 }, { 8, 1993, 2048 }, { 8, 1994, 2048 }, { 9, 1995, 2048 }, { 8, 1996, 2048 }, { 9, 1997, 2048 }, { 9, 1998, 2048 }, { 10, 1999, 2048 },
{ 7, 2000, 2048 }, { 8, 2001, 2048 }, { 8, 2002, 2048 }, { 9, 2003, 2048 }, { 8, 2004, 2048 }, { 9, 2005, 2048 }, { 9, 2006, 2048 }, { 10, 2007, 2048 },
{ 8, 2008, 2048 }, { 9, 2009, 2048 }, { 9, 2010, 2048 }, { 10, 2011, 2048 }, { 9, 2012, 2048 }, { 10, 2013, 2048 }, { 10, 2014, 2048 }, { 11, 2015, 2048 },
{ 7, 2016, 2048 }, { 8, 2017, 2048 }, { 8, 2018, 2048 }, { 9, 2019, 2048 }, { 8, 2020, 2048 }, { 9, 2021, 2048 }, { 9, 2022, 2048 }, { 10, 2023, 2048 },
{ 8, 2024, 2048 }, { 9, 2025, 2048 }, { 9, 2026, 2048 }, { 10, 2027, 2048 }, { 9, 2028, 2048 }, { 10, 2029, 2048 }, { 10, 2030, 2048 }, { 11, 2031, 2048 },
{ 8, 2032, 2048 }, { 9, 2033, 2048 }, { 9, 2034, 2048 }, { 10, 2035, 2048 }, { 9, 2036, 2048 }, { 10, 2037, 2048 }, { 10, 2038, 2048 }, { 11, 2039, 2048 },
{ 9, 2040, 2048 }, { 10, 2041, 2048 }, { 10, 2042, 2048 }, { 11, 2043, 2048 }, { 10, 2044, 2048 }, { 11, 2045, 2048 }, { 11, 2046, 2048 }, { 12, 2047, 2048 },
#endif
#endif
#endif
#endif
#endif
#endif
};
/* find a hole and free as required, return -1 if no hole found */
static int find_hole(void)
{
unsigned x;
int y, z;
for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) {
z = x;
y = fp_cache[x].lru_count;
}
}
/* decrease all */
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].lru_count > 3) {
--(fp_cache[x].lru_count);
}
}
/* free entry z */
if (z >= 0 && fp_cache[z].g) {
mp_clear(&fp_cache[z].mu);
wc_ecc_del_point(fp_cache[z].g);
fp_cache[z].g = NULL;
for (x = 0; x < (1U<<FP_LUT); x++) {
wc_ecc_del_point(fp_cache[z].LUT[x]);
fp_cache[z].LUT[x] = NULL;
}
fp_cache[z].lru_count = 0;
}
return z;
}
/* determine if a base is already in the cache and if so, where */
static int find_base(ecc_point* g)
{
int x;
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].g != NULL &&
mp_cmp(fp_cache[x].g->x, g->x) == MP_EQ &&
mp_cmp(fp_cache[x].g->y, g->y) == MP_EQ &&
mp_cmp(fp_cache[x].g->z, g->z) == MP_EQ) {
break;
}
}
if (x == FP_ENTRIES) {
x = -1;
}
return x;
}
/* add a new base to the cache */
static int add_entry(int idx, ecc_point *g)
{
unsigned x, y;
/* allocate base and LUT */
fp_cache[idx].g = wc_ecc_new_point();
if (fp_cache[idx].g == NULL) {
return GEN_MEM_ERR;
}
/* copy x and y */
if ((mp_copy(g->x, fp_cache[idx].g->x) != MP_OKAY) ||
(mp_copy(g->y, fp_cache[idx].g->y) != MP_OKAY) ||
(mp_copy(g->z, fp_cache[idx].g->z) != MP_OKAY)) {
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
return GEN_MEM_ERR;
}
for (x = 0; x < (1U<<FP_LUT); x++) {
fp_cache[idx].LUT[x] = wc_ecc_new_point();
if (fp_cache[idx].LUT[x] == NULL) {
for (y = 0; y < x; y++) {
wc_ecc_del_point(fp_cache[idx].LUT[y]);
fp_cache[idx].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
fp_cache[idx].lru_count = 0;
return GEN_MEM_ERR;
}
}
fp_cache[idx].lru_count = 0;
return MP_OKAY;
}
#endif
#ifndef WOLFSSL_SP_MATH
/* build the LUT by spacing the bits of the input by #modulus/FP_LUT bits apart
*
* The algorithm builds patterns in increasing bit order by first making all
* single bit input patterns, then all two bit input patterns and so on
*/
static int build_lut(int idx, mp_int* a, mp_int* modulus, mp_digit mp,
mp_int* mu)
{
int err;
unsigned x, y, bitlen, lut_gap;
mp_int tmp;
if (mp_init(&tmp) != MP_OKAY)
return GEN_MEM_ERR;
/* sanity check to make sure lut_order table is of correct size,
should compile out to a NOP if true */
if ((sizeof(lut_orders) / sizeof(lut_orders[0])) < (1U<<FP_LUT)) {
err = BAD_FUNC_ARG;
}
else {
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* init the mu */
err = mp_init_copy(&fp_cache[idx].mu, mu);
}
/* copy base */
if (err == MP_OKAY) {
if ((mp_mulmod(fp_cache[idx].g->x, mu, modulus,
fp_cache[idx].LUT[1]->x) != MP_OKAY) ||
(mp_mulmod(fp_cache[idx].g->y, mu, modulus,
fp_cache[idx].LUT[1]->y) != MP_OKAY) ||
(mp_mulmod(fp_cache[idx].g->z, mu, modulus,
fp_cache[idx].LUT[1]->z) != MP_OKAY)) {
err = MP_MULMOD_E;
}
}
/* make all single bit entries */
for (x = 1; x < FP_LUT; x++) {
if (err != MP_OKAY)
break;
if ((mp_copy(fp_cache[idx].LUT[1<<(x-1)]->x,
fp_cache[idx].LUT[1<<x]->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[1<<(x-1)]->y,
fp_cache[idx].LUT[1<<x]->y) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[1<<(x-1)]->z,
fp_cache[idx].LUT[1<<x]->z) != MP_OKAY)){
err = MP_INIT_E;
break;
} else {
/* now double it bitlen/FP_LUT times */
for (y = 0; y < lut_gap; y++) {
if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[1<<x],
fp_cache[idx].LUT[1<<x], a, modulus, mp)) != MP_OKAY) {
break;
}
}
}
}
/* now make all entries in increase order of hamming weight */
for (x = 2; x <= FP_LUT; x++) {
if (err != MP_OKAY)
break;
for (y = 0; y < (1UL<<FP_LUT); y++) {
if (lut_orders[y].ham != (int)x) continue;
/* perform the add */
if ((err = ecc_projective_add_point(
fp_cache[idx].LUT[lut_orders[y].terma],
fp_cache[idx].LUT[lut_orders[y].termb],
fp_cache[idx].LUT[y], a, modulus, mp)) != MP_OKAY) {
break;
}
}
}
/* now map all entries back to affine space to make point addition faster */
for (x = 1; x < (1UL<<FP_LUT); x++) {
if (err != MP_OKAY)
break;
/* convert z to normal from montgomery */
err = mp_montgomery_reduce(fp_cache[idx].LUT[x]->z, modulus, mp);
/* invert it */
if (err == MP_OKAY)
err = mp_invmod(fp_cache[idx].LUT[x]->z, modulus,
fp_cache[idx].LUT[x]->z);
if (err == MP_OKAY)
/* now square it */
err = mp_sqrmod(fp_cache[idx].LUT[x]->z, modulus, &tmp);
if (err == MP_OKAY)
/* fix x */
err = mp_mulmod(fp_cache[idx].LUT[x]->x, &tmp, modulus,
fp_cache[idx].LUT[x]->x);
if (err == MP_OKAY)
/* get 1/z^3 */
err = mp_mulmod(&tmp, fp_cache[idx].LUT[x]->z, modulus, &tmp);
if (err == MP_OKAY)
/* fix y */
err = mp_mulmod(fp_cache[idx].LUT[x]->y, &tmp, modulus,
fp_cache[idx].LUT[x]->y);
if (err == MP_OKAY)
/* free z */
mp_clear(fp_cache[idx].LUT[x]->z);
}
mp_clear(&tmp);
if (err == MP_OKAY)
return MP_OKAY;
/* err cleanup */
for (y = 0; y < (1U<<FP_LUT); y++) {
wc_ecc_del_point(fp_cache[idx].LUT[y]);
fp_cache[idx].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[idx].g);
fp_cache[idx].g = NULL;
fp_cache[idx].lru_count = 0;
mp_clear(&fp_cache[idx].mu);
return err;
}
/* perform a fixed point ECC mulmod */
static int accel_fp_mul(int idx, mp_int* k, ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp, int map)
{
#define KB_SIZE 128
#ifdef WOLFSSL_SMALL_STACK
unsigned char* kb = NULL;
#else
unsigned char kb[KB_SIZE];
#endif
int x, err;
unsigned y, z = 0, bitlen, bitpos, lut_gap, first;
mp_int tk, order;
if (mp_init_multi(&tk, &order, NULL, NULL, NULL, NULL) != MP_OKAY)
return MP_INIT_E;
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(k) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* k must be less than modulus */
if (mp_cmp(k, &order) != MP_LT) {
if ((err = mp_mod(k, &order, &tk)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(k, &tk)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(k, &tk)) != MP_OKAY) {
goto done;
}
}
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* get the k value */
if (mp_unsigned_bin_size(&tk) > (int)(KB_SIZE - 2)) {
err = BUFFER_E; goto done;
}
/* store k */
#ifdef WOLFSSL_SMALL_STACK
kb = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb, 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tk, kb)) == MP_OKAY) {
/* let's reverse kb so it's little endian */
x = 0;
y = mp_unsigned_bin_size(&tk);
if (y > 0) {
y -= 1;
}
while ((unsigned)x < y) {
z = kb[x]; kb[x] = kb[y]; kb[y] = (byte)z;
++x; --y;
}
/* at this point we can start, yipee */
first = 1;
for (x = lut_gap-1; x >= 0; x--) {
/* extract FP_LUT bits from kb spread out by lut_gap bits and offset
by x bits from the start */
bitpos = x;
for (y = z = 0; y < FP_LUT; y++) {
z |= ((kb[bitpos>>3] >> (bitpos&7)) & 1) << y;
bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid
the mult in each loop */
}
/* double if not first */
if (!first) {
if ((err = ecc_projective_dbl_point(R, R, a, modulus,
mp)) != MP_OKAY) {
break;
}
}
/* add if not first, otherwise copy */
if (!first && z) {
if ((err = ecc_projective_add_point(R, fp_cache[idx].LUT[z], R, a,
modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[z],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
} else if (z) {
if ((mp_copy(fp_cache[idx].LUT[z]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx].LUT[z]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
}
}
if (err == MP_OKAY) {
(void) z; /* Acknowledge the unused assignment */
ForceZero(kb, KB_SIZE);
/* map R back from projective space */
if (map) {
err = ecc_map(R, modulus, mp);
} else {
err = MP_OKAY;
}
}
done:
/* cleanup */
mp_clear(&order);
mp_clear(&tk);
#ifdef WOLFSSL_SMALL_STACK
XFREE(kb, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
#undef KB_SIZE
return err;
}
#endif
#ifdef ECC_SHAMIR
#ifndef WOLFSSL_SP_MATH
/* perform a fixed point ECC mulmod */
static int accel_fp_mul2add(int idx1, int idx2,
mp_int* kA, mp_int* kB,
ecc_point *R, mp_int* a,
mp_int* modulus, mp_digit mp)
{
#define KB_SIZE 128
#ifdef WOLFSSL_SMALL_STACK
unsigned char* kb[2] = {NULL, NULL};
#else
unsigned char kb[2][KB_SIZE];
#endif
int x, err;
unsigned y, z, bitlen, bitpos, lut_gap, first, zA, zB;
mp_int tka, tkb, order;
if (mp_init_multi(&tka, &tkb, &order, NULL, NULL, NULL) != MP_OKAY)
return MP_INIT_E;
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(kA) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* kA must be less than modulus */
if (mp_cmp(kA, &order) != MP_LT) {
if ((err = mp_mod(kA, &order, &tka)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(kA, &tka)) != MP_OKAY) {
goto done;
}
}
/* if it's smaller than modulus we fine */
if (mp_unsigned_bin_size(kB) > mp_unsigned_bin_size(modulus)) {
/* find order */
y = mp_unsigned_bin_size(modulus);
for (x = 0; ecc_sets[x].size; x++) {
if (y <= (unsigned)ecc_sets[x].size) break;
}
/* back off if we are on the 521 bit curve */
if (y == 66) --x;
if ((err = mp_read_radix(&order, ecc_sets[x].order,
MP_RADIX_HEX)) != MP_OKAY) {
goto done;
}
/* kB must be less than modulus */
if (mp_cmp(kB, &order) != MP_LT) {
if ((err = mp_mod(kB, &order, &tkb)) != MP_OKAY) {
goto done;
}
} else {
if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
goto done;
}
}
} else {
if ((err = mp_copy(kB, &tkb)) != MP_OKAY) {
goto done;
}
}
/* get bitlen and round up to next multiple of FP_LUT */
bitlen = mp_unsigned_bin_size(modulus) << 3;
x = bitlen % FP_LUT;
if (x) {
bitlen += FP_LUT - x;
}
lut_gap = bitlen / FP_LUT;
/* get the k value */
if ((mp_unsigned_bin_size(&tka) > (int)(KB_SIZE - 2)) ||
(mp_unsigned_bin_size(&tkb) > (int)(KB_SIZE - 2)) ) {
err = BUFFER_E; goto done;
}
/* store k */
#ifdef WOLFSSL_SMALL_STACK
kb[0] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb[0] == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb[0], 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tka, kb[0])) != MP_OKAY) {
goto done;
}
/* let's reverse kb so it's little endian */
x = 0;
y = mp_unsigned_bin_size(&tka);
if (y > 0) {
y -= 1;
}
mp_clear(&tka);
while ((unsigned)x < y) {
z = kb[0][x]; kb[0][x] = kb[0][y]; kb[0][y] = (byte)z;
++x; --y;
}
/* store b */
#ifdef WOLFSSL_SMALL_STACK
kb[1] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (kb[1] == NULL) {
err = MEMORY_E; goto done;
}
#endif
XMEMSET(kb[1], 0, KB_SIZE);
if ((err = mp_to_unsigned_bin(&tkb, kb[1])) == MP_OKAY) {
x = 0;
y = mp_unsigned_bin_size(&tkb);
if (y > 0) {
y -= 1;
}
while ((unsigned)x < y) {
z = kb[1][x]; kb[1][x] = kb[1][y]; kb[1][y] = (byte)z;
++x; --y;
}
/* at this point we can start, yipee */
first = 1;
for (x = lut_gap-1; x >= 0; x--) {
/* extract FP_LUT bits from kb spread out by lut_gap bits and
offset by x bits from the start */
bitpos = x;
for (y = zA = zB = 0; y < FP_LUT; y++) {
zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y;
zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y;
bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid
the mult in each loop */
}
/* double if not first */
if (!first) {
if ((err = ecc_projective_dbl_point(R, R, a, modulus,
mp)) != MP_OKAY) {
break;
}
}
/* add if not first, otherwise copy */
if (!first) {
if (zA) {
if ((err = ecc_projective_add_point(R, fp_cache[idx1].LUT[zA],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx1].LUT[zA], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx1].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
if (zB) {
if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB],
R, a, modulus, mp)) != MP_OKAY) {
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx2].LUT[zB], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx2].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
} else {
if (zA) {
if ((mp_copy(fp_cache[idx1].LUT[zA]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx1].LUT[zA]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx1].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
if (zB && first == 0) {
if (zB) {
if ((err = ecc_projective_add_point(R,
fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY){
break;
}
if (mp_iszero(R->z)) {
/* When all zero then should have done an add */
if (mp_iszero(R->x) && mp_iszero(R->y)) {
if ((err = ecc_projective_dbl_point(
fp_cache[idx2].LUT[zB], R,
a, modulus, mp)) != MP_OKAY) {
break;
}
}
/* When only Z zero then result is infinity */
else {
err = mp_set(R->x, 0);
if (err != MP_OKAY) {
break;
}
err = mp_set(R->y, 0);
if (err != MP_OKAY) {
break;
}
err = mp_copy(&fp_cache[idx2].mu, R->z);
if (err != MP_OKAY) {
break;
}
first = 1;
}
}
}
} else if (zB && first == 1) {
if ((mp_copy(fp_cache[idx2].LUT[zB]->x, R->x) != MP_OKAY) ||
(mp_copy(fp_cache[idx2].LUT[zB]->y, R->y) != MP_OKAY) ||
(mp_copy(&fp_cache[idx2].mu, R->z) != MP_OKAY)) {
err = GEN_MEM_ERR;
break;
}
first = 0;
}
}
}
}
done:
/* cleanup */
mp_clear(&tkb);
mp_clear(&tka);
mp_clear(&order);
#ifdef WOLFSSL_SMALL_STACK
if (kb[0])
#endif
ForceZero(kb[0], KB_SIZE);
#ifdef WOLFSSL_SMALL_STACK
if (kb[1])
#endif
ForceZero(kb[1], KB_SIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(kb[0], NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
#undef KB_SIZE
if (err != MP_OKAY)
return err;
return ecc_map(R, modulus, mp);
}
/** ECC Fixed Point mulmod global with heap hint used
Computes kA*A + kB*B = C using Shamir's Trick
A First point to multiply
kA What to multiple A by
B Second point to multiply
kB What to multiple B by
C [out] Destination point (can overlap with A or B)
a ECC curve parameter a
modulus Modulus for curve
return MP_OKAY on success
*/
int ecc_mul2add(ecc_point* A, mp_int* kA,
ecc_point* B, mp_int* kB,
ecc_point* C, mp_int* a, mp_int* modulus, void* heap)
{
int idx1 = -1, idx2 = -1, err, mpInit = 0;
mp_digit mp;
mp_int mu;
err = mp_init(&mu);
if (err != MP_OKAY)
return err;
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) != 0)
return BAD_MUTEX_E;
#endif /* HAVE_THREAD_LS */
/* find point */
idx1 = find_base(A);
/* no entry? */
if (idx1 == -1) {
/* find hole and add it */
if ((idx1 = find_hole()) >= 0) {
err = add_entry(idx1, A);
}
}
if (err == MP_OKAY && idx1 != -1) {
/* increment LRU */
++(fp_cache[idx1].lru_count);
}
if (err == MP_OKAY)
/* find point */
idx2 = find_base(B);
if (err == MP_OKAY) {
/* no entry? */
if (idx2 == -1) {
/* find hole and add it */
if ((idx2 = find_hole()) >= 0)
err = add_entry(idx2, B);
}
}
if (err == MP_OKAY && idx2 != -1) {
/* increment LRU */
++(fp_cache[idx2].lru_count);
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx1 >= 0 && fp_cache[idx1].lru_count == 2) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
mpInit = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx1, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx2 >= 0 && fp_cache[idx2].lru_count == 2) {
if (mpInit == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
mpInit = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx2, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].lru_count >= 2 &&
fp_cache[idx2].lru_count >= 2) {
if (mpInit == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
}
if (err == MP_OKAY)
err = accel_fp_mul2add(idx1, idx2, kA, kB, C, a, modulus, mp);
} else {
err = normal_ecc_mul2add(A, kA, B, kB, C, a, modulus, heap);
}
}
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
#endif /* HAVE_THREAD_LS */
mp_clear(&mu);
return err;
}
#endif
#endif /* ECC_SHAMIR */
/** ECC Fixed Point mulmod global
k The multiplicand
G Base point to multiply
R [out] Destination of product
a ECC curve parameter a
modulus The modulus for the curve
map [boolean] If non-zero maps the point back to affine coordinates,
otherwise it's left in jacobian-montgomery form
return MP_OKAY if successful
*/
int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a,
mp_int* modulus, int map, void* heap)
{
#ifndef WOLFSSL_SP_MATH
int idx, err = MP_OKAY;
mp_digit mp;
mp_int mu;
int mpSetup = 0;
if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
if (mp_init(&mu) != MP_OKAY)
return MP_INIT_E;
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) != 0)
return BAD_MUTEX_E;
#endif /* HAVE_THREAD_LS */
/* find point */
idx = find_base(G);
/* no entry? */
if (idx == -1) {
/* find hole and add it */
idx = find_hole();
if (idx >= 0)
err = add_entry(idx, G);
}
if (err == MP_OKAY && idx >= 0) {
/* increment LRU */
++(fp_cache[idx].lru_count);
}
if (err == MP_OKAY) {
/* if it's 2 build the LUT, if it's higher just use the LUT */
if (idx >= 0 && fp_cache[idx].lru_count == 2) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
if (err == MP_OKAY) {
/* compute mu */
mpSetup = 1;
err = mp_montgomery_calc_normalization(&mu, modulus);
}
if (err == MP_OKAY)
/* build the LUT */
err = build_lut(idx, a, modulus, mp, &mu);
}
}
if (err == MP_OKAY) {
if (idx >= 0 && fp_cache[idx].lru_count >= 2) {
if (mpSetup == 0) {
/* compute mp */
err = mp_montgomery_setup(modulus, &mp);
}
if (err == MP_OKAY)
err = accel_fp_mul(idx, k, R, a, modulus, mp, map);
} else {
err = normal_ecc_mulmod(k, G, R, a, modulus, map, heap);
}
}
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
#endif /* HAVE_THREAD_LS */
mp_clear(&mu);
return err;
#else
if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) {
return ECC_BAD_ARG_E;
}
#ifndef WOLFSSL_SP_NO_256
if (mp_count_bits(modulus) == 256) {
return sp_ecc_mulmod_256(k, G, R, map, heap);
}
#endif
#ifdef WOLFSSL_SP_384
if (mp_count_bits(modulus) == 384) {
return sp_ecc_mulmod_384(k, G, R, map, heap);
}
#endif
return WC_KEY_SIZE_E;
#endif
}
#ifndef WOLFSSL_SP_MATH
/* helper function for freeing the cache ...
must be called with the cache mutex locked */
static void wc_ecc_fp_free_cache(void)
{
unsigned x, y;
for (x = 0; x < FP_ENTRIES; x++) {
if (fp_cache[x].g != NULL) {
for (y = 0; y < (1U<<FP_LUT); y++) {
wc_ecc_del_point(fp_cache[x].LUT[y]);
fp_cache[x].LUT[y] = NULL;
}
wc_ecc_del_point(fp_cache[x].g);
fp_cache[x].g = NULL;
mp_clear(&fp_cache[x].mu);
fp_cache[x].lru_count = 0;
fp_cache[x].lock = 0;
}
}
}
#endif
/** Free the Fixed Point cache */
void wc_ecc_fp_free(void)
{
#ifndef WOLFSSL_SP_MATH
#ifndef HAVE_THREAD_LS
if (initMutex == 0) {
wc_InitMutex(&ecc_fp_lock);
initMutex = 1;
}
if (wc_LockMutex(&ecc_fp_lock) == 0) {
#endif /* HAVE_THREAD_LS */
wc_ecc_fp_free_cache();
#ifndef HAVE_THREAD_LS
wc_UnLockMutex(&ecc_fp_lock);
wc_FreeMutex(&ecc_fp_lock);
initMutex = 0;
}
#endif /* HAVE_THREAD_LS */
#endif
}
#endif /* FP_ECC */
#ifdef HAVE_ECC_ENCRYPT
enum ecCliState {
ecCLI_INIT = 1,
ecCLI_SALT_GET = 2,
ecCLI_SALT_SET = 3,
ecCLI_SENT_REQ = 4,
ecCLI_RECV_RESP = 5,
ecCLI_BAD_STATE = 99
};
enum ecSrvState {
ecSRV_INIT = 1,
ecSRV_SALT_GET = 2,
ecSRV_SALT_SET = 3,
ecSRV_RECV_REQ = 4,
ecSRV_SENT_RESP = 5,
ecSRV_BAD_STATE = 99
};
struct ecEncCtx {
const byte* kdfSalt; /* optional salt for kdf */
const byte* kdfInfo; /* optional info for kdf */
const byte* macSalt; /* optional salt for mac */
word32 kdfSaltSz; /* size of kdfSalt */
word32 kdfInfoSz; /* size of kdfInfo */
word32 macSaltSz; /* size of macSalt */
void* heap; /* heap hint for memory used */
byte clientSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */
byte serverSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */
byte encAlgo; /* which encryption type */
byte kdfAlgo; /* which key derivation function type */
byte macAlgo; /* which mac function type */
byte protocol; /* are we REQ_RESP client or server ? */
byte cliSt; /* protocol state, for sanity checks */
byte srvSt; /* protocol state, for sanity checks */
};
const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx)
{
if (ctx == NULL || ctx->protocol == 0)
return NULL;
if (ctx->protocol == REQ_RESP_CLIENT) {
if (ctx->cliSt == ecCLI_INIT) {
ctx->cliSt = ecCLI_SALT_GET;
return ctx->clientSalt;
}
else {
ctx->cliSt = ecCLI_BAD_STATE;
return NULL;
}
}
else if (ctx->protocol == REQ_RESP_SERVER) {
if (ctx->srvSt == ecSRV_INIT) {
ctx->srvSt = ecSRV_SALT_GET;
return ctx->serverSalt;
}
else {
ctx->srvSt = ecSRV_BAD_STATE;
return NULL;
}
}
return NULL;
}
/* optional set info, can be called before or after set_peer_salt */
int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz)
{
if (ctx == NULL || info == 0 || sz < 0)
return BAD_FUNC_ARG;
ctx->kdfInfo = info;
ctx->kdfInfoSz = sz;
return 0;
}
static const char* exchange_info = "Secure Message Exchange";
int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt)
{
byte tmp[EXCHANGE_SALT_SZ/2];
int halfSz = EXCHANGE_SALT_SZ/2;
if (ctx == NULL || ctx->protocol == 0 || salt == NULL)
return BAD_FUNC_ARG;
if (ctx->protocol == REQ_RESP_CLIENT) {
XMEMCPY(ctx->serverSalt, salt, EXCHANGE_SALT_SZ);
if (ctx->cliSt == ecCLI_SALT_GET)
ctx->cliSt = ecCLI_SALT_SET;
else {
ctx->cliSt = ecCLI_BAD_STATE;
return BAD_STATE_E;
}
}
else {
XMEMCPY(ctx->clientSalt, salt, EXCHANGE_SALT_SZ);
if (ctx->srvSt == ecSRV_SALT_GET)
ctx->srvSt = ecSRV_SALT_SET;
else {
ctx->srvSt = ecSRV_BAD_STATE;
return BAD_STATE_E;
}
}
/* mix half and half */
/* tmp stores 2nd half of client before overwrite */
XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz);
XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz);
XMEMCPY(ctx->serverSalt, tmp, halfSz);
ctx->kdfSalt = ctx->clientSalt;
ctx->kdfSaltSz = EXCHANGE_SALT_SZ;
ctx->macSalt = ctx->serverSalt;
ctx->macSaltSz = EXCHANGE_SALT_SZ;
if (ctx->kdfInfo == NULL) {
/* default info */
ctx->kdfInfo = (const byte*)exchange_info;
ctx->kdfInfoSz = EXCHANGE_INFO_SZ;
}
return 0;
}
static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng)
{
byte* saltBuffer = NULL;
if (ctx == NULL || rng == NULL || flags == 0)
return BAD_FUNC_ARG;
saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt;
return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ);
}
static void ecc_ctx_init(ecEncCtx* ctx, int flags)
{
if (ctx) {
XMEMSET(ctx, 0, sizeof(ecEncCtx));
ctx->encAlgo = ecAES_128_CBC;
ctx->kdfAlgo = ecHKDF_SHA256;
ctx->macAlgo = ecHMAC_SHA256;
ctx->protocol = (byte)flags;
if (flags == REQ_RESP_CLIENT)
ctx->cliSt = ecCLI_INIT;
if (flags == REQ_RESP_SERVER)
ctx->srvSt = ecSRV_INIT;
}
}
/* allow ecc context reset so user doesn't have to init/free for reuse */
int wc_ecc_ctx_reset(ecEncCtx* ctx, WC_RNG* rng)
{
if (ctx == NULL || rng == NULL)
return BAD_FUNC_ARG;
ecc_ctx_init(ctx, ctx->protocol);
return ecc_ctx_set_salt(ctx, ctx->protocol, rng);
}
ecEncCtx* wc_ecc_ctx_new_ex(int flags, WC_RNG* rng, void* heap)
{
int ret = 0;
ecEncCtx* ctx = (ecEncCtx*)XMALLOC(sizeof(ecEncCtx), heap,
DYNAMIC_TYPE_ECC);
if (ctx) {
ctx->protocol = (byte)flags;
ctx->heap = heap;
}
ret = wc_ecc_ctx_reset(ctx, rng);
if (ret != 0) {
wc_ecc_ctx_free(ctx);
ctx = NULL;
}
return ctx;
}
/* alloc/init and set defaults, return new Context */
ecEncCtx* wc_ecc_ctx_new(int flags, WC_RNG* rng)
{
return wc_ecc_ctx_new_ex(flags, rng, NULL);
}
/* free any resources, clear any keys */
void wc_ecc_ctx_free(ecEncCtx* ctx)
{
if (ctx) {
ForceZero(ctx, sizeof(ecEncCtx));
XFREE(ctx, ctx->heap, DYNAMIC_TYPE_ECC);
}
}
static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz,
int* keysLen, word32* digestSz, word32* blockSz)
{
if (ctx) {
switch (ctx->encAlgo) {
case ecAES_128_CBC:
*encKeySz = KEY_SIZE_128;
*ivSz = IV_SIZE_128;
*blockSz = AES_BLOCK_SIZE;
break;
default:
return BAD_FUNC_ARG;
}
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
*digestSz = WC_SHA256_DIGEST_SIZE;
break;
default:
return BAD_FUNC_ARG;
}
} else
return BAD_FUNC_ARG;
*keysLen = *encKeySz + *ivSz + *digestSz;
return 0;
}
/* ecc encrypt with shared secret run through kdf
ctx holds non default algos and inputs
msgSz should be the right size for encAlgo, i.e., already padded
return 0 on success */
int wc_ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg,
word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx)
{
int ret = 0;
word32 blockSz;
word32 digestSz;
ecEncCtx localCtx;
#ifdef WOLFSSL_SMALL_STACK
byte* sharedSecret;
byte* keys;
#else
byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */
byte keys[ECC_BUFSIZE]; /* max size */
#endif
word32 sharedSz = ECC_MAXSIZE;
int keysLen;
int encKeySz;
int ivSz;
int offset = 0; /* keys offset if doing msg exchange */
byte* encKey;
byte* encIv;
byte* macKey;
if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL ||
outSz == NULL)
return BAD_FUNC_ARG;
if (ctx == NULL) { /* use defaults */
ecc_ctx_init(&localCtx, 0);
ctx = &localCtx;
}
ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz,
&blockSz);
if (ret != 0)
return ret;
if (ctx->protocol == REQ_RESP_SERVER) {
offset = keysLen;
keysLen *= 2;
if (ctx->srvSt != ecSRV_RECV_REQ)
return BAD_STATE_E;
ctx->srvSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */
}
else if (ctx->protocol == REQ_RESP_CLIENT) {
if (ctx->cliSt != ecCLI_SALT_SET)
return BAD_STATE_E;
ctx->cliSt = ecCLI_SENT_REQ; /* only do this once */
}
if (keysLen > ECC_BUFSIZE) /* keys size */
return BUFFER_E;
if ( (msgSz%blockSz) != 0)
return BAD_PADDING_E;
if (*outSz < (msgSz + digestSz))
return BUFFER_E;
#ifdef WOLFSSL_SMALL_STACK
sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (sharedSecret == NULL)
return MEMORY_E;
keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (keys == NULL) {
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
#endif
do {
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
if (ret != 0)
break;
#endif
ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz);
} while (ret == WC_PENDING_E);
if (ret == 0) {
switch (ctx->kdfAlgo) {
case ecHKDF_SHA256 :
ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt,
ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz,
keys, keysLen);
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
encKey = keys + offset;
encIv = encKey + encKeySz;
macKey = encKey + encKeySz + ivSz;
switch (ctx->encAlgo) {
case ecAES_128_CBC:
{
Aes aes;
ret = wc_AesInit(&aes, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
AES_ENCRYPTION);
if (ret == 0) {
ret = wc_AesCbcEncrypt(&aes, out, msg, msgSz);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
ret = wc_AsyncWait(ret, &aes.asyncDev,
WC_ASYNC_FLAG_NONE);
#endif
}
wc_AesFree(&aes);
}
if (ret != 0)
break;
}
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
{
Hmac hmac;
ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, out, msgSz);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
if (ret == 0)
ret = wc_HmacFinal(&hmac, out+msgSz);
wc_HmacFree(&hmac);
}
}
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0)
*outSz = msgSz + digestSz;
#ifdef WOLFSSL_SMALL_STACK
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
/* ecc decrypt with shared secret run through kdf
ctx holds non default algos and inputs
return 0 on success */
int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg,
word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx)
{
int ret = 0;
word32 blockSz;
word32 digestSz;
ecEncCtx localCtx;
#ifdef WOLFSSL_SMALL_STACK
byte* sharedSecret;
byte* keys;
#else
byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */
byte keys[ECC_BUFSIZE]; /* max size */
#endif
word32 sharedSz = ECC_MAXSIZE;
int keysLen;
int encKeySz;
int ivSz;
int offset = 0; /* in case using msg exchange */
byte* encKey;
byte* encIv;
byte* macKey;
if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL ||
outSz == NULL)
return BAD_FUNC_ARG;
if (ctx == NULL) { /* use defaults */
ecc_ctx_init(&localCtx, 0);
ctx = &localCtx;
}
ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz,
&blockSz);
if (ret != 0)
return ret;
if (ctx->protocol == REQ_RESP_CLIENT) {
offset = keysLen;
keysLen *= 2;
if (ctx->cliSt != ecCLI_SENT_REQ)
return BAD_STATE_E;
ctx->cliSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */
}
else if (ctx->protocol == REQ_RESP_SERVER) {
if (ctx->srvSt != ecSRV_SALT_SET)
return BAD_STATE_E;
ctx->srvSt = ecSRV_RECV_REQ; /* only do this once */
}
if (keysLen > ECC_BUFSIZE) /* keys size */
return BUFFER_E;
if ( ((msgSz-digestSz) % blockSz) != 0)
return BAD_PADDING_E;
if (*outSz < (msgSz - digestSz))
return BUFFER_E;
#ifdef WOLFSSL_SMALL_STACK
sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (sharedSecret == NULL)
return MEMORY_E;
keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (keys == NULL) {
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
return MEMORY_E;
}
#endif
do {
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC)
ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
if (ret != 0)
break;
#endif
ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz);
} while (ret == WC_PENDING_E);
if (ret == 0) {
switch (ctx->kdfAlgo) {
case ecHKDF_SHA256 :
ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt,
ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz,
keys, keysLen);
break;
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
encKey = keys + offset;
encIv = encKey + encKeySz;
macKey = encKey + encKeySz + ivSz;
switch (ctx->macAlgo) {
case ecHMAC_SHA256:
{
byte verify[WC_SHA256_DIGEST_SIZE];
Hmac hmac;
ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID);
if (ret == 0) {
ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, msg, msgSz-digestSz);
if (ret == 0)
ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz);
if (ret == 0)
ret = wc_HmacFinal(&hmac, verify);
if (ret == 0) {
if (XMEMCMP(verify, msg + msgSz - digestSz, digestSz) != 0)
ret = -1;
}
wc_HmacFree(&hmac);
}
break;
}
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0) {
switch (ctx->encAlgo) {
#ifdef HAVE_AES_CBC
case ecAES_128_CBC:
{
Aes aes;
ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv,
AES_DECRYPTION);
if (ret != 0)
break;
ret = wc_AesCbcDecrypt(&aes, out, msg, msgSz-digestSz);
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_AES)
ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE);
#endif
}
break;
#endif
default:
ret = BAD_FUNC_ARG;
break;
}
}
if (ret == 0)
*outSz = msgSz - digestSz;
#ifdef WOLFSSL_SMALL_STACK
XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER);
XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return ret;
}
#endif /* HAVE_ECC_ENCRYPT */
#ifdef HAVE_COMP_KEY
#if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_CRYPTOCELL)
#ifndef WOLFSSL_SP_MATH
int do_mp_jacobi(mp_int* a, mp_int* n, int* c);
int do_mp_jacobi(mp_int* a, mp_int* n, int* c)
{
int k, s, res;
int r = 0; /* initialize to help static analysis out */
mp_digit residue;
/* if a < 0 return MP_VAL */
if (mp_isneg(a) == MP_YES) {
return MP_VAL;
}
/* if n <= 0 return MP_VAL */
if (mp_cmp_d(n, 0) != MP_GT) {
return MP_VAL;
}
/* step 1. handle case of a == 0 */
if (mp_iszero (a) == MP_YES) {
/* special case of a == 0 and n == 1 */
if (mp_cmp_d (n, 1) == MP_EQ) {
*c = 1;
} else {
*c = 0;
}
return MP_OKAY;
}
/* step 2. if a == 1, return 1 */
if (mp_cmp_d (a, 1) == MP_EQ) {
*c = 1;
return MP_OKAY;
}
/* default */
s = 0;
/* divide out larger power of two */
k = mp_cnt_lsb(a);
res = mp_div_2d(a, k, a, NULL);
if (res == MP_OKAY) {
/* step 4. if e is even set s=1 */
if ((k & 1) == 0) {
s = 1;
} else {
/* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */
residue = n->dp[0] & 7;
if (residue == 1 || residue == 7) {
s = 1;
} else if (residue == 3 || residue == 5) {
s = -1;
}
}
/* step 5. if p == 3 (mod 4) *and* a == 3 (mod 4) then s = -s */
if ( ((n->dp[0] & 3) == 3) && ((a->dp[0] & 3) == 3)) {
s = -s;
}
}
if (res == MP_OKAY) {
/* if a == 1 we're done */
if (mp_cmp_d(a, 1) == MP_EQ) {
*c = s;
} else {
/* n1 = n mod a */
res = mp_mod (n, a, n);
if (res == MP_OKAY)
res = do_mp_jacobi(n, a, &r);
if (res == MP_OKAY)
*c = s * r;
}
}
return res;
}
/* computes the jacobi c = (a | n) (or Legendre if n is prime)
* HAC pp. 73 Algorithm 2.149
* HAC is wrong here, as the special case of (0 | 1) is not
* handled correctly.
*/
int mp_jacobi(mp_int* a, mp_int* n, int* c)
{
mp_int a1, n1;
int res;
/* step 3. write a = a1 * 2**k */
if ((res = mp_init_multi(&a1, &n1, NULL, NULL, NULL, NULL)) != MP_OKAY) {
return res;
}
if ((res = mp_copy(a, &a1)) != MP_OKAY) {
goto done;
}
if ((res = mp_copy(n, &n1)) != MP_OKAY) {
goto done;
}
res = do_mp_jacobi(&a1, &n1, c);
done:
/* cleanup */
mp_clear(&n1);
mp_clear(&a1);
return res;
}
/* Solves the modular equation x^2 = n (mod p)
* where prime number is greater than 2 (odd prime).
* The result is returned in the third argument x
* the function returns MP_OKAY on success, MP_VAL or another error on failure
*/
int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret)
{
#ifdef SQRTMOD_USE_MOD_EXP
int res;
mp_int e;
res = mp_init(&e);
if (res == MP_OKAY)
res = mp_add_d(prime, 1, &e);
if (res == MP_OKAY)
res = mp_div_2d(&e, 2, &e, NULL);
if (res == MP_OKAY)
res = mp_exptmod(n, &e, prime, ret);
mp_clear(&e);
return res;
#else
int res, legendre, done = 0;
mp_int t1, C, Q, S, Z, M, T, R, two;
mp_digit i;
/* first handle the simple cases n = 0 or n = 1 */
if (mp_cmp_d(n, 0) == MP_EQ) {
mp_zero(ret);
return MP_OKAY;
}
if (mp_cmp_d(n, 1) == MP_EQ) {
return mp_set(ret, 1);
}
/* prime must be odd */
if (mp_cmp_d(prime, 2) == MP_EQ) {
return MP_VAL;
}
/* is quadratic non-residue mod prime */
if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) {
return res;
}
if (legendre == -1) {
return MP_VAL;
}
if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M)) != MP_OKAY)
return res;
if ((res = mp_init_multi(&T, &R, &two, NULL, NULL, NULL))
!= MP_OKAY) {
mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z);
mp_clear(&M);
return res;
}
/* SPECIAL CASE: if prime mod 4 == 3
* compute directly: res = n^(prime+1)/4 mod prime
* Handbook of Applied Cryptography algorithm 3.36
*/
res = mp_mod_d(prime, 4, &i);
if (res == MP_OKAY && i == 3) {
res = mp_add_d(prime, 1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
if (res == MP_OKAY)
res = mp_exptmod(n, &t1, prime, ret);
done = 1;
}
/* NOW: TonelliShanks algorithm */
if (res == MP_OKAY && done == 0) {
/* factor out powers of 2 from prime-1, defining Q and S
* as: prime-1 = Q*2^S */
/* Q = prime - 1 */
res = mp_copy(prime, &Q);
if (res == MP_OKAY)
res = mp_sub_d(&Q, 1, &Q);
/* S = 0 */
if (res == MP_OKAY)
mp_zero(&S);
while (res == MP_OKAY && mp_iseven(&Q) == MP_YES) {
/* Q = Q / 2 */
res = mp_div_2(&Q, &Q);
/* S = S + 1 */
if (res == MP_OKAY)
res = mp_add_d(&S, 1, &S);
}
/* find a Z such that the Legendre symbol (Z|prime) == -1 */
/* Z = 2 */
if (res == MP_OKAY)
res = mp_set_int(&Z, 2);
while (res == MP_OKAY) {
res = mp_jacobi(&Z, prime, &legendre);
if (res == MP_OKAY && legendre == -1)
break;
/* Z = Z + 1 */
if (res == MP_OKAY)
res = mp_add_d(&Z, 1, &Z);
}
/* C = Z ^ Q mod prime */
if (res == MP_OKAY)
res = mp_exptmod(&Z, &Q, prime, &C);
/* t1 = (Q + 1) / 2 */
if (res == MP_OKAY)
res = mp_add_d(&Q, 1, &t1);
if (res == MP_OKAY)
res = mp_div_2(&t1, &t1);
/* R = n ^ ((Q + 1) / 2) mod prime */
if (res == MP_OKAY)
res = mp_exptmod(n, &t1, prime, &R);
/* T = n ^ Q mod prime */
if (res == MP_OKAY)
res = mp_exptmod(n, &Q, prime, &T);
/* M = S */
if (res == MP_OKAY)
res = mp_copy(&S, &M);
if (res == MP_OKAY)
res = mp_set_int(&two, 2);
while (res == MP_OKAY && done == 0) {
res = mp_copy(&T, &t1);
/* reduce to 1 and count */
i = 0;
while (res == MP_OKAY) {
if (mp_cmp_d(&t1, 1) == MP_EQ)
break;
res = mp_exptmod(&t1, &two, prime, &t1);
if (res == MP_OKAY)
i++;
}
if (res == MP_OKAY && i == 0) {
res = mp_copy(&R, ret);
done = 1;
}
if (done == 0) {
/* t1 = 2 ^ (M - i - 1) */
if (res == MP_OKAY)
res = mp_sub_d(&M, i, &t1);
if (res == MP_OKAY)
res = mp_sub_d(&t1, 1, &t1);
if (res == MP_OKAY)
res = mp_exptmod(&two, &t1, prime, &t1);
/* t1 = C ^ (2 ^ (M - i - 1)) mod prime */
if (res == MP_OKAY)
res = mp_exptmod(&C, &t1, prime, &t1);
/* C = (t1 * t1) mod prime */
if (res == MP_OKAY)
res = mp_sqrmod(&t1, prime, &C);
/* R = (R * t1) mod prime */
if (res == MP_OKAY)
res = mp_mulmod(&R, &t1, prime, &R);
/* T = (T * C) mod prime */
if (res == MP_OKAY)
res = mp_mulmod(&T, &C, prime, &T);
/* M = i */
if (res == MP_OKAY)
res = mp_set(&M, i);
}
}
}
/* done */
mp_clear(&t1);
mp_clear(&C);
mp_clear(&Q);
mp_clear(&S);
mp_clear(&Z);
mp_clear(&M);
mp_clear(&T);
mp_clear(&R);
mp_clear(&two);
return res;
#endif
}
#endif
#endif /* !WOLFSSL_ATECC508A && !WOLFSSL_CRYPTOCELL */
/* export public ECC key in ANSI X9.63 format compressed */
static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen)
{
word32 numlen;
int ret = MP_OKAY;
if (key == NULL || out == NULL || outLen == NULL)
return BAD_FUNC_ARG;
if (wc_ecc_is_valid_idx(key->idx) == 0) {
return ECC_BAD_ARG_E;
}
numlen = key->dp->size;
if (*outLen < (1 + numlen)) {
*outLen = 1 + numlen;
return BUFFER_E;
}
/* store first byte */
out[0] = mp_isodd(key->pubkey.y) == MP_YES ? ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
/* pad and store x */
XMEMSET(out+1, 0, numlen);
ret = mp_to_unsigned_bin(key->pubkey.x,
out+1 + (numlen - mp_unsigned_bin_size(key->pubkey.x)));
*outLen = 1 + numlen;
return ret;
}
#endif /* HAVE_COMP_KEY */
int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz)
{
int x;
if (oidSum == 0) {
return BAD_FUNC_ARG;
}
/* find matching OID sum (based on encoded value) */
for (x = 0; ecc_sets[x].size != 0; x++) {
if (ecc_sets[x].oidSum == oidSum) {
int ret = 0;
#ifdef HAVE_OID_ENCODING
/* check cache */
oid_cache_t* o = &ecc_oid_cache[x];
if (o->oidSz == 0) {
o->oidSz = sizeof(o->oid);
ret = EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz,
o->oid, &o->oidSz);
}
if (oidSz) {
*oidSz = o->oidSz;
}
if (oid) {
*oid = o->oid;
}
#else
if (oidSz) {
*oidSz = ecc_sets[x].oidSz;
}
if (oid) {
*oid = ecc_sets[x].oid;
}
#endif
/* on success return curve id */
if (ret == 0) {
ret = ecc_sets[x].id;
}
return ret;
}
}
return NOT_COMPILED_IN;
}
#ifdef WOLFSSL_CUSTOM_CURVES
int wc_ecc_set_custom_curve(ecc_key* key, const ecc_set_type* dp)
{
if (key == NULL || dp == NULL) {
return BAD_FUNC_ARG;
}
key->idx = ECC_CUSTOM_IDX;
key->dp = dp;
return 0;
}
#endif /* WOLFSSL_CUSTOM_CURVES */
#ifdef HAVE_X963_KDF
static WC_INLINE void IncrementX963KdfCounter(byte* inOutCtr)
{
int i;
/* in network byte order so start at end and work back */
for (i = 3; i >= 0; i--) {
if (++inOutCtr[i]) /* we're done unless we overflow */
return;
}
}
/* ASN X9.63 Key Derivation Function (SEC1) */
int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz,
const byte* sinfo, word32 sinfoSz, byte* out, word32 outSz)
{
int ret, i;
int digestSz, copySz;
int remaining = outSz;
byte* outIdx;
byte counter[4];
byte tmp[WC_MAX_DIGEST_SIZE];
#ifdef WOLFSSL_SMALL_STACK
wc_HashAlg* hash;
#else
wc_HashAlg hash[1];
#endif
if (secret == NULL || secretSz == 0 || out == NULL)
return BAD_FUNC_ARG;
/* X9.63 allowed algos only */
if (type != WC_HASH_TYPE_SHA && type != WC_HASH_TYPE_SHA224 &&
type != WC_HASH_TYPE_SHA256 && type != WC_HASH_TYPE_SHA384 &&
type != WC_HASH_TYPE_SHA512)
return BAD_FUNC_ARG;
digestSz = wc_HashGetDigestSize(type);
if (digestSz < 0)
return digestSz;
#ifdef WOLFSSL_SMALL_STACK
hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), NULL,
DYNAMIC_TYPE_HASHES);
if (hash == NULL)
return MEMORY_E;
#endif
ret = wc_HashInit(hash, type);
if (ret != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(hash, NULL, DYNAMIC_TYPE_HASHES);
#endif
return ret;
}
outIdx = out;
XMEMSET(counter, 0, sizeof(counter));
for (i = 1; remaining > 0; i++) {
IncrementX963KdfCounter(counter);
ret = wc_HashUpdate(hash, type, secret, secretSz);
if (ret != 0) {
break;
}
ret = wc_HashUpdate(hash, type, counter, sizeof(counter));
if (ret != 0) {
break;
}
if (sinfo) {
ret = wc_HashUpdate(hash, type, sinfo, sinfoSz);
if (ret != 0) {
break;
}
}
ret = wc_HashFinal(hash, type, tmp);
if (ret != 0) {
break;
}
copySz = min(remaining, digestSz);
XMEMCPY(outIdx, tmp, copySz);
remaining -= copySz;
outIdx += copySz;
}
wc_HashFree(hash, type);
#ifdef WOLFSSL_SMALL_STACK
XFREE(hash, NULL, DYNAMIC_TYPE_HASHES);
#endif
return ret;
}
#endif /* HAVE_X963_KDF */
#endif /* HAVE_ECC */
| ./CrossVul/dataset_final_sorted/CWE-326/c/bad_3970_0 |
crossvul-cpp_data_good_3970_1 | /* tfm.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
/*
* Based on public domain TomsFastMath 0.10 by Tom St Denis, tomstdenis@iahu.ca,
* http://math.libtomcrypt.com
*/
/**
* Edited by Moises Guimaraes (moises@wolfssl.com)
* to fit wolfSSL's needs.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* in case user set USE_FAST_MATH there */
#include <wolfssl/wolfcrypt/settings.h>
#ifdef NO_INLINE
#include <wolfssl/wolfcrypt/misc.h>
#else
#define WOLFSSL_MISC_INCLUDED
#include <wolfcrypt/src/misc.c>
#endif
#ifdef USE_FAST_MATH
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssl/wolfcrypt/tfm.h>
#include <wolfcrypt/src/asm.c> /* will define asm MACROS or C ones */
#include <wolfssl/wolfcrypt/wolfmath.h> /* common functions */
#if defined(FREESCALE_LTC_TFM)
#include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
#endif
#ifdef WOLFSSL_DEBUG_MATH
#include <stdio.h>
#endif
#ifdef USE_WINDOWS_API
#pragma warning(disable:4127)
/* Disables the warning:
* 4127: conditional expression is constant
* in this file.
*/
#endif
#if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
#ifdef __cplusplus
extern "C" {
#endif
WOLFSSL_LOCAL int sp_ModExp_1024(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_1536(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_2048(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_3072(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
WOLFSSL_LOCAL int sp_ModExp_4096(mp_int* base, mp_int* exp, mp_int* mod,
mp_int* res);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
#ifndef WOLFSSL_SP_MATH
/* math settings check */
word32 CheckRunTimeSettings(void)
{
return CTC_SETTINGS;
}
#endif
/* math settings size check */
word32 CheckRunTimeFastMath(void)
{
return FP_SIZE;
}
/* Functions */
void fp_add(fp_int *a, fp_int *b, fp_int *c)
{
int sa, sb;
/* get sign of both inputs */
sa = a->sign;
sb = b->sign;
/* handle two cases, not four */
if (sa == sb) {
/* both positive or both negative */
/* add their magnitudes, copy the sign */
c->sign = sa;
s_fp_add (a, b, c);
} else {
/* one positive, the other negative */
/* subtract the one with the greater magnitude from */
/* the one of the lesser magnitude. The result gets */
/* the sign of the one with the greater magnitude. */
if (fp_cmp_mag (a, b) == FP_LT) {
c->sign = sb;
s_fp_sub (b, a, c);
} else {
c->sign = sa;
s_fp_sub (a, b, c);
}
}
}
/* unsigned addition */
void s_fp_add(fp_int *a, fp_int *b, fp_int *c)
{
int x, y, oldused;
fp_word t;
y = MAX(a->used, b->used);
oldused = MIN(c->used, FP_SIZE); /* help static analysis w/ largest size */
c->used = y;
t = 0;
for (x = 0; x < y; x++) {
t += ((fp_word)a->dp[x]) + ((fp_word)b->dp[x]);
c->dp[x] = (fp_digit)t;
t >>= DIGIT_BIT;
}
if (t != 0 && x < FP_SIZE) {
c->dp[c->used++] = (fp_digit)t;
++x;
}
c->used = x;
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a - b */
void fp_sub(fp_int *a, fp_int *b, fp_int *c)
{
int sa, sb;
sa = a->sign;
sb = b->sign;
if (sa != sb) {
/* subtract a negative from a positive, OR */
/* subtract a positive from a negative. */
/* In either case, ADD their magnitudes, */
/* and use the sign of the first number. */
c->sign = sa;
s_fp_add (a, b, c);
} else {
/* subtract a positive from a positive, OR */
/* subtract a negative from a negative. */
/* First, take the difference between their */
/* magnitudes, then... */
if (fp_cmp_mag (a, b) != FP_LT) {
/* Copy the sign from the first */
c->sign = sa;
/* The first has a larger or equal magnitude */
s_fp_sub (a, b, c);
} else {
/* The result has the *opposite* sign from */
/* the first number. */
c->sign = (sa == FP_ZPOS) ? FP_NEG : FP_ZPOS;
/* The second has a larger magnitude */
s_fp_sub (b, a, c);
}
}
}
/* unsigned subtraction ||a|| >= ||b|| ALWAYS! */
void s_fp_sub(fp_int *a, fp_int *b, fp_int *c)
{
int x, oldbused, oldused;
fp_word t;
oldused = c->used;
oldbused = b->used;
c->used = a->used;
t = 0;
for (x = 0; x < oldbused; x++) {
t = ((fp_word)a->dp[x]) - (((fp_word)b->dp[x]) + t);
c->dp[x] = (fp_digit)t;
t = (t >> DIGIT_BIT)&1;
}
for (; x < a->used; x++) {
t = ((fp_word)a->dp[x]) - t;
c->dp[x] = (fp_digit)t;
t = (t >> DIGIT_BIT)&1;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a * b */
int fp_mul(fp_int *A, fp_int *B, fp_int *C)
{
int ret = 0;
int y, yy, oldused;
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
ret = esp_mp_mul(A, B, C);
if(ret != -2) return ret;
#endif
oldused = C->used;
y = MAX(A->used, B->used);
yy = MIN(A->used, B->used);
/* call generic if we're out of range */
if (y + yy > FP_SIZE) {
ret = fp_mul_comba(A, B, C);
goto clean;
}
/* pick a comba (unrolled 4/8/16/32 x or rolled) based on the size
of the largest input. We also want to avoid doing excess mults if the
inputs are not close to the next power of two. That is, for example,
if say y=17 then we would do (32-17)^2 = 225 unneeded multiplications
*/
#if defined(TFM_MUL3) && FP_SIZE >= 6
if (y <= 3) {
ret = fp_mul_comba3(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL4) && FP_SIZE >= 8
if (y == 4) {
ret = fp_mul_comba4(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL6) && FP_SIZE >= 12
if (y <= 6) {
ret = fp_mul_comba6(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL7) && FP_SIZE >= 14
if (y == 7) {
ret = fp_mul_comba7(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL8) && FP_SIZE >= 16
if (y == 8) {
ret = fp_mul_comba8(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL9) && FP_SIZE >= 18
if (y == 9) {
ret = fp_mul_comba9(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL12) && FP_SIZE >= 24
if (y <= 12) {
ret = fp_mul_comba12(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL17) && FP_SIZE >= 34
if (y <= 17) {
ret = fp_mul_comba17(A,B,C);
goto clean;
}
#endif
#if defined(TFM_SMALL_SET) && FP_SIZE >= 32
if (y <= 16) {
ret = fp_mul_comba_small(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL20) && FP_SIZE >= 40
if (y <= 20) {
ret = fp_mul_comba20(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL24) && FP_SIZE >= 48
if (yy >= 16 && y <= 24) {
ret = fp_mul_comba24(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL28) && FP_SIZE >= 56
if (yy >= 20 && y <= 28) {
ret = fp_mul_comba28(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL32) && FP_SIZE >= 64
if (yy >= 24 && y <= 32) {
ret = fp_mul_comba32(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL48) && FP_SIZE >= 96
if (yy >= 40 && y <= 48) {
ret = fp_mul_comba48(A,B,C);
goto clean;
}
#endif
#if defined(TFM_MUL64) && FP_SIZE >= 128
if (yy >= 56 && y <= 64) {
ret = fp_mul_comba64(A,B,C);
goto clean;
}
#endif
ret = fp_mul_comba(A,B,C);
clean:
/* zero any excess digits on the destination that we didn't write to */
for (y = C->used; y >= 0 && y < oldused; y++) {
C->dp[y] = 0;
}
return ret;
}
void fp_mul_2(fp_int * a, fp_int * b)
{
int x, oldused;
oldused = b->used;
b->used = a->used;
{
fp_digit r, rr, *tmpa, *tmpb;
/* alias for source */
tmpa = a->dp;
/* alias for dest */
tmpb = b->dp;
/* carry */
r = 0;
for (x = 0; x < a->used; x++) {
/* get what will be the *next* carry bit from the
* MSB of the current digit
*/
rr = *tmpa >> ((fp_digit)(DIGIT_BIT - 1));
/* now shift up this digit, add in the carry [from the previous] */
*tmpb++ = ((*tmpa++ << ((fp_digit)1)) | r);
/* copy the carry that would be from the source
* digit into the next iteration
*/
r = rr;
}
/* new leading digit? */
if (r != 0 && b->used != (FP_SIZE-1)) {
/* add a MSB which is always 1 at this point */
*tmpb = 1;
++(b->used);
}
/* zero any excess digits on the destination that we didn't write to */
tmpb = b->dp + b->used;
for (x = b->used; x < oldused; x++) {
*tmpb++ = 0;
}
}
b->sign = a->sign;
}
/* c = a * b */
void fp_mul_d(fp_int *a, fp_digit b, fp_int *c)
{
fp_word w;
int x, oldused;
oldused = c->used;
c->used = a->used;
c->sign = a->sign;
w = 0;
for (x = 0; x < a->used; x++) {
w = ((fp_word)a->dp[x]) * ((fp_word)b) + w;
c->dp[x] = (fp_digit)w;
w = w >> DIGIT_BIT;
}
if (w != 0 && (a->used != FP_SIZE)) {
c->dp[c->used++] = (fp_digit) w;
++x;
}
/* zero any excess digits on the destination that we didn't write to */
/* also checking FP_SIZE here for static analysis */
for (; x < oldused && x < FP_SIZE; x++) {
c->dp[x] = 0;
}
fp_clamp(c);
}
/* c = a * 2**d */
void fp_mul_2d(fp_int *a, int b, fp_int *c)
{
fp_digit carry, carrytmp, shift;
int x;
/* copy it */
fp_copy(a, c);
/* handle whole digits */
if (b >= DIGIT_BIT) {
fp_lshd(c, b/DIGIT_BIT);
}
b %= DIGIT_BIT;
/* shift the digits */
if (b != 0) {
carry = 0;
shift = DIGIT_BIT - b;
for (x = 0; x < c->used; x++) {
carrytmp = c->dp[x] >> shift;
c->dp[x] = (c->dp[x] << b) + carry;
carry = carrytmp;
}
/* store last carry if room */
if (carry && x < FP_SIZE) {
c->dp[c->used++] = carry;
}
}
fp_clamp(c);
}
/* generic PxQ multiplier */
#if defined(HAVE_INTEL_MULX)
WC_INLINE static int fp_mul_comba_mulx(fp_int *A, fp_int *B, fp_int *C)
{
int ix, iy, iz, pa;
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)ix; (void)iy; (void)iz;
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* get size of output and trim */
pa = A->used + B->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* Always take branch to use tmp variable. This avoids a cache attack for
* determining if C equals A */
if (1) {
fp_init(tmp);
dst = tmp;
}
TFM_INTEL_MUL_COMBA(A, B, dst) ;
dst->used = pa;
dst->sign = A->sign ^ B->sign;
fp_clamp(dst);
fp_copy(dst, C);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
int fp_mul_comba(fp_int *A, fp_int *B, fp_int *C)
{
int ret = 0;
int ix, iy, iz, tx, ty, pa;
fp_digit c0, c1, c2, *tmpx, *tmpy;
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)c0; (void)c1; (void)c2;
IF_HAVE_INTEL_MULX(ret = fp_mul_comba_mulx(A, B, C), return ret) ;
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
COMBA_START;
COMBA_CLEAR;
/* get size of output and trim */
pa = A->used + B->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* Always take branch to use tmp variable. This avoids a cache attack for
* determining if C equals A */
if (1) {
fp_init(tmp);
dst = tmp;
}
for (ix = 0; ix < pa; ix++) {
/* get offsets into the two bignums */
ty = MIN(ix, (B->used > 0 ? B->used - 1 : 0));
tx = ix - ty;
/* setup temp aliases */
tmpx = A->dp + tx;
tmpy = B->dp + ty;
/* this is the number of times the loop will iterate, essentially its
while (tx++ < a->used && ty-- >= 0) { ... }
*/
iy = MIN(A->used-tx, ty+1);
/* execute loop */
COMBA_FORWARD;
for (iz = 0; iz < iy; ++iz) {
fp_digit _tmpx = *tmpx++;
fp_digit _tmpy = *tmpy--;
MULADD(_tmpx, _tmpy);
}
/* store term */
COMBA_STORE(dst->dp[ix]);
}
COMBA_FINI;
dst->used = pa;
dst->sign = A->sign ^ B->sign;
fp_clamp(dst);
fp_copy(dst, C);
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return ret;
}
/* a/b => cb + d == a */
int fp_div(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int n, t, i, norm, neg;
#ifndef WOLFSSL_SMALL_STACK
fp_int q[1], x[1], y[1], t1[1], t2[1];
#else
fp_int *q, *x, *y, *t1, *t2;
#endif
/* is divisor zero ? */
if (fp_iszero (b) == FP_YES) {
return FP_VAL;
}
/* if a < b then q=0, r = a */
if (fp_cmp_mag (a, b) == FP_LT) {
if (d != NULL) {
fp_copy (a, d);
}
if (c != NULL) {
fp_zero (c);
}
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
q = (fp_int*)XMALLOC(sizeof(fp_int) * 5, NULL, DYNAMIC_TYPE_BIGINT);
if (q == NULL) {
return FP_MEM;
}
x = &q[1]; y = &q[2]; t1 = &q[3]; t2 = &q[4];
#endif
fp_init(q);
q->used = a->used + 2;
fp_init(t1);
fp_init(t2);
fp_init_copy(x, a);
fp_init_copy(y, b);
/* fix the sign */
neg = (a->sign == b->sign) ? FP_ZPOS : FP_NEG;
x->sign = y->sign = FP_ZPOS;
/* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */
norm = fp_count_bits(y) % DIGIT_BIT;
if (norm < (int)(DIGIT_BIT-1)) {
norm = (DIGIT_BIT-1) - norm;
fp_mul_2d (x, norm, x);
fp_mul_2d (y, norm, y);
} else {
norm = 0;
}
/* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */
n = x->used - 1;
t = y->used - 1;
/* while (x >= y*b**n-t) do { q[n-t] += 1; x -= y*b**{n-t} } */
fp_lshd (y, n - t); /* y = y*b**{n-t} */
while (fp_cmp (x, y) != FP_LT) {
++(q->dp[n - t]);
fp_sub (x, y, x);
}
/* reset y by shifting it back down */
fp_rshd (y, n - t);
/* step 3. for i from n down to (t + 1) */
for (i = n; i >= (t + 1); i--) {
if (i > x->used) {
continue;
}
/* step 3.1 if xi == yt then set q{i-t-1} to b-1,
* otherwise set q{i-t-1} to (xi*b + x{i-1})/yt */
if (x->dp[i] == y->dp[t]) {
q->dp[i - t - 1] = (fp_digit) ((((fp_word)1) << DIGIT_BIT) - 1);
} else {
fp_word tmp;
tmp = ((fp_word) x->dp[i]) << ((fp_word) DIGIT_BIT);
tmp |= ((fp_word) x->dp[i - 1]);
tmp /= ((fp_word)y->dp[t]);
q->dp[i - t - 1] = (fp_digit) (tmp);
}
/* while (q{i-t-1} * (yt * b + y{t-1})) >
xi * b**2 + xi-1 * b + xi-2
do q{i-t-1} -= 1;
*/
q->dp[i - t - 1] = (q->dp[i - t - 1] + 1);
do {
q->dp[i - t - 1] = (q->dp[i - t - 1] - 1);
/* find left hand */
fp_zero (t1);
t1->dp[0] = (t - 1 < 0) ? 0 : y->dp[t - 1];
t1->dp[1] = y->dp[t];
t1->used = 2;
fp_mul_d (t1, q->dp[i - t - 1], t1);
/* find right hand */
t2->dp[0] = (i - 2 < 0) ? 0 : x->dp[i - 2];
t2->dp[1] = (i - 1 < 0) ? 0 : x->dp[i - 1];
t2->dp[2] = x->dp[i];
t2->used = 3;
} while (fp_cmp_mag(t1, t2) == FP_GT);
/* step 3.3 x = x - q{i-t-1} * y * b**{i-t-1} */
fp_mul_d (y, q->dp[i - t - 1], t1);
fp_lshd (t1, i - t - 1);
fp_sub (x, t1, x);
/* if x < 0 then { x = x + y*b**{i-t-1}; q{i-t-1} -= 1; } */
if (x->sign == FP_NEG) {
fp_copy (y, t1);
fp_lshd (t1, i - t - 1);
fp_add (x, t1, x);
q->dp[i - t - 1] = q->dp[i - t - 1] - 1;
}
}
/* now q is the quotient and x is the remainder
* [which we have to normalize]
*/
/* get sign before writing to c */
x->sign = x->used == 0 ? FP_ZPOS : a->sign;
if (c != NULL) {
fp_clamp (q);
fp_copy (q, c);
c->sign = neg;
}
if (d != NULL) {
fp_div_2d (x, norm, x, NULL);
/* zero any excess digits on the destination that we didn't write to */
for (i = b->used; i < x->used; i++) {
x->dp[i] = 0;
}
fp_clamp(x);
fp_copy (x, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(q, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* b = a/2 */
void fp_div_2(fp_int * a, fp_int * b)
{
int x, oldused;
oldused = b->used;
b->used = a->used;
{
fp_digit r, rr, *tmpa, *tmpb;
/* source alias */
tmpa = a->dp + b->used - 1;
/* dest alias */
tmpb = b->dp + b->used - 1;
/* carry */
r = 0;
for (x = b->used - 1; x >= 0; x--) {
/* get the carry for the next iteration */
rr = *tmpa & 1;
/* shift the current digit, add in carry and store */
*tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
/* forward carry to next iteration */
r = rr;
}
/* zero any excess digits on the destination that we didn't write to */
tmpb = b->dp + b->used;
for (x = b->used; x < oldused; x++) {
*tmpb++ = 0;
}
}
b->sign = a->sign;
fp_clamp (b);
}
/* c = a / 2**b */
void fp_div_2d(fp_int *a, int b, fp_int *c, fp_int *d)
{
int D;
/* if the shift count is <= 0 then we do no work */
if (b <= 0) {
fp_copy (a, c);
if (d != NULL) {
fp_zero (d);
}
return;
}
/* get the remainder before a is changed in calculating c */
if (a == c && d != NULL) {
fp_mod_2d (a, b, d);
}
/* copy */
fp_copy(a, c);
/* shift by as many digits in the bit count */
if (b >= (int)DIGIT_BIT) {
fp_rshd (c, b / DIGIT_BIT);
}
/* shift any bit count < DIGIT_BIT */
D = (b % DIGIT_BIT);
if (D != 0) {
fp_rshb(c, D);
}
/* get the remainder if a is not changed in calculating c */
if (a != c && d != NULL) {
fp_mod_2d (a, b, d);
}
fp_clamp (c);
}
/* c = a mod b, 0 <= c < b */
int fp_mod(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
int err;
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_div(a, b, NULL, t);
if (err == FP_OKAY) {
if (t->sign != b->sign) {
fp_add(t, b, c);
} else {
fp_copy(t, c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* c = a mod 2**d */
void fp_mod_2d(fp_int *a, int b, fp_int *c)
{
int x;
/* zero if count less than or equal to zero */
if (b <= 0) {
fp_zero(c);
return;
}
/* get copy of input */
fp_copy(a, c);
/* if 2**d is larger than we just return */
if (b >= (DIGIT_BIT * a->used)) {
return;
}
/* zero digits above the last digit of the modulus */
for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
c->dp[x] = 0;
}
/* clear the digit that is not completely outside/inside the modulus */
c->dp[b / DIGIT_BIT] &= ~((fp_digit)0) >> (DIGIT_BIT - b);
fp_clamp (c);
}
static int fp_invmod_slow (fp_int * a, fp_int * b, fp_int * c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int x[1], y[1], u[1], v[1], A[1], B[1], C[1], D[1];
#else
fp_int *x, *y, *u, *v, *A, *B, *C, *D;
#endif
int err;
/* b cannot be negative */
if (b->sign == FP_NEG || fp_iszero(b) == FP_YES) {
return FP_VAL;
}
if (fp_iszero(a) == FP_YES) {
return FP_VAL;
}
#ifdef WOLFSSL_SMALL_STACK
x = (fp_int*)XMALLOC(sizeof(fp_int) * 8, NULL, DYNAMIC_TYPE_BIGINT);
if (x == NULL) {
return FP_MEM;
}
y = &x[1]; u = &x[2]; v = &x[3]; A = &x[4]; B = &x[5]; C = &x[6]; D = &x[7];
#endif
/* init temps */
fp_init(x); fp_init(y);
fp_init(u); fp_init(v);
fp_init(A); fp_init(B);
fp_init(C); fp_init(D);
/* x = a, y = b */
if ((err = fp_mod(a, b, x)) != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_copy(b, y);
/* 2. [modified] if x,y are both even then return an error! */
if (fp_iseven(x) == FP_YES && fp_iseven(y) == FP_YES) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
fp_copy (x, u);
fp_copy (y, v);
fp_set (A, 1);
fp_set (D, 1);
top:
/* 4. while u is even do */
while (fp_iseven (u) == FP_YES) {
/* 4.1 u = u/2 */
fp_div_2 (u, u);
/* 4.2 if A or B is odd then */
if (fp_isodd (A) == FP_YES || fp_isodd (B) == FP_YES) {
/* A = (A+y)/2, B = (B-x)/2 */
fp_add (A, y, A);
fp_sub (B, x, B);
}
/* A = A/2, B = B/2 */
fp_div_2 (A, A);
fp_div_2 (B, B);
}
/* 5. while v is even do */
while (fp_iseven (v) == FP_YES) {
/* 5.1 v = v/2 */
fp_div_2 (v, v);
/* 5.2 if C or D is odd then */
if (fp_isodd (C) == FP_YES || fp_isodd (D) == FP_YES) {
/* C = (C+y)/2, D = (D-x)/2 */
fp_add (C, y, C);
fp_sub (D, x, D);
}
/* C = C/2, D = D/2 */
fp_div_2 (C, C);
fp_div_2 (D, D);
}
/* 6. if u >= v then */
if (fp_cmp (u, v) != FP_LT) {
/* u = u - v, A = A - C, B = B - D */
fp_sub (u, v, u);
fp_sub (A, C, A);
fp_sub (B, D, B);
} else {
/* v - v - u, C = C - A, D = D - B */
fp_sub (v, u, v);
fp_sub (C, A, C);
fp_sub (D, B, D);
}
/* if not zero goto step 4 */
if (fp_iszero (u) == FP_NO)
goto top;
/* now a = C, b = D, gcd == g*v */
/* if v != 1 then there is no inverse */
if (fp_cmp_d (v, 1) != FP_EQ) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* if its too low */
while (fp_cmp_d(C, 0) == FP_LT) {
fp_add(C, b, C);
}
/* too big */
while (fp_cmp_mag(C, b) != FP_LT) {
fp_sub(C, b, C);
}
/* C is now the inverse */
fp_copy(C, c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* c = 1/a (mod b) for odd b only */
int fp_invmod(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int x[1], y[1], u[1], v[1], B[1], D[1];
#else
fp_int *x, *y, *u, *v, *B, *D;
#endif
int neg;
int err;
if (b->sign == FP_NEG || fp_iszero(b) == FP_YES) {
return FP_VAL;
}
/* [modified] sanity check on "a" */
if (fp_iszero(a) == FP_YES) {
return FP_VAL; /* can not divide by 0 here */
}
/* 2. [modified] b must be odd */
if (fp_iseven(b) == FP_YES) {
return fp_invmod_slow(a,b,c);
}
#ifdef WOLFSSL_SMALL_STACK
x = (fp_int*)XMALLOC(sizeof(fp_int) * 6, NULL, DYNAMIC_TYPE_BIGINT);
if (x == NULL) {
return FP_MEM;
}
y = &x[1]; u = &x[2]; v = &x[3]; B = &x[4]; D = &x[5];
#endif
/* init all our temps */
fp_init(x); fp_init(y);
fp_init(u); fp_init(v);
fp_init(B); fp_init(D);
if (fp_cmp(a, b) != MP_LT) {
err = mp_mod(a, b, y);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
a = y;
}
if (fp_iszero(a) == FP_YES) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* x == modulus, y == value to invert */
fp_copy(b, x);
/* we need y = |a| */
fp_abs(a, y);
/* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
fp_copy(x, u);
fp_copy(y, v);
fp_set (D, 1);
top:
/* 4. while u is even do */
while (fp_iseven (u) == FP_YES) {
/* 4.1 u = u/2 */
fp_div_2 (u, u);
/* 4.2 if B is odd then */
if (fp_isodd (B) == FP_YES) {
fp_sub (B, x, B);
}
/* B = B/2 */
fp_div_2 (B, B);
}
/* 5. while v is even do */
while (fp_iseven (v) == FP_YES) {
/* 5.1 v = v/2 */
fp_div_2 (v, v);
/* 5.2 if D is odd then */
if (fp_isodd (D) == FP_YES) {
/* D = (D-x)/2 */
fp_sub (D, x, D);
}
/* D = D/2 */
fp_div_2 (D, D);
}
/* 6. if u >= v then */
if (fp_cmp (u, v) != FP_LT) {
/* u = u - v, B = B - D */
fp_sub (u, v, u);
fp_sub (B, D, B);
} else {
/* v - v - u, D = D - B */
fp_sub (v, u, v);
fp_sub (D, B, D);
}
/* if not zero goto step 4 */
if (fp_iszero (u) == FP_NO) {
goto top;
}
/* now a = C, b = D, gcd == g*v */
/* if v != 1 then there is no inverse */
if (fp_cmp_d (v, 1) != FP_EQ) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_VAL;
}
/* b is now the inverse */
neg = a->sign;
while (D->sign == FP_NEG) {
fp_add (D, b, D);
}
/* too big */
while (fp_cmp_mag(D, b) != FP_LT) {
fp_sub(D, b, D);
}
fp_copy (D, c);
c->sign = neg;
#ifdef WOLFSSL_SMALL_STACK
XFREE(x, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#define CT_INV_MOD_PRE_CNT 8
/* modulus (b) must be greater than 2 and a prime */
int fp_invmod_mont_ct(fp_int *a, fp_int *b, fp_int *c, fp_digit mp)
{
int i, j;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1], e[1];
fp_int pre[CT_INV_MOD_PRE_CNT];
#else
fp_int* t;
fp_int* e;
fp_int* pre;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int) * (2 + CT_INV_MOD_PRE_CNT), NULL,
DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
e = t + 1;
pre = t + 2;
#endif
fp_init(t);
fp_init(e);
fp_init(&pre[0]);
fp_copy(a, &pre[0]);
for (i = 1; i < CT_INV_MOD_PRE_CNT; i++) {
fp_init(&pre[i]);
fp_sqr(&pre[i-1], &pre[i]);
fp_montgomery_reduce(&pre[i], b, mp);
fp_mul(&pre[i], a, &pre[i]);
fp_montgomery_reduce(&pre[i], b, mp);
}
fp_sub_d(b, 2, e);
/* Highest bit is always set. */
for (i = fp_count_bits(e)-2, j = 1; i >= 0; i--, j++) {
if (!fp_is_bit_set(e, i) || j == CT_INV_MOD_PRE_CNT)
break;
}
fp_copy(&pre[j-1], t);
for (j = 0; i >= 0; i--) {
int set = fp_is_bit_set(e, i);
if ((j == CT_INV_MOD_PRE_CNT) || (!set && j > 0)) {
fp_mul(t, &pre[j-1], t);
fp_montgomery_reduce(t, b, mp);
j = 0;
}
fp_sqr(t, t);
fp_montgomery_reduce(t, b, mp);
j += set;
}
if (j > 0) {
fp_mul(t, &pre[j-1], c);
fp_montgomery_reduce(c, b, mp);
}
else
fp_copy(t, c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* d = a * b (mod c) */
int fp_mulmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_mul(a, b, t);
if (err == FP_OKAY) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* d = a - b (mod c) */
int fp_submod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
fp_sub(a, b, t);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* d = a + b (mod c) */
int fp_addmod(fp_int *a, fp_int *b, fp_int *c, fp_int *d)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
fp_add(a, b, t);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (d->size < FP_SIZE) {
err = fp_mod(t, c, t);
fp_copy(t, d);
} else
#endif
{
err = fp_mod(t, c, d);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#ifdef TFM_TIMING_RESISTANT
#ifdef WC_RSA_NONBLOCK
#ifdef WC_RSA_NONBLOCK_TIME
/* User can override the check-time at build-time using the
* FP_EXPTMOD_NB_CHECKTIME macro to define your own function */
#ifndef FP_EXPTMOD_NB_CHECKTIME
/* instruction count for each type of operation */
/* array lookup is using TFM_EXPTMOD_NB_* states */
static const word32 exptModNbInst[TFM_EXPTMOD_NB_COUNT] = {
#ifdef TFM_PPC32
#ifdef _DEBUG
11098, 8701, 3971, 178394, 858093, 1040, 822, 178056, 181574, 90883, 184339, 236813
#else
7050, 2554, 3187, 43178, 200422, 384, 275, 43024, 43550, 30450, 46270, 61376
#endif
#elif defined(TFM_X86_64)
#ifdef _DEBUG
954, 2377, 858, 19027, 90840, 287, 407, 20140, 7874, 11385, 8005, 6151
#else
765, 1007, 771, 5216, 34993, 248, 193, 4975, 4201, 3947, 4275, 3811
#endif
#else /* software only fast math */
#ifdef _DEBUG
798, 2245, 802, 16657, 66920, 352, 186, 16997, 16145, 12789, 16742, 15006
#else
775, 1084, 783, 4692, 37510, 207, 183, 4374, 4392, 3097, 4442, 4079
#endif
#endif
};
static int fp_exptmod_nb_checktime(exptModNb_t* nb)
{
word32 totalInst;
/* if no max time has been set then stop (do not block) */
if (nb->maxBlockInst == 0 || nb->state >= TFM_EXPTMOD_NB_COUNT) {
return TFM_EXPTMOD_NB_STOP;
}
/* if instruction table not set then use maxBlockInst as simple counter */
if (exptModNbInst[nb->state] == 0) {
if (++nb->totalInst < nb->maxBlockInst)
return TFM_EXPTMOD_NB_CONTINUE;
nb->totalInst = 0; /* reset counter */
return TFM_EXPTMOD_NB_STOP;
}
/* get total instruction count including next operation */
totalInst = nb->totalInst + exptModNbInst[nb->state];
/* if the next operation can completed within the maximum then continue */
if (totalInst <= nb->maxBlockInst) {
return TFM_EXPTMOD_NB_CONTINUE;
}
return TFM_EXPTMOD_NB_STOP;
}
#define FP_EXPTMOD_NB_CHECKTIME(nb) fp_exptmod_nb_checktime((nb))
#endif /* !FP_EXPTMOD_NB_CHECKTIME */
#endif /* WC_RSA_NONBLOCK_TIME */
/* non-blocking version of timing resistant fp_exptmod function */
/* supports cache resistance */
int fp_exptmod_nb(exptModNb_t* nb, fp_int* G, fp_int* X, fp_int* P, fp_int* Y)
{
int err, ret = FP_WOULDBLOCK;
if (nb == NULL)
return FP_VAL;
#ifdef WC_RSA_NONBLOCK_TIME
nb->totalInst = 0;
do {
nb->totalInst += exptModNbInst[nb->state];
#endif
switch (nb->state) {
case TFM_EXPTMOD_NB_INIT:
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &nb->mp)) != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
/* init ints */
fp_init(&nb->R[0]);
fp_init(&nb->R[1]);
#ifndef WC_NO_CACHE_RESISTANT
fp_init(&nb->R[2]);
#endif
nb->state = TFM_EXPTMOD_NB_MONT;
break;
case TFM_EXPTMOD_NB_MONT:
/* mod m -> R[0] */
fp_montgomery_calc_normalization(&nb->R[0], P);
nb->state = TFM_EXPTMOD_NB_MONT_RED;
break;
case TFM_EXPTMOD_NB_MONT_RED:
/* reduce G -> R[1] */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &nb->R[1]);
} else {
fp_copy(G, &nb->R[1]);
}
nb->state = TFM_EXPTMOD_NB_MONT_MUL;
break;
case TFM_EXPTMOD_NB_MONT_MUL:
/* G (R[1]) * m (R[0]) */
err = fp_mul(&nb->R[1], &nb->R[0], &nb->R[1]);
if (err != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
nb->state = TFM_EXPTMOD_NB_MONT_MOD;
break;
case TFM_EXPTMOD_NB_MONT_MOD:
/* mod m */
err = fp_div(&nb->R[1], P, NULL, &nb->R[1]);
if (err != FP_OKAY) {
nb->state = TFM_EXPTMOD_NB_INIT;
return err;
}
nb->state = TFM_EXPTMOD_NB_MONT_MODCHK;
break;
case TFM_EXPTMOD_NB_MONT_MODCHK:
/* m matches sign of (G * R mod m) */
if (nb->R[1].sign != P->sign) {
fp_add(&nb->R[1], P, &nb->R[1]);
}
/* set initial mode and bit cnt */
nb->bitcnt = 1;
nb->buf = 0;
nb->digidx = X->used - 1;
nb->state = TFM_EXPTMOD_NB_NEXT;
break;
case TFM_EXPTMOD_NB_NEXT:
/* grab next digit as required */
if (--nb->bitcnt == 0) {
/* if nb->digidx == -1 we are out of digits so break */
if (nb->digidx == -1) {
nb->state = TFM_EXPTMOD_NB_RED;
break;
}
/* read next digit and reset nb->bitcnt */
nb->buf = X->dp[nb->digidx--];
nb->bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
nb->y = (int)(nb->buf >> (DIGIT_BIT - 1)) & 1;
nb->buf <<= (fp_digit)1;
nb->state = TFM_EXPTMOD_NB_MUL;
FALL_THROUGH;
case TFM_EXPTMOD_NB_MUL:
fp_mul(&nb->R[0], &nb->R[1], &nb->R[nb->y^1]);
nb->state = TFM_EXPTMOD_NB_MUL_RED;
break;
case TFM_EXPTMOD_NB_MUL_RED:
fp_montgomery_reduce(&nb->R[nb->y^1], P, nb->mp);
nb->state = TFM_EXPTMOD_NB_SQR;
break;
case TFM_EXPTMOD_NB_SQR:
#ifdef WC_NO_CACHE_RESISTANT
fp_sqr(&nb->R[nb->y], &nb->R[nb->y]);
#else
fp_copy((fp_int*) ( ((wolfssl_word)&nb->R[0] & wc_off_on_addr[nb->y^1]) +
((wolfssl_word)&nb->R[1] & wc_off_on_addr[nb->y]) ),
&nb->R[2]);
fp_sqr(&nb->R[2], &nb->R[2]);
#endif /* WC_NO_CACHE_RESISTANT */
nb->state = TFM_EXPTMOD_NB_SQR_RED;
break;
case TFM_EXPTMOD_NB_SQR_RED:
#ifdef WC_NO_CACHE_RESISTANT
fp_montgomery_reduce(&nb->R[nb->y], P, nb->mp);
#else
fp_montgomery_reduce(&nb->R[2], P, nb->mp);
fp_copy(&nb->R[2],
(fp_int*) ( ((wolfssl_word)&nb->R[0] & wc_off_on_addr[nb->y^1]) +
((wolfssl_word)&nb->R[1] & wc_off_on_addr[nb->y]) ) );
#endif /* WC_NO_CACHE_RESISTANT */
nb->state = TFM_EXPTMOD_NB_NEXT;
break;
case TFM_EXPTMOD_NB_RED:
/* final reduce */
fp_montgomery_reduce(&nb->R[0], P, nb->mp);
fp_copy(&nb->R[0], Y);
nb->state = TFM_EXPTMOD_NB_INIT;
ret = FP_OKAY;
break;
} /* switch */
#ifdef WC_RSA_NONBLOCK_TIME
/* determine if maximum blocking time has been reached */
} while (ret == FP_WOULDBLOCK &&
FP_EXPTMOD_NB_CHECKTIME(nb) == TFM_EXPTMOD_NB_CONTINUE);
#endif
return ret;
}
#endif /* WC_RSA_NONBLOCK */
/* timing resistant montgomery ladder based exptmod
Based on work by Marc Joye, Sung-Ming Yen, "The Montgomery Powering Ladder",
Cryptographic Hardware and Embedded Systems, CHES 2002
*/
static int _fp_exptmod(fp_int * G, fp_int * X, int digits, fp_int * P, fp_int * Y)
{
#ifndef WOLFSSL_SMALL_STACK
#ifdef WC_NO_CACHE_RESISTANT
fp_int R[2];
#else
fp_int R[3]; /* need a temp for cache resistance */
#endif
#else
fp_int *R;
#endif
fp_digit buf, mp;
int err, bitcnt, digidx, y;
/* now setup montgomery */
if ((err = fp_montgomery_setup (P, &mp)) != FP_OKAY) {
return err;
}
#ifdef WOLFSSL_SMALL_STACK
#ifndef WC_NO_CACHE_RESISTANT
R = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
#else
R = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
#endif
if (R == NULL)
return FP_MEM;
#endif
fp_init(&R[0]);
fp_init(&R[1]);
#ifndef WC_NO_CACHE_RESISTANT
fp_init(&R[2]);
#endif
/* now we need R mod m */
fp_montgomery_calc_normalization (&R[0], P);
/* now set R[0][1] to G * R mod m */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &R[1]);
} else {
fp_copy(G, &R[1]);
}
fp_mulmod (&R[1], &R[0], P, &R[1]);
/* for j = t-1 downto 0 do
r_!k = R0*R1; r_k = r_k^2
*/
/* set initial mode and bit cnt */
bitcnt = 1;
buf = 0;
digidx = digits - 1;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* do ops */
err = fp_mul(&R[0], &R[1], &R[y^1]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[y^1], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#ifdef WC_NO_CACHE_RESISTANT
err = fp_sqr(&R[y], &R[y]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[y], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#else
/* instead of using R[y] for sqr, which leaks key bit to cache monitor,
* use R[2] as temp, make sure address calc is constant, keep
* &R[0] and &R[1] in cache */
fp_copy((fp_int*) ( ((wolfssl_word)&R[0] & wc_off_on_addr[y^1]) +
((wolfssl_word)&R[1] & wc_off_on_addr[y]) ),
&R[2]);
err = fp_sqr(&R[2], &R[2]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&R[2], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_copy(&R[2],
(fp_int*) ( ((wolfssl_word)&R[0] & wc_off_on_addr[y^1]) +
((wolfssl_word)&R[1] & wc_off_on_addr[y]) ) );
#endif /* WC_NO_CACHE_RESISTANT */
}
err = fp_montgomery_reduce(&R[0], P, mp);
fp_copy(&R[0], Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(R, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#else /* TFM_TIMING_RESISTANT */
/* y = g**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod(fp_int * G, fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
fp_int *M;
#else
fp_int res[1];
fp_int M[64];
#endif
(void)digits;
/* find window size */
x = fp_count_bits (X);
if (x <= 21) {
winsize = 1;
} else if (x <= 36) {
winsize = 3;
} else if (x <= 140) {
winsize = 4;
} else if (x <= 450) {
winsize = 5;
} else {
winsize = 6;
}
/* now setup montgomery */
if ((err = fp_montgomery_setup (P, &mp)) != FP_OKAY) {
return err;
}
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
M = (fp_int*)XMALLOC(sizeof(fp_int)*((1 << winsize) + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (M == NULL) {
return FP_MEM;
}
res = &M[1 << winsize];
#endif
/* init M array */
for(x = 0; x < (1 << winsize); x++)
fp_init(&M[x]);
/* setup result */
fp_init(res);
/* create M table
*
* The M table contains powers of the input base, e.g. M[x] = G^x mod P
*
* The first half of the table is not computed though except for M[0] and M[1]
*/
/* now we need R mod m */
fp_montgomery_calc_normalization (res, P);
/* now set M[1] to G * R mod m */
if (fp_cmp_mag(P, G) != FP_GT) {
/* G > P so we reduce it first */
fp_mod(G, P, &M[1]);
} else {
fp_copy(G, &M[1]);
}
fp_mulmod (&M[1], res, P, &M[1]);
/* compute the value at M[1<<(winsize-1)] by
* squaring M[1] (winsize-1) times */
fp_copy (&M[1], &M[1 << (winsize - 1)]);
for (x = 0; x < (winsize - 1); x++) {
fp_sqr (&M[1 << (winsize - 1)], &M[1 << (winsize - 1)]);
err = fp_montgomery_reduce (&M[1 << (winsize - 1)], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* create upper table */
for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
err = fp_mul(&M[x - 1], &M[1], &M[x]);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(&M[x], P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* set initial mode and bit cnt */
mode = 0;
bitcnt = 1;
buf = 0;
digidx = X->used - 1;
bitcpy = 0;
bitbuf = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* if the bit is zero and mode == 0 then we ignore it
* These represent the leading zero bits before the first 1 bit
* in the exponent. Technically this opt is not required but it
* does lower the # of trivial squaring/reductions used
*/
if (mode == 0 && y == 0) {
continue;
}
/* if the bit is zero and mode == 1 then we square */
if (mode == 1 && y == 0) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
continue;
}
/* else we add it to the window */
bitbuf |= (y << (winsize - ++bitcpy));
mode = 2;
if (bitcpy == winsize) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < winsize; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
/* then multiply */
err = fp_mul(res, &M[bitbuf], res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
mode = 1;
}
}
/* if bits remain then square/multiply */
if (mode == 2 && bitcpy > 0) {
/* square then multiply if the bit is set */
for (x = 0; x < bitcpy; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* get next bit of the window */
bitbuf <<= 1;
if ((bitbuf & (1 << winsize)) != 0) {
/* then multiply */
err = fp_mul(res, &M[1], res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
}
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy (res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
#endif /* TFM_TIMING_RESISTANT */
#ifdef TFM_TIMING_RESISTANT
#if DIGIT_BIT <= 16
#define WINSIZE 2
#elif DIGIT_BIT <= 32
#define WINSIZE 3
#elif DIGIT_BIT <= 64
#define WINSIZE 4
#elif DIGIT_BIT <= 128
#define WINSIZE 5
#endif
/* y = 2**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod_base_2(fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, digidx, x, y;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
fp_int *tmp;
#else
fp_int res[1];
fp_int tmp[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
res = (fp_int*)XMALLOC(2*sizeof(fp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (res == NULL) {
return FP_MEM;
}
tmp = &res[1];
#endif
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &mp)) != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* setup result */
fp_init(res);
fp_init(tmp);
fp_mul_2d(P, 1 << WINSIZE, tmp);
/* now we need R mod m */
fp_montgomery_calc_normalization(res, P);
/* Get the top bits left over after taking WINSIZE bits starting at the
* least-significant.
*/
digidx = digits - 1;
bitcpy = (digits * DIGIT_BIT) % WINSIZE;
if (bitcpy > 0) {
bitcnt = (int)DIGIT_BIT - bitcpy;
buf = X->dp[digidx--];
bitbuf = (int)(buf >> bitcnt);
/* Multiply montgomery representation of 1 by 2 ^ top */
fp_mul_2d(res, bitbuf, res);
fp_add(res, tmp, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* Move out bits used */
buf <<= bitcpy;
bitcnt++;
}
else {
bitcnt = 1;
buf = 0;
}
/* empty window and reset */
bitbuf = 0;
bitcpy = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* add bit to the window */
bitbuf |= (y << (WINSIZE - ++bitcpy));
if (bitcpy == WINSIZE) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < WINSIZE; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
}
/* then multiply by 2^bitbuf */
fp_mul_2d(res, bitbuf, res);
/* Add in value to make mod operation take same time */
fp_add(res, tmp, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy(res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
#undef WINSIZE
#else
#if DIGIT_BIT < 16
#define WINSIZE 3
#elif DIGIT_BIT < 32
#define WINSIZE 4
#elif DIGIT_BIT < 64
#define WINSIZE 5
#elif DIGIT_BIT < 128
#define WINSIZE 6
#elif DIGIT_BIT == 128
#define WINSIZE 7
#endif
/* y = 2**x (mod b)
* Some restrictions... x must be positive and < b
*/
static int _fp_exptmod_base_2(fp_int * X, int digits, fp_int * P,
fp_int * Y)
{
fp_digit buf, mp;
int err, bitbuf, bitcpy, bitcnt, digidx, x, y;
#ifdef WOLFSSL_SMALL_STACK
fp_int *res;
#else
fp_int res[1];
#endif
#ifdef WOLFSSL_SMALL_STACK
res = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (res == NULL) {
return FP_MEM;
}
#endif
/* now setup montgomery */
if ((err = fp_montgomery_setup(P, &mp)) != FP_OKAY) {
return err;
}
/* setup result */
fp_init(res);
/* now we need R mod m */
fp_montgomery_calc_normalization(res, P);
/* Get the top bits left over after taking WINSIZE bits starting at the
* least-significant.
*/
digidx = digits - 1;
bitcpy = (digits * DIGIT_BIT) % WINSIZE;
if (bitcpy > 0) {
bitcnt = (int)DIGIT_BIT - bitcpy;
buf = X->dp[digidx--];
bitbuf = (int)(buf >> bitcnt);
/* Multiply montgomery representation of 1 by 2 ^ top */
fp_mul_2d(res, bitbuf, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* Move out bits used */
buf <<= bitcpy;
bitcnt++;
}
else {
bitcnt = 1;
buf = 0;
}
/* empty window and reset */
bitbuf = 0;
bitcpy = 0;
for (;;) {
/* grab next digit as required */
if (--bitcnt == 0) {
/* if digidx == -1 we are out of digits so break */
if (digidx == -1) {
break;
}
/* read next digit and reset bitcnt */
buf = X->dp[digidx--];
bitcnt = (int)DIGIT_BIT;
}
/* grab the next msb from the exponent */
y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
buf <<= (fp_digit)1;
/* add bit to the window */
bitbuf |= (y << (WINSIZE - ++bitcpy));
if (bitcpy == WINSIZE) {
/* ok window is filled so square as required and multiply */
/* square first */
for (x = 0; x < WINSIZE; x++) {
err = fp_sqr(res, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
err = fp_montgomery_reduce(res, P, mp);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
}
/* then multiply by 2^bitbuf */
fp_mul_2d(res, bitbuf, res);
err = fp_mod(res, P, res);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
/* empty window and reset */
bitcpy = 0;
bitbuf = 0;
}
}
/* fixup result if Montgomery reduction is used
* recall that any value in a Montgomery system is
* actually multiplied by R mod n. So we have
* to reduce one more time to cancel out the factor
* of R.
*/
err = fp_montgomery_reduce(res, P, mp);
/* swap res with Y */
fp_copy(res, Y);
#ifdef WOLFSSL_SMALL_STACK
XFREE(res, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
#undef WINSIZE
#endif
int fp_exptmod(fp_int * G, fp_int * X, fp_int * P, fp_int * Y)
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int x = fp_count_bits (X);
#endif
/* handle modulus of zero and prevent overflows */
if (fp_iszero(P) || (P->used > (FP_SIZE/2))) {
return FP_VAL;
}
if (fp_isone(P)) {
fp_set(Y, 0);
return FP_OKAY;
}
if (fp_iszero(X)) {
fp_set(Y, 1);
return FP_OKAY;
}
if (fp_iszero(G)) {
fp_set(Y, 0);
return FP_OKAY;
}
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
if(x > EPS_RSA_EXPT_XBTIS) {
return esp_mp_exptmod(G, X, x, P, Y);
}
#endif
if (X->sign == FP_NEG) {
#ifndef POSITIVE_EXP_ONLY /* reduce stack if assume no negatives */
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[2];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* yes, copy G and invmod it */
fp_init_copy(&tmp[0], G);
fp_init_copy(&tmp[1], P);
tmp[1].sign = FP_ZPOS;
err = fp_invmod(&tmp[0], &tmp[1], &tmp[0]);
if (err == FP_OKAY) {
fp_copy(X, &tmp[1]);
tmp[1].sign = FP_ZPOS;
err = _fp_exptmod(&tmp[0], &tmp[1], tmp[1].used, P, Y);
if (P->sign == FP_NEG) {
fp_add(Y, P, Y);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
#else
return FP_VAL;
#endif
}
else if (G->used == 1 && G->dp[0] == 2) {
return _fp_exptmod_base_2(X, X->used, P, Y);
}
else {
/* Positive exponent so just exptmod */
return _fp_exptmod(G, X, X->used, P, Y);
}
}
int fp_exptmod_ex(fp_int * G, fp_int * X, int digits, fp_int * P, fp_int * Y)
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int x = fp_count_bits (X);
#endif
if (fp_iszero(G)) {
fp_set(G, 0);
return FP_OKAY;
}
/* prevent overflows */
if (P->used > (FP_SIZE/2)) {
return FP_VAL;
}
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
if(x > EPS_RSA_EXPT_XBTIS) {
return esp_mp_exptmod(G, X, x, P, Y);
}
#endif
if (X->sign == FP_NEG) {
#ifndef POSITIVE_EXP_ONLY /* reduce stack if assume no negatives */
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[2];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (tmp == NULL)
return FP_MEM;
#endif
/* yes, copy G and invmod it */
fp_init_copy(&tmp[0], G);
fp_init_copy(&tmp[1], P);
tmp[1].sign = FP_ZPOS;
err = fp_invmod(&tmp[0], &tmp[1], &tmp[0]);
if (err == FP_OKAY) {
X->sign = FP_ZPOS;
err = _fp_exptmod(&tmp[0], X, digits, P, Y);
if (X != Y) {
X->sign = FP_NEG;
}
if (P->sign == FP_NEG) {
fp_add(Y, P, Y);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
#else
return FP_VAL;
#endif
}
else {
/* Positive exponent so just exptmod */
return _fp_exptmod(G, X, digits, P, Y);
}
}
/* computes a = 2**b */
void fp_2expt(fp_int *a, int b)
{
int z;
/* zero a as per default */
fp_zero (a);
if (b < 0) {
return;
}
z = b / DIGIT_BIT;
if (z >= FP_SIZE) {
return;
}
/* set the used count of where the bit will go */
a->used = z + 1;
/* put the single bit in its place */
a->dp[z] = ((fp_digit)1) << (b % DIGIT_BIT);
}
/* b = a*a */
int fp_sqr(fp_int *A, fp_int *B)
{
int err;
int y, oldused;
oldused = B->used;
y = A->used;
/* call generic if we're out of range */
if (y + y > FP_SIZE) {
err = fp_sqr_comba(A, B);
goto clean;
}
#if defined(TFM_SQR3) && FP_SIZE >= 6
if (y <= 3) {
err = fp_sqr_comba3(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR4) && FP_SIZE >= 8
if (y == 4) {
err = fp_sqr_comba4(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR6) && FP_SIZE >= 12
if (y <= 6) {
err = fp_sqr_comba6(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR7) && FP_SIZE >= 14
if (y == 7) {
err = fp_sqr_comba7(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR8) && FP_SIZE >= 16
if (y == 8) {
err = fp_sqr_comba8(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR9) && FP_SIZE >= 18
if (y == 9) {
err = fp_sqr_comba9(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR12) && FP_SIZE >= 24
if (y <= 12) {
err = fp_sqr_comba12(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR17) && FP_SIZE >= 34
if (y <= 17) {
err = fp_sqr_comba17(A,B);
goto clean;
}
#endif
#if defined(TFM_SMALL_SET)
if (y <= 16) {
err = fp_sqr_comba_small(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR20) && FP_SIZE >= 40
if (y <= 20) {
err = fp_sqr_comba20(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR24) && FP_SIZE >= 48
if (y <= 24) {
err = fp_sqr_comba24(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR28) && FP_SIZE >= 56
if (y <= 28) {
err = fp_sqr_comba28(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR32) && FP_SIZE >= 64
if (y <= 32) {
err = fp_sqr_comba32(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR48) && FP_SIZE >= 96
if (y <= 48) {
err = fp_sqr_comba48(A,B);
goto clean;
}
#endif
#if defined(TFM_SQR64) && FP_SIZE >= 128
if (y <= 64) {
err = fp_sqr_comba64(A,B);
goto clean;
}
#endif
err = fp_sqr_comba(A, B);
clean:
/* zero any excess digits on the destination that we didn't write to */
for (y = B->used; y >= 0 && y < oldused; y++) {
B->dp[y] = 0;
}
return err;
}
/* generic comba squarer */
int fp_sqr_comba(fp_int *A, fp_int *B)
{
int pa, ix, iz;
fp_digit c0, c1, c2;
#ifdef TFM_ISO
fp_word tt;
#endif
fp_int *dst;
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
/* Variables used but not seen by cppcheck. */
(void)c0; (void)c1; (void)c2;
#ifdef TFM_ISO
(void)tt;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
/* get size of output and trim */
pa = A->used + A->used;
if (pa >= FP_SIZE) {
pa = FP_SIZE-1;
}
/* number of output digits to produce */
COMBA_START;
COMBA_CLEAR;
if (A == B) {
fp_init(tmp);
dst = tmp;
} else {
fp_zero(B);
dst = B;
}
for (ix = 0; ix < pa; ix++) {
int tx, ty, iy;
fp_digit *tmpy, *tmpx;
/* get offsets into the two bignums */
ty = MIN(A->used-1, ix);
tx = ix - ty;
/* setup temp aliases */
tmpx = A->dp + tx;
tmpy = A->dp + ty;
/* this is the number of times the loop will iterate,
while (tx++ < a->used && ty-- >= 0) { ... }
*/
iy = MIN(A->used-tx, ty+1);
/* now for squaring tx can never equal ty
* we halve the distance since they approach
* at a rate of 2x and we have to round because
* odd cases need to be executed
*/
iy = MIN(iy, (ty-tx+1)>>1);
/* forward carries */
COMBA_FORWARD;
/* execute loop */
for (iz = 0; iz < iy; iz++) {
SQRADD2(*tmpx++, *tmpy--);
}
/* even columns have the square term in them */
if ((ix&1) == 0) {
/* TAO change COMBA_ADD back to SQRADD */
SQRADD(A->dp[ix>>1], A->dp[ix>>1]);
}
/* store it */
COMBA_STORE(dst->dp[ix]);
}
COMBA_FINI;
/* setup dest */
dst->used = pa;
fp_clamp (dst);
if (dst != B) {
fp_copy(dst, B);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int fp_cmp(fp_int *a, fp_int *b)
{
if (a->sign == FP_NEG && b->sign == FP_ZPOS) {
return FP_LT;
} else if (a->sign == FP_ZPOS && b->sign == FP_NEG) {
return FP_GT;
} else {
/* compare digits */
if (a->sign == FP_NEG) {
/* if negative compare opposite direction */
return fp_cmp_mag(b, a);
} else {
return fp_cmp_mag(a, b);
}
}
}
/* compare against a single digit */
int fp_cmp_d(fp_int *a, fp_digit b)
{
/* special case for zero*/
if (a->used == 0 && b == 0)
return FP_EQ;
/* compare based on sign */
if ((b && a->used == 0) || a->sign == FP_NEG) {
return FP_LT;
}
/* compare based on magnitude */
if (a->used > 1) {
return FP_GT;
}
/* compare the only digit of a to b */
if (a->dp[0] > b) {
return FP_GT;
} else if (a->dp[0] < b) {
return FP_LT;
} else {
return FP_EQ;
}
}
int fp_cmp_mag(fp_int *a, fp_int *b)
{
int x;
if (a->used > b->used) {
return FP_GT;
} else if (a->used < b->used) {
return FP_LT;
} else {
for (x = a->used - 1; x >= 0; x--) {
if (a->dp[x] > b->dp[x]) {
return FP_GT;
} else if (a->dp[x] < b->dp[x]) {
return FP_LT;
}
}
}
return FP_EQ;
}
/* sets up the montgomery reduction */
int fp_montgomery_setup(fp_int *a, fp_digit *rho)
{
fp_digit x, b;
/* fast inversion mod 2**k
*
* Based on the fact that
*
* XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
* => 2*X*A - X*X*A*A = 1
* => 2*(1) - (1) = 1
*/
b = a->dp[0];
if ((b & 1) == 0) {
return FP_VAL;
}
x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
x *= 2 - b * x; /* here x*a==1 mod 2**8 */
x *= 2 - b * x; /* here x*a==1 mod 2**16 */
x *= 2 - b * x; /* here x*a==1 mod 2**32 */
#ifdef FP_64BIT
x *= 2 - b * x; /* here x*a==1 mod 2**64 */
#endif
/* rho = -1/m mod b */
*rho = (fp_digit) (((fp_word) 1 << ((fp_word) DIGIT_BIT)) - ((fp_word)x));
return FP_OKAY;
}
/* computes a = B**n mod b without division or multiplication useful for
* normalizing numbers in a Montgomery system.
*/
void fp_montgomery_calc_normalization(fp_int *a, fp_int *b)
{
int x, bits;
/* how many bits of last digit does b use */
bits = fp_count_bits (b) % DIGIT_BIT;
if (!bits) bits = DIGIT_BIT;
/* compute A = B^(n-1) * 2^(bits-1) */
if (b->used > 1) {
fp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1);
} else {
fp_set(a, 1);
bits = 1;
}
/* now compute C = A * B mod b */
for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
fp_mul_2 (a, a);
if (fp_cmp_mag (a, b) != FP_LT) {
s_fp_sub (a, b, a);
}
}
}
#ifdef TFM_SMALL_MONT_SET
#include "fp_mont_small.i"
#endif
#ifdef HAVE_INTEL_MULX
static WC_INLINE void innermul8_mulx(fp_digit *c_mulx, fp_digit *cy_mulx, fp_digit *tmpm, fp_digit mu)
{
fp_digit cy = *cy_mulx ;
INNERMUL8_MULX ;
*cy_mulx = cy ;
}
/* computes x/R == x (mod N) via Montgomery Reduction */
static int fp_montgomery_reduce_mulx(fp_int *a, fp_int *m, fp_digit mp)
{
#ifndef WOLFSSL_SMALL_STACK
fp_digit c[FP_SIZE+1];
#else
fp_digit *c;
#endif
fp_digit *_c, *tmpm, mu = 0;
int oldused, x, y, pa;
/* bail if too large */
if (m->used > (FP_SIZE/2)) {
(void)mu; /* shut up compiler */
return FP_OKAY;
}
#ifdef TFM_SMALL_MONT_SET
if (m->used <= 16) {
return fp_montgomery_reduce_small(a, m, mp);
}
#endif
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
c = (fp_digit*)XMALLOC(sizeof(fp_digit)*(FP_SIZE + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (c == NULL) {
return FP_MEM;
}
#endif
/* now zero the buff */
XMEMSET(c, 0, sizeof(fp_digit)*(FP_SIZE + 1));
pa = m->used;
/* copy the input */
oldused = a->used;
for (x = 0; x < oldused; x++) {
c[x] = a->dp[x];
}
MONT_START;
for (x = 0; x < pa; x++) {
fp_digit cy = 0;
/* get Mu for this round */
LOOP_START;
_c = c + x;
tmpm = m->dp;
y = 0;
for (; y < (pa & ~7); y += 8) {
innermul8_mulx(_c, &cy, tmpm, mu) ;
_c += 8;
tmpm += 8;
}
for (; y < pa; y++) {
INNERMUL;
++_c;
}
LOOP_END;
while (cy) {
PROPCARRY;
++_c;
}
}
/* now copy out */
_c = c + pa;
tmpm = a->dp;
for (x = 0; x < pa+1; x++) {
*tmpm++ = *_c++;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
*tmpm++ = 0;
}
MONT_FINI;
a->used = pa+1;
fp_clamp(a);
/* if A >= m then A = A - m */
if (fp_cmp_mag (a, m) != FP_LT) {
s_fp_sub (a, m, a);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
/* computes x/R == x (mod N) via Montgomery Reduction */
int fp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp)
{
#ifndef WOLFSSL_SMALL_STACK
fp_digit c[FP_SIZE+1];
#else
fp_digit *c;
#endif
fp_digit *_c, *tmpm, mu = 0;
int oldused, x, y, pa, err = 0;
IF_HAVE_INTEL_MULX(err = fp_montgomery_reduce_mulx(a, m, mp), return err) ;
(void)err;
/* bail if too large */
if (m->used > (FP_SIZE/2)) {
(void)mu; /* shut up compiler */
return FP_OKAY;
}
#ifdef TFM_SMALL_MONT_SET
if (m->used <= 16) {
return fp_montgomery_reduce_small(a, m, mp);
}
#endif
#ifdef WOLFSSL_SMALL_STACK
/* only allocate space for what's needed for window plus res */
c = (fp_digit*)XMALLOC(sizeof(fp_digit)*(FP_SIZE + 1), NULL, DYNAMIC_TYPE_BIGINT);
if (c == NULL) {
return FP_MEM;
}
#endif
/* now zero the buff */
XMEMSET(c, 0, sizeof(fp_digit)*(FP_SIZE + 1));
pa = m->used;
/* copy the input */
oldused = a->used;
for (x = 0; x < oldused; x++) {
c[x] = a->dp[x];
}
MONT_START;
for (x = 0; x < pa; x++) {
fp_digit cy = 0;
/* get Mu for this round */
LOOP_START;
_c = c + x;
tmpm = m->dp;
y = 0;
#if defined(INNERMUL8)
for (; y < (pa & ~7); y += 8) {
INNERMUL8 ;
_c += 8;
tmpm += 8;
}
#endif
for (; y < pa; y++) {
INNERMUL;
++_c;
}
LOOP_END;
while (cy) {
PROPCARRY;
++_c;
}
}
/* now copy out */
_c = c + pa;
tmpm = a->dp;
for (x = 0; x < pa+1; x++) {
*tmpm++ = *_c++;
}
/* zero any excess digits on the destination that we didn't write to */
for (; x < oldused; x++) {
*tmpm++ = 0;
}
MONT_FINI;
a->used = pa+1;
fp_clamp(a);
/* if A >= m then A = A - m */
if (fp_cmp_mag (a, m) != FP_LT) {
s_fp_sub (a, m, a);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(c, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
void fp_read_unsigned_bin(fp_int *a, const unsigned char *b, int c)
{
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
const word32 maxC = (a->size * sizeof(fp_digit));
#else
const word32 maxC = (FP_SIZE * sizeof(fp_digit));
#endif
/* zero the int */
fp_zero (a);
/* if input b excess max, then truncate */
if (c > 0 && (word32)c > maxC) {
int excess = (c - maxC);
c -= excess;
b += excess;
}
/* If we know the endianness of this architecture, and we're using
32-bit fp_digits, we can optimize this */
#if (defined(LITTLE_ENDIAN_ORDER) || defined(BIG_ENDIAN_ORDER)) && \
defined(FP_32BIT)
/* But not for both simultaneously */
#if defined(LITTLE_ENDIAN_ORDER) && defined(BIG_ENDIAN_ORDER)
#error Both LITTLE_ENDIAN_ORDER and BIG_ENDIAN_ORDER defined.
#endif
{
unsigned char *pd = (unsigned char *)a->dp;
a->used = (c + sizeof(fp_digit) - 1)/sizeof(fp_digit);
/* read the bytes in */
#ifdef BIG_ENDIAN_ORDER
{
/* Use Duff's device to unroll the loop. */
int idx = (c - 1) & ~3;
switch (c % 4) {
case 0: do { pd[idx+0] = *b++; // fallthrough
case 3: pd[idx+1] = *b++; // fallthrough
case 2: pd[idx+2] = *b++; // fallthrough
case 1: pd[idx+3] = *b++; // fallthrough
idx -= 4;
} while ((c -= 4) > 0);
}
}
#else
for (c -= 1; c >= 0; c -= 1) {
pd[c] = *b++;
}
#endif
}
#else
/* read the bytes in */
for (; c > 0; c--) {
fp_mul_2d (a, 8, a);
a->dp[0] |= *b++;
if (a->used == 0) {
a->used = 1;
}
}
#endif
fp_clamp (a);
}
int fp_to_unsigned_bin_at_pos(int x, fp_int *t, unsigned char *b)
{
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
int i, j;
fp_digit n;
for (j=0,i=0; i<t->used-1; ) {
b[x++] = (unsigned char)(t->dp[i] >> j);
j += 8;
i += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
n = t->dp[i];
while (n != 0) {
b[x++] = (unsigned char)n;
n >>= 8;
}
return x;
#else
while (fp_iszero (t) == FP_NO) {
b[x++] = (unsigned char) (t->dp[0] & 255);
fp_div_2d (t, 8, t, NULL);
}
return x;
#endif
}
int fp_to_unsigned_bin(fp_int *a, unsigned char *b)
{
int x;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init_copy(t, a);
x = fp_to_unsigned_bin_at_pos(0, t, b);
fp_reverse (b, x);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int fp_to_unsigned_bin_len(fp_int *a, unsigned char *b, int c)
{
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
int i, j, x;
for (x=c-1,j=0,i=0; x >= 0; x--) {
b[x] = (unsigned char)(a->dp[i] >> j);
j += 8;
i += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
return FP_OKAY;
#else
int x;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init_copy(t, a);
for (x = 0; x < c; x++) {
b[x] = (unsigned char) (t->dp[0] & 255);
fp_div_2d (t, 8, t, NULL);
}
fp_reverse (b, x);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
#endif
}
int fp_unsigned_bin_size(fp_int *a)
{
int size = fp_count_bits (a);
return (size / 8 + ((size & 7) != 0 ? 1 : 0));
}
void fp_set(fp_int *a, fp_digit b)
{
fp_zero(a);
a->dp[0] = b;
a->used = a->dp[0] ? 1 : 0;
}
#ifndef MP_SET_CHUNK_BITS
#define MP_SET_CHUNK_BITS 4
#endif
void fp_set_int(fp_int *a, unsigned long b)
{
int x;
/* use direct fp_set if b is less than fp_digit max */
if (b < FP_DIGIT_MAX) {
fp_set (a, (fp_digit)b);
return;
}
fp_zero (a);
/* set chunk bits at a time */
for (x = 0; x < (int)(sizeof(b) * 8) / MP_SET_CHUNK_BITS; x++) {
fp_mul_2d (a, MP_SET_CHUNK_BITS, a);
/* OR in the top bits of the source */
a->dp[0] |= (b >> ((sizeof(b) * 8) - MP_SET_CHUNK_BITS)) &
((1 << MP_SET_CHUNK_BITS) - 1);
/* shift the source up to the next chunk bits */
b <<= MP_SET_CHUNK_BITS;
/* ensure that digits are not clamped off */
a->used += 1;
}
/* clamp digits */
fp_clamp(a);
}
/* check if a bit is set */
int fp_is_bit_set (fp_int *a, fp_digit b)
{
fp_digit i;
if (b > FP_MAX_BITS)
return 0;
else
i = b/DIGIT_BIT;
if ((fp_digit)a->used < i)
return 0;
return (int)((a->dp[i] >> b%DIGIT_BIT) & (fp_digit)1);
}
/* set the b bit of a */
int fp_set_bit (fp_int * a, fp_digit b)
{
fp_digit i;
if (b > FP_MAX_BITS)
return 0;
else
i = b/DIGIT_BIT;
/* set the used count of where the bit will go if required */
if (a->used < (int)(i+1))
a->used = (int)(i+1);
/* put the single bit in its place */
a->dp[i] |= ((fp_digit)1) << (b % DIGIT_BIT);
return MP_OKAY;
}
int fp_count_bits (fp_int * a)
{
int r;
fp_digit q;
/* shortcut */
if (a->used == 0) {
return 0;
}
/* get number of digits and add that */
r = (a->used - 1) * DIGIT_BIT;
/* take the last digit and count the bits in it */
q = a->dp[a->used - 1];
while (q > ((fp_digit) 0)) {
++r;
q >>= ((fp_digit) 1);
}
return r;
}
int fp_leading_bit(fp_int *a)
{
int bit = 0;
if (a->used != 0) {
fp_digit q = a->dp[a->used - 1];
int qSz = sizeof(fp_digit);
while (qSz > 0) {
if ((unsigned char)q != 0)
bit = (q & 0x80) != 0;
q >>= 8;
qSz--;
}
}
return bit;
}
void fp_lshd(fp_int *a, int x)
{
int y;
/* move up and truncate as required */
y = MIN(a->used + x - 1, (int)(FP_SIZE-1));
/* store new size */
a->used = y + 1;
/* move digits */
for (; y >= x; y--) {
a->dp[y] = a->dp[y-x];
}
/* zero lower digits */
for (; y >= 0; y--) {
a->dp[y] = 0;
}
/* clamp digits */
fp_clamp(a);
}
/* right shift by bit count */
void fp_rshb(fp_int *c, int x)
{
fp_digit *tmpc, mask, shift;
fp_digit r, rr;
fp_digit D = x;
if (fp_iszero(c)) return;
/* mask */
mask = (((fp_digit)1) << D) - 1;
/* shift for lsb */
shift = DIGIT_BIT - D;
/* alias */
tmpc = c->dp + (c->used - 1);
/* carry */
r = 0;
for (x = c->used - 1; x >= 0; x--) {
/* get the lower bits of this word in a temp */
rr = *tmpc & mask;
/* shift the current word and mix in the carry bits from previous word */
*tmpc = (*tmpc >> D) | (r << shift);
--tmpc;
/* set the carry to the carry bits of the current word found above */
r = rr;
}
/* clamp digits */
fp_clamp(c);
}
void fp_rshd(fp_int *a, int x)
{
int y;
/* too many digits just zero and return */
if (x >= a->used) {
fp_zero(a);
return;
}
/* shift */
for (y = 0; y < a->used - x; y++) {
a->dp[y] = a->dp[y+x];
}
/* zero rest */
for (; y < a->used; y++) {
a->dp[y] = 0;
}
/* decrement count */
a->used -= x;
fp_clamp(a);
}
/* reverse an array, used for radix code */
void fp_reverse (unsigned char *s, int len)
{
int ix, iy;
unsigned char t;
ix = 0;
iy = len - 1;
while (ix < iy) {
t = s[ix];
s[ix] = s[iy];
s[iy] = t;
++ix;
--iy;
}
}
/* c = a - b */
int fp_sub_d(fp_int *a, fp_digit b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp[1];
#else
fp_int *tmp;
#endif
#ifdef WOLFSSL_SMALL_STACK
tmp = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (tmp == NULL)
return FP_MEM;
#endif
fp_init(tmp);
fp_set(tmp, b);
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (c->size < FP_SIZE) {
fp_sub(a, tmp, tmp);
fp_copy(tmp, c);
} else
#endif
{
fp_sub(a, tmp, c);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(tmp, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* wolfSSL callers from normal lib */
/* init a new mp_int */
int mp_init (mp_int * a)
{
if (a)
fp_init(a);
return MP_OKAY;
}
void fp_init(fp_int *a)
{
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
a->size = FP_SIZE;
#endif
#ifdef HAVE_WOLF_BIGINT
wc_bigint_init(&a->raw);
#endif
fp_zero(a);
}
void fp_zero(fp_int *a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
XMEMSET(a->dp, 0, size * sizeof(fp_digit));
}
void fp_clear(fp_int *a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
XMEMSET(a->dp, 0, size * sizeof(fp_digit));
fp_free(a);
}
void fp_forcezero (mp_int * a)
{
int size;
a->used = 0;
a->sign = FP_ZPOS;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
ForceZero(a->dp, size * sizeof(fp_digit));
#ifdef HAVE_WOLF_BIGINT
wc_bigint_zero(&a->raw);
#endif
fp_free(a);
}
void mp_forcezero (mp_int * a)
{
fp_forcezero(a);
}
void fp_free(fp_int* a)
{
#ifdef HAVE_WOLF_BIGINT
wc_bigint_free(&a->raw);
#else
(void)a;
#endif
}
/* clear one (frees) */
void mp_clear (mp_int * a)
{
if (a == NULL)
return;
fp_clear(a);
}
void mp_free(mp_int* a)
{
fp_free(a);
}
/* handle up to 6 inits */
int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d,
mp_int* e, mp_int* f)
{
if (a)
fp_init(a);
if (b)
fp_init(b);
if (c)
fp_init(c);
if (d)
fp_init(d);
if (e)
fp_init(e);
if (f)
fp_init(f);
return MP_OKAY;
}
/* high level addition (handles signs) */
int mp_add (mp_int * a, mp_int * b, mp_int * c)
{
fp_add(a, b, c);
return MP_OKAY;
}
/* high level subtraction (handles signs) */
int mp_sub (mp_int * a, mp_int * b, mp_int * c)
{
fp_sub(a, b, c);
return MP_OKAY;
}
/* high level multiplication (handles sign) */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mul(mp_int * a, mp_int * b, mp_int * c)
#else
int mp_mul (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_mul(a, b, c);
}
int mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
{
fp_mul_d(a, b, c);
return MP_OKAY;
}
/* d = a * b (mod c) */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
#else
int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
#endif
{
#if defined(WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI) && \
!defined(NO_WOLFSSL_ESP32WROOM32_CRYPT_RSA_PRI)
int A = fp_count_bits (a);
int B = fp_count_bits (b);
if( A >= ESP_RSA_MULM_BITS && B >= ESP_RSA_MULM_BITS)
return esp_mp_mulmod(a, b, c, d);
else
#endif
return fp_mulmod(a, b, c, d);
}
/* d = a - b (mod c) */
int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
{
return fp_submod(a, b, c, d);
}
/* d = a + b (mod c) */
int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
{
return fp_addmod(a, b, c, d);
}
/* c = a mod b, 0 <= c < b */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_mod (mp_int * a, mp_int * b, mp_int * c)
#else
int mp_mod (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_mod (a, b, c);
}
/* hac 14.61, pp608 */
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_invmod (mp_int * a, mp_int * b, mp_int * c)
#else
int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
#endif
{
return fp_invmod(a, b, c);
}
/* hac 14.61, pp608 */
int mp_invmod_mont_ct (mp_int * a, mp_int * b, mp_int * c, mp_digit mp)
{
return fp_invmod_mont_ct(a, b, c, mp);
}
/* this is a shell function that calls either the normal or Montgomery
* exptmod functions. Originally the call to the montgomery code was
* embedded in the normal function but that wasted a lot of stack space
* for nothing (since 99% of the time the Montgomery code would be called)
*/
#if defined(FREESCALE_LTC_TFM)
int wolfcrypt_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
#else
int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
#endif
{
return fp_exptmod(G, X, P, Y);
}
int mp_exptmod_ex (mp_int * G, mp_int * X, int digits, mp_int * P, mp_int * Y)
{
return fp_exptmod_ex(G, X, digits, P, Y);
}
/* compare two ints (signed)*/
int mp_cmp (mp_int * a, mp_int * b)
{
return fp_cmp(a, b);
}
/* compare a digit */
int mp_cmp_d(mp_int * a, mp_digit b)
{
return fp_cmp_d(a, b);
}
/* get the size for an unsigned equivalent */
int mp_unsigned_bin_size (mp_int * a)
{
return fp_unsigned_bin_size(a);
}
int mp_to_unsigned_bin_at_pos(int x, fp_int *t, unsigned char *b)
{
return fp_to_unsigned_bin_at_pos(x, t, b);
}
/* store in unsigned [big endian] format */
int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
{
return fp_to_unsigned_bin(a,b);
}
int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c)
{
return fp_to_unsigned_bin_len(a, b, c);
}
/* reads a unsigned char array, assumes the msb is stored first [big endian] */
int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
{
fp_read_unsigned_bin(a, b, c);
return MP_OKAY;
}
int mp_sub_d(fp_int *a, fp_digit b, fp_int *c)
{
return fp_sub_d(a, b, c);
}
int mp_mul_2d(fp_int *a, int b, fp_int *c)
{
fp_mul_2d(a, b, c);
return MP_OKAY;
}
int mp_2expt(fp_int* a, int b)
{
fp_2expt(a, b);
return MP_OKAY;
}
int mp_div(fp_int * a, fp_int * b, fp_int * c, fp_int * d)
{
return fp_div(a, b, c, d);
}
int mp_div_2d(fp_int* a, int b, fp_int* c, fp_int* d)
{
fp_div_2d(a, b, c, d);
return MP_OKAY;
}
void fp_copy(fp_int *a, fp_int *b)
{
/* if source and destination are different */
if (a != b) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
/* verify a will fit in b */
if (b->size >= a->used) {
int x, oldused;
oldused = b->used;
b->used = a->used;
b->sign = a->sign;
XMEMCPY(b->dp, a->dp, a->used * sizeof(fp_digit));
/* zero any excess digits on the destination that we didn't write to */
for (x = b->used; x >= 0 && x < oldused; x++) {
b->dp[x] = 0;
}
}
else {
/* TODO: Handle error case */
}
#else
/* all dp's are same size, so do straight copy */
b->used = a->used;
b->sign = a->sign;
XMEMCPY(b->dp, a->dp, FP_SIZE * sizeof(fp_digit));
#endif
}
}
void fp_init_copy(fp_int *a, fp_int* b)
{
if (a != b) {
fp_init(a);
fp_copy(b, a);
}
}
/* fast math wrappers */
int mp_copy(fp_int* a, fp_int* b)
{
fp_copy(a, b);
return MP_OKAY;
}
int mp_isodd(mp_int* a)
{
return fp_isodd(a);
}
int mp_iszero(mp_int* a)
{
return fp_iszero(a);
}
int mp_count_bits (mp_int* a)
{
return fp_count_bits(a);
}
int mp_leading_bit (mp_int* a)
{
return fp_leading_bit(a);
}
void mp_rshb (mp_int* a, int x)
{
fp_rshb(a, x);
}
void mp_rshd (mp_int* a, int x)
{
fp_rshd(a, x);
}
int mp_set_int(mp_int *a, unsigned long b)
{
fp_set_int(a, b);
return MP_OKAY;
}
int mp_is_bit_set (mp_int *a, mp_digit b)
{
return fp_is_bit_set(a, b);
}
int mp_set_bit(mp_int *a, mp_digit b)
{
return fp_set_bit(a, b);
}
#if defined(WOLFSSL_KEY_GEN) || defined (HAVE_ECC) || !defined(NO_DH) || \
!defined(NO_DSA) || !defined(NO_RSA)
/* c = a * a (mod b) */
int fp_sqrmod(fp_int *a, fp_int *b, fp_int *c)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
fp_init(t);
err = fp_sqr(a, t);
if (err == FP_OKAY) {
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
if (c->size < FP_SIZE) {
err = fp_mod(t, b, t);
fp_copy(t, c);
}
else
#endif
{
err = fp_mod(t, b, c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* fast math conversion */
int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c)
{
return fp_sqrmod(a, b, c);
}
/* fast math conversion */
int mp_montgomery_calc_normalization(mp_int *a, mp_int *b)
{
fp_montgomery_calc_normalization(a, b);
return MP_OKAY;
}
#endif /* WOLFSSL_KEYGEN || HAVE_ECC */
#if defined(WC_MP_TO_RADIX) || !defined(NO_DH) || !defined(NO_DSA) || \
!defined(NO_RSA)
#ifdef WOLFSSL_KEY_GEN
/* swap the elements of two integers, for cases where you can't simply swap the
* mp_int pointers around
*/
static int fp_exch (fp_int * a, fp_int * b)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
*t = *a;
*a = *b;
*b = *t;
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif
static const int lnz[16] = {
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
};
/* Counts the number of lsbs which are zero before the first zero bit */
int fp_cnt_lsb(fp_int *a)
{
int x;
fp_digit q, qq;
/* easy out */
if (fp_iszero(a) == FP_YES) {
return 0;
}
/* scan lower digits until non-zero */
for (x = 0; x < a->used && a->dp[x] == 0; x++) {}
q = a->dp[x];
x *= DIGIT_BIT;
/* now scan this digit until a 1 is found */
if ((q & 1) == 0) {
do {
qq = q & 15;
x += lnz[qq];
q >>= 4;
} while (qq == 0);
}
return x;
}
static int s_is_power_of_two(fp_digit b, int *p)
{
int x;
/* fast return if no power of two */
if ((b==0) || (b & (b-1))) {
return FP_NO;
}
for (x = 0; x < DIGIT_BIT; x++) {
if (b == (((fp_digit)1)<<x)) {
*p = x;
return FP_YES;
}
}
return FP_NO;
}
/* a/b => cb + d == a */
static int fp_div_d(fp_int *a, fp_digit b, fp_int *c, fp_digit *d)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int q[1];
#else
fp_int *q;
#endif
fp_word w;
fp_digit t;
int ix;
/* cannot divide by zero */
if (b == 0) {
return FP_VAL;
}
/* quick outs */
if (b == 1 || fp_iszero(a) == FP_YES) {
if (d != NULL) {
*d = 0;
}
if (c != NULL) {
fp_copy(a, c);
}
return FP_OKAY;
}
/* power of two ? */
if (s_is_power_of_two(b, &ix) == FP_YES) {
if (d != NULL) {
*d = a->dp[0] & ((((fp_digit)1)<<ix) - 1);
}
if (c != NULL) {
fp_div_2d(a, ix, c, NULL);
}
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
q = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (q == NULL)
return FP_MEM;
#endif
fp_init(q);
if (c != NULL) {
q->used = a->used;
q->sign = a->sign;
}
w = 0;
for (ix = a->used - 1; ix >= 0; ix--) {
w = (w << ((fp_word)DIGIT_BIT)) | ((fp_word)a->dp[ix]);
if (w >= b) {
t = (fp_digit)(w / b);
w -= ((fp_word)t) * ((fp_word)b);
} else {
t = 0;
}
if (c != NULL)
q->dp[ix] = (fp_digit)t;
}
if (d != NULL) {
*d = (fp_digit)w;
}
if (c != NULL) {
fp_clamp(q);
fp_copy(q, c);
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(q, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* c = a mod b, 0 <= c < b */
static int fp_mod_d(fp_int *a, fp_digit b, fp_digit *c)
{
return fp_div_d(a, b, NULL, c);
}
int mp_mod_d(fp_int *a, fp_digit b, fp_digit *c)
{
return fp_mod_d(a, b, c);
}
#endif /* WC_MP_TO_RADIX || !NO_DH || !NO_DSA || !NO_RSA */
#if !defined(NO_DH) || !defined(NO_DSA) || !defined(NO_RSA) || \
defined(WOLFSSL_KEY_GEN)
static int fp_isprime_ex(fp_int *a, int t, int* result);
int mp_prime_is_prime(mp_int* a, int t, int* result)
{
return fp_isprime_ex(a, t, result);
}
/* Miller-Rabin test of "a" to the base of "b" as described in
* HAC pp. 139 Algorithm 4.24
*
* Sets result to 0 if definitely composite or 1 if probably prime.
* Randomly the chance of error is no more than 1/4 and often
* very much lower.
*/
static int fp_prime_miller_rabin_ex(fp_int * a, fp_int * b, int *result,
fp_int *n1, fp_int *y, fp_int *r)
{
int s, j;
int err;
/* default */
*result = FP_NO;
/* ensure b > 1 */
if (fp_cmp_d(b, 1) != FP_GT) {
return FP_OKAY;
}
/* get n1 = a - 1 */
fp_copy(a, n1);
err = fp_sub_d(n1, 1, n1);
if (err != FP_OKAY) {
return err;
}
/* set 2**s * r = n1 */
fp_copy(n1, r);
/* count the number of least significant bits
* which are zero
*/
s = fp_cnt_lsb(r);
/* now divide n - 1 by 2**s */
fp_div_2d (r, s, r, NULL);
/* compute y = b**r mod a */
fp_zero(y);
#if (defined(WOLFSSL_HAVE_SP_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)) || \
defined(WOLFSSL_HAVE_SP_DH)
#ifndef WOLFSSL_SP_NO_2048
if (fp_count_bits(a) == 1024)
sp_ModExp_1024(b, r, a, y);
else if (fp_count_bits(a) == 2048)
sp_ModExp_2048(b, r, a, y);
else
#endif
#ifndef WOLFSSL_SP_NO_3072
if (fp_count_bits(a) == 1536)
sp_ModExp_1536(b, r, a, y);
else if (fp_count_bits(a) == 3072)
sp_ModExp_3072(b, r, a, y);
else
#endif
#ifdef WOLFSSL_SP_4096
if (fp_count_bits(a) == 4096)
sp_ModExp_4096(b, r, a, y);
else
#endif
#endif
fp_exptmod(b, r, a, y);
/* if y != 1 and y != n1 do */
if (fp_cmp_d (y, 1) != FP_EQ && fp_cmp (y, n1) != FP_EQ) {
j = 1;
/* while j <= s-1 and y != n1 */
while ((j <= (s - 1)) && fp_cmp (y, n1) != FP_EQ) {
fp_sqrmod (y, a, y);
/* if y == 1 then composite */
if (fp_cmp_d (y, 1) == FP_EQ) {
return FP_OKAY;
}
++j;
}
/* if y != n1 then composite */
if (fp_cmp (y, n1) != FP_EQ) {
return FP_OKAY;
}
}
/* probably prime now */
*result = FP_YES;
return FP_OKAY;
}
static int fp_prime_miller_rabin(fp_int * a, fp_int * b, int *result)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int n1[1], y[1], r[1];
#else
fp_int *n1, *y, *r;
#endif
#ifdef WOLFSSL_SMALL_STACK
n1 = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
if (n1 == NULL) {
return FP_MEM;
}
y = &n1[1]; r = &n1[2];
#endif
fp_init(n1);
fp_init(y);
fp_init(r);
err = fp_prime_miller_rabin_ex(a, b, result, n1, y, r);
fp_clear(n1);
fp_clear(y);
fp_clear(r);
#ifdef WOLFSSL_SMALL_STACK
XFREE(n1, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* a few primes */
static const fp_digit primes[FP_PRIME_SIZE] = {
0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F, 0x0083,
0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
};
int fp_isprime_ex(fp_int *a, int t, int* result)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int b[1];
#else
fp_int *b;
#endif
fp_digit d;
int r, res;
if (t <= 0 || t > FP_PRIME_SIZE) {
*result = FP_NO;
return FP_VAL;
}
if (fp_isone(a)) {
*result = FP_NO;
return FP_OKAY;
}
/* check against primes table */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_cmp_d(a, primes[r]) == FP_EQ) {
*result = FP_YES;
return FP_OKAY;
}
}
/* do trial division */
for (r = 0; r < FP_PRIME_SIZE; r++) {
res = fp_mod_d(a, primes[r], &d);
if (res != MP_OKAY || d == 0) {
*result = FP_NO;
return FP_OKAY;
}
}
#ifdef WOLFSSL_SMALL_STACK
b = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (b == NULL)
return FP_MEM;
#endif
/* now do 't' miller rabins */
fp_init(b);
for (r = 0; r < t; r++) {
fp_set(b, primes[r]);
fp_prime_miller_rabin(a, b, &res);
if (res == FP_NO) {
*result = FP_NO;
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
}
*result = FP_YES;
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
int mp_prime_is_prime_ex(mp_int* a, int t, int* result, WC_RNG* rng)
{
int ret = FP_YES;
if (a == NULL || result == NULL || rng == NULL)
return FP_VAL;
if (fp_isone(a)) {
*result = FP_NO;
return FP_OKAY;
}
if (ret == FP_YES) {
fp_digit d;
int r;
/* check against primes table */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_cmp_d(a, primes[r]) == FP_EQ) {
*result = FP_YES;
return FP_OKAY;
}
}
/* do trial division */
for (r = 0; r < FP_PRIME_SIZE; r++) {
if (fp_mod_d(a, primes[r], &d) == MP_OKAY) {
if (d == 0) {
*result = FP_NO;
return FP_OKAY;
}
}
else
return FP_VAL;
}
}
#ifndef WC_NO_RNG
/* now do a miller rabin with up to t random numbers, this should
* give a (1/4)^t chance of a false prime. */
if (ret == FP_YES) {
#ifndef WOLFSSL_SMALL_STACK
fp_int b[1], c[1], n1[1], y[1], r[1];
byte base[FP_MAX_PRIME_SIZE];
#else
fp_int *b, *c, *n1, *y, *r;
byte* base;
#endif
word32 baseSz;
int err;
baseSz = fp_count_bits(a);
/* The base size is the number of bits / 8. One is added if the number
* of bits isn't an even 8. */
baseSz = (baseSz / 8) + ((baseSz % 8) ? 1 : 0);
#ifndef WOLFSSL_SMALL_STACK
if (baseSz > sizeof(base))
return FP_MEM;
#else
base = (byte*)XMALLOC(baseSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
if (base == NULL)
return FP_MEM;
b = (fp_int*)XMALLOC(sizeof(fp_int) * 5, NULL, DYNAMIC_TYPE_BIGINT);
if (b == NULL) {
return FP_MEM;
}
c = &b[1]; n1 = &b[2]; y= &b[3]; r = &b[4];
#endif
fp_init(b);
fp_init(c);
fp_init(n1);
fp_init(y);
fp_init(r);
err = fp_sub_d(a, 2, c);
if (err != FP_OKAY) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
while (t > 0) {
if ((err = wc_RNG_GenerateBlock(rng, base, baseSz)) != 0) {
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
return err;
}
fp_read_unsigned_bin(b, base, baseSz);
if (fp_cmp_d(b, 2) != FP_GT || fp_cmp(b, c) != FP_LT) {
continue;
}
fp_prime_miller_rabin_ex(a, b, &ret, n1, y, r);
if (ret == FP_NO)
break;
fp_zero(b);
t--;
}
fp_clear(n1);
fp_clear(y);
fp_clear(r);
fp_clear(b);
fp_clear(c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(b, NULL, DYNAMIC_TYPE_BIGINT);
XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
}
#else
(void)t;
#endif /* !WC_NO_RNG */
*result = ret;
return FP_OKAY;
}
#endif /* !NO_RSA || !NO_DSA || !NO_DH || WOLFSSL_KEY_GEN */
#ifdef WOLFSSL_KEY_GEN
static int fp_gcd(fp_int *a, fp_int *b, fp_int *c);
static int fp_lcm(fp_int *a, fp_int *b, fp_int *c);
static int fp_randprime(fp_int* N, int len, WC_RNG* rng, void* heap);
int mp_gcd(fp_int *a, fp_int *b, fp_int *c)
{
return fp_gcd(a, b, c);
}
int mp_lcm(fp_int *a, fp_int *b, fp_int *c)
{
return fp_lcm(a, b, c);
}
int mp_rand_prime(mp_int* N, int len, WC_RNG* rng, void* heap)
{
int err;
err = fp_randprime(N, len, rng, heap);
switch(err) {
case FP_VAL:
return MP_VAL;
case FP_MEM:
return MP_MEM;
default:
break;
}
return MP_OKAY;
}
int mp_exch (mp_int * a, mp_int * b)
{
return fp_exch(a, b);
}
int fp_randprime(fp_int* N, int len, WC_RNG* rng, void* heap)
{
static const int USE_BBS = 1;
int err, type;
int isPrime = FP_YES;
/* Assume the candidate is probably prime and then test until
* it is proven composite. */
byte* buf;
(void)heap;
/* get type */
if (len < 0) {
type = USE_BBS;
len = -len;
} else {
type = 0;
}
/* allow sizes between 2 and 512 bytes for a prime size */
if (len < 2 || len > 512) {
return FP_VAL;
}
/* allocate buffer to work with */
buf = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_TMP_BUFFER);
if (buf == NULL) {
return FP_MEM;
}
XMEMSET(buf, 0, len);
do {
#ifdef SHOW_GEN
printf(".");
fflush(stdout);
#endif
/* generate value */
err = wc_RNG_GenerateBlock(rng, buf, len);
if (err != 0) {
XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
return FP_VAL;
}
/* munge bits */
buf[0] |= 0x80 | 0x40;
buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00);
/* load value */
fp_read_unsigned_bin(N, buf, len);
/* test */
/* Running Miller-Rabin up to 3 times gives us a 2^{-80} chance
* of a 1024-bit candidate being a false positive, when it is our
* prime candidate. (Note 4.49 of Handbook of Applied Cryptography.)
* Using 8 because we've always used 8 */
mp_prime_is_prime_ex(N, 8, &isPrime, rng);
} while (isPrime == FP_NO);
XMEMSET(buf, 0, len);
XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
return FP_OKAY;
}
/* c = [a, b] */
int fp_lcm(fp_int *a, fp_int *b, fp_int *c)
{
int err;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[2];
#else
fp_int *t;
#endif
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int) * 2, NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL) {
return FP_MEM;
}
#endif
fp_init(&t[0]);
fp_init(&t[1]);
err = fp_gcd(a, b, &t[0]);
if (err == FP_OKAY) {
if (fp_cmp_mag(a, b) == FP_GT) {
err = fp_div(a, &t[0], &t[1], NULL);
if (err == FP_OKAY)
err = fp_mul(b, &t[1], c);
} else {
err = fp_div(b, &t[0], &t[1], NULL);
if (err == FP_OKAY)
err = fp_mul(a, &t[1], c);
}
}
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return err;
}
/* c = (a, b) */
int fp_gcd(fp_int *a, fp_int *b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int u[1], v[1], r[1];
#else
fp_int *u, *v, *r;
#endif
/* either zero than gcd is the largest */
if (fp_iszero (a) == FP_YES && fp_iszero (b) == FP_NO) {
fp_abs (b, c);
return FP_OKAY;
}
if (fp_iszero (a) == FP_NO && fp_iszero (b) == FP_YES) {
fp_abs (a, c);
return FP_OKAY;
}
/* optimized. At this point if a == 0 then
* b must equal zero too
*/
if (fp_iszero (a) == FP_YES) {
fp_zero(c);
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
u = (fp_int*)XMALLOC(sizeof(fp_int) * 3, NULL, DYNAMIC_TYPE_BIGINT);
if (u == NULL) {
return FP_MEM;
}
v = &u[1]; r = &u[2];
#endif
/* sort inputs */
if (fp_cmp_mag(a, b) != FP_LT) {
fp_init_copy(u, a);
fp_init_copy(v, b);
} else {
fp_init_copy(u, b);
fp_init_copy(v, a);
}
u->sign = FP_ZPOS;
v->sign = FP_ZPOS;
fp_init(r);
while (fp_iszero(v) == FP_NO) {
fp_mod(u, v, r);
fp_copy(v, u);
fp_copy(r, v);
}
fp_copy(u, c);
#ifdef WOLFSSL_SMALL_STACK
XFREE(u, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#endif /* WOLFSSL_KEY_GEN */
#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(OPENSSL_EXTRA) || \
defined(WC_RSA_BLINDING) || !defined(NO_DSA) || \
(!defined(NO_RSA) && !defined(NO_RSA_BOUNDS_CHECK))
/* c = a + b */
void fp_add_d(fp_int *a, fp_digit b, fp_int *c)
{
#ifndef WOLFSSL_SMALL_STACK
fp_int tmp;
fp_init(&tmp);
fp_set(&tmp, b);
fp_add(a, &tmp, c);
#else
int i;
fp_word t = b;
fp_copy(a, c);
for (i = 0; t != 0 && i < FP_SIZE && i < c->used; i++) {
t += c->dp[i];
c->dp[i] = (fp_digit)t;
t >>= DIGIT_BIT;
}
if (i == c->used && i < FP_SIZE && t != 0) {
c->dp[i] = t;
c->used++;
}
#endif
}
/* external compatibility */
int mp_add_d(fp_int *a, fp_digit b, fp_int *c)
{
fp_add_d(a, b, c);
return MP_OKAY;
}
#endif /* HAVE_ECC || !NO_PWDBASED || OPENSSL_EXTRA || WC_RSA_BLINDING ||
!NO_DSA || (!NO_RSA && !NO_RSA_BOUNDS_CHECK) */
#if !defined(NO_DSA) || defined(HAVE_ECC) || defined(WOLFSSL_KEY_GEN) || \
defined(HAVE_COMP_KEY) || defined(WOLFSSL_DEBUG_MATH) || \
defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA) || defined(WC_MP_TO_RADIX)
/* chars used in radix conversions */
static const char* const fp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz+/";
#endif
#if !defined(NO_DSA) || defined(HAVE_ECC)
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
static int fp_read_radix_16(fp_int *a, const char *str)
{
int i, j, k, neg;
char ch;
/* if the leading digit is a
* minus set the sign to negative.
*/
if (*str == '-') {
++str;
neg = FP_NEG;
} else {
neg = FP_ZPOS;
}
j = 0;
k = 0;
for (i = (int)(XSTRLEN(str) - 1); i >= 0; i--) {
ch = str[i];
if (ch >= '0' && ch <= '9')
ch -= '0';
else if (ch >= 'A' && ch <= 'F')
ch -= 'A' - 10;
else if (ch >= 'a' && ch <= 'f')
ch -= 'a' - 10;
else
return FP_VAL;
a->dp[k] |= ((fp_digit)ch) << j;
j += 4;
k += j == DIGIT_BIT;
j &= DIGIT_BIT - 1;
}
a->used = k + 1;
fp_clamp(a);
/* set the sign only if a != 0 */
if (fp_iszero(a) != FP_YES) {
a->sign = neg;
}
return FP_OKAY;
}
#endif
static int fp_read_radix(fp_int *a, const char *str, int radix)
{
int y, neg;
char ch;
/* set the integer to the default of zero */
fp_zero (a);
#if DIGIT_BIT == 64 || DIGIT_BIT == 32
if (radix == 16)
return fp_read_radix_16(a, str);
#endif
/* make sure the radix is ok */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
/* if the leading digit is a
* minus set the sign to negative.
*/
if (*str == '-') {
++str;
neg = FP_NEG;
} else {
neg = FP_ZPOS;
}
/* process each digit of the string */
while (*str) {
/* if the radix <= 36 the conversion is case insensitive
* this allows numbers like 1AB and 1ab to represent the same value
* [e.g. in hex]
*/
ch = (char)((radix <= 36) ? XTOUPPER((unsigned char)*str) : *str);
for (y = 0; y < 64; y++) {
if (ch == fp_s_rmap[y]) {
break;
}
}
/* if the char was found in the map
* and is less than the given radix add it
* to the number, otherwise exit the loop.
*/
if (y < radix) {
fp_mul_d (a, (fp_digit) radix, a);
fp_add_d (a, (fp_digit) y, a);
} else {
break;
}
++str;
}
/* set the sign only if a != 0 */
if (fp_iszero(a) != FP_YES) {
a->sign = neg;
}
return FP_OKAY;
}
/* fast math conversion */
int mp_read_radix(mp_int *a, const char *str, int radix)
{
return fp_read_radix(a, str, radix);
}
#endif /* !defined(NO_DSA) || defined(HAVE_ECC) */
#ifdef HAVE_ECC
/* fast math conversion */
int mp_sqr(fp_int *A, fp_int *B)
{
return fp_sqr(A, B);
}
/* fast math conversion */
int mp_montgomery_reduce(fp_int *a, fp_int *m, fp_digit mp)
{
return fp_montgomery_reduce(a, m, mp);
}
/* fast math conversion */
int mp_montgomery_setup(fp_int *a, fp_digit *rho)
{
return fp_montgomery_setup(a, rho);
}
int mp_div_2(fp_int * a, fp_int * b)
{
fp_div_2(a, b);
return MP_OKAY;
}
int mp_init_copy(fp_int * a, fp_int * b)
{
fp_init_copy(a, b);
return MP_OKAY;
}
#ifdef HAVE_COMP_KEY
int mp_cnt_lsb(fp_int* a)
{
return fp_cnt_lsb(a);
}
#endif /* HAVE_COMP_KEY */
#endif /* HAVE_ECC */
#if defined(HAVE_ECC) || !defined(NO_RSA) || !defined(NO_DSA) || \
defined(WOLFSSL_KEY_GEN)
/* fast math conversion */
int mp_set(fp_int *a, fp_digit b)
{
fp_set(a,b);
return MP_OKAY;
}
#endif
#ifdef WC_MP_TO_RADIX
/* returns size of ASCII representation */
int mp_radix_size (mp_int *a, int radix, int *size)
{
int res, digs;
fp_digit d;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
*size = 0;
/* special case for binary */
if (radix == 2) {
*size = fp_count_bits (a) + (a->sign == FP_NEG ? 1 : 0) + 1;
return FP_YES;
}
/* make sure the radix is in range */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
if (fp_iszero(a) == MP_YES) {
*size = 2;
return FP_OKAY;
}
/* digs is the digit count */
digs = 0;
/* if it's negative add one for the sign */
if (a->sign == FP_NEG) {
++digs;
}
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
/* init a copy of the input */
fp_init_copy (t, a);
/* force temp to positive */
t->sign = FP_ZPOS;
/* fetch out all of the digits */
while (fp_iszero (t) == FP_NO) {
if ((res = fp_div_d (t, (mp_digit) radix, t, &d)) != FP_OKAY) {
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return res;
}
++digs;
}
fp_zero (t);
/* return digs + 1, the 1 is for the NULL byte that would be required. */
*size = digs + 1;
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
/* stores a bignum as a ASCII string in a given radix (2..64) */
int mp_toradix (mp_int *a, char *str, int radix)
{
int res, digs;
fp_digit d;
char *_s = str;
#ifndef WOLFSSL_SMALL_STACK
fp_int t[1];
#else
fp_int *t;
#endif
/* check range of the radix */
if (radix < 2 || radix > 64) {
return FP_VAL;
}
/* quick out if its zero */
if (fp_iszero(a) == FP_YES) {
*str++ = '0';
*str = '\0';
return FP_OKAY;
}
#ifdef WOLFSSL_SMALL_STACK
t = (fp_int*)XMALLOC(sizeof(fp_int), NULL, DYNAMIC_TYPE_BIGINT);
if (t == NULL)
return FP_MEM;
#endif
/* init a copy of the input */
fp_init_copy (t, a);
/* if it is negative output a - */
if (t->sign == FP_NEG) {
++_s;
*str++ = '-';
t->sign = FP_ZPOS;
}
digs = 0;
while (fp_iszero (t) == FP_NO) {
if ((res = fp_div_d (t, (fp_digit) radix, t, &d)) != FP_OKAY) {
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return res;
}
*str++ = fp_s_rmap[d];
++digs;
}
#ifndef WC_DISABLE_RADIX_ZERO_PAD
/* For hexadecimal output, add zero padding when number of digits is odd */
if ((digs & 1) && (radix == 16)) {
*str++ = fp_s_rmap[0];
++digs;
}
#endif
/* reverse the digits of the string. In this case _s points
* to the first digit [excluding the sign] of the number]
*/
fp_reverse ((unsigned char *)_s, digs);
/* append a NULL so the string is properly terminated */
*str = '\0';
fp_zero (t);
#ifdef WOLFSSL_SMALL_STACK
XFREE(t, NULL, DYNAMIC_TYPE_BIGINT);
#endif
return FP_OKAY;
}
#ifdef WOLFSSL_DEBUG_MATH
void mp_dump(const char* desc, mp_int* a, byte verbose)
{
char buffer[FP_SIZE * sizeof(fp_digit) * 2];
int size;
#if defined(ALT_ECC_SIZE) || defined(HAVE_WOLF_BIGINT)
size = a->size;
#else
size = FP_SIZE;
#endif
printf("%s: ptr=%p, used=%d, sign=%d, size=%d, fpd=%d\n",
desc, a, a->used, a->sign, size, (int)sizeof(fp_digit));
mp_tohex(a, buffer);
printf(" %s\n ", buffer);
if (verbose) {
int i;
for(i=0; i<size * (int)sizeof(fp_digit); i++) {
printf("%x ", *(((byte*)a->dp) + i));
}
printf("\n");
}
}
#endif /* WOLFSSL_DEBUG_MATH */
#endif /* WC_MP_TO_RADIX */
int mp_abs(mp_int* a, mp_int* b)
{
fp_abs(a, b);
return FP_OKAY;
}
int mp_lshd (mp_int * a, int b)
{
fp_lshd(a, b);
return FP_OKAY;
}
#endif /* USE_FAST_MATH */
| ./CrossVul/dataset_final_sorted/CWE-326/c/good_3970_1 |
crossvul-cpp_data_bad_3963_0 | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2015, Atmel 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:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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 "common.h"
#include "secure.h"
#include "aes.h"
#include "debug.h"
#include "string.h"
#include "autoconf.h"
static inline void init_keys(at91_aes_key_size_t *key_size,
unsigned int *cipher_key,
unsigned int *cmac_key,
unsigned int *iv)
{
#if defined(CONFIG_AES_KEY_SIZE_128)
*key_size = AT91_AES_KEY_SIZE_128;
#elif defined(CONFIG_AES_KEY_SIZE_192)
*key_size = AT91_AES_KEY_SIZE_192;
#elif defined(CONFIG_AES_KEY_SIZE_256)
*key_size = AT91_AES_KEY_SIZE_256;
#else
#error "bad AES key size"
#endif
iv[0] = CONFIG_AES_IV_WORD0;
iv[1] = CONFIG_AES_IV_WORD1;
iv[2] = CONFIG_AES_IV_WORD2;
iv[3] = CONFIG_AES_IV_WORD3;
cipher_key[0] = CONFIG_AES_CIPHER_KEY_WORD0;
cmac_key[0] = CONFIG_AES_CMAC_KEY_WORD0;
cipher_key[1] = CONFIG_AES_CIPHER_KEY_WORD1;
cmac_key[1] = CONFIG_AES_CMAC_KEY_WORD1;
cipher_key[2] = CONFIG_AES_CIPHER_KEY_WORD2;
cmac_key[2] = CONFIG_AES_CMAC_KEY_WORD2;
cipher_key[3] = CONFIG_AES_CIPHER_KEY_WORD3;
cmac_key[3] = CONFIG_AES_CMAC_KEY_WORD3;
#if defined(CONFIG_AES_KEY_SIZE_192) || defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[4] = CONFIG_AES_CIPHER_KEY_WORD4;
cmac_key[4] = CONFIG_AES_CMAC_KEY_WORD4;
cipher_key[5] = CONFIG_AES_CIPHER_KEY_WORD5;
cmac_key[5] = CONFIG_AES_CMAC_KEY_WORD5;
#endif
#if defined(CONFIG_AES_KEY_SIZE_256)
cipher_key[6] = CONFIG_AES_CIPHER_KEY_WORD6;
cmac_key[6] = CONFIG_AES_CMAC_KEY_WORD6;
cipher_key[7] = CONFIG_AES_CIPHER_KEY_WORD7;
cmac_key[7] = CONFIG_AES_CMAC_KEY_WORD7;
#endif
}
int secure_decrypt(void *data, unsigned int data_length, int is_signed)
{
at91_aes_key_size_t key_size;
unsigned int cmac_key[8], cipher_key[8];
unsigned int iv[AT91_AES_IV_SIZE_WORD];
unsigned int computed_cmac[AT91_AES_BLOCK_SIZE_WORD];
unsigned int fixed_length;
const unsigned int *cmac;
int rc = -1;
/* Init keys */
init_keys(&key_size, cipher_key, cmac_key, iv);
/* Init periph */
at91_aes_init();
/* Check signature if required */
if (is_signed) {
/* Compute the CMAC */
if (at91_aes_cmac(data_length, data, computed_cmac,
key_size, cmac_key))
goto exit;
/* Check the CMAC */
fixed_length = at91_aes_roundup(data_length);
cmac = (const unsigned int *)((char *)data + fixed_length);
if (!consttime_memequal(cmac, computed_cmac, AT91_AES_BLOCK_SIZE_BYTE))
goto exit;
}
/* Decrypt the whole file */
if (at91_aes_cbc(data_length, data, data, 0,
key_size, cipher_key, iv))
goto exit;
rc = 0;
exit:
/* Reset periph */
at91_aes_cleanup();
/* Reset keys */
memset(cmac_key, 0, sizeof(cmac_key));
memset(cipher_key, 0, sizeof(cipher_key));
memset(iv, 0, sizeof(iv));
return rc;
}
int secure_check(void *data)
{
const at91_secure_header_t *header;
void *file;
if (secure_decrypt(data, sizeof(*header), 0))
return -1;
header = (const at91_secure_header_t *)data;
if (header->magic != AT91_SECURE_MAGIC)
return -1;
file = (unsigned char *)data + sizeof(*header);
return secure_decrypt(file, header->file_size, 1);
}
| ./CrossVul/dataset_final_sorted/CWE-326/c/bad_3963_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.